python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher <[email protected]>
*
* Fix by Harrison Xing <[email protected]>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <[email protected]>.
* xattr consolidation Copyright (c) 2004 James Morris <[email protected]>,
* Red Hat Inc.
*
*/
/*
* Extended attributes are stored on disk blocks allocated outside of
* any inode. The i_file_acl field is then made to point to this allocated
* block. If all extended attributes of an inode are identical, these
* inodes may share the same extended attribute block. Such situations
* are automatically detected by keeping a cache of recent attribute block
* numbers and hashes over the block's contents in memory.
*
*
* Extended attribute block layout:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The block header is followed by multiple entry descriptors. These entry
* descriptors are variable in size, and aligned to EXT2_XATTR_PAD
* byte boundaries. The entry descriptors are sorted by attribute name,
* so that two extended attribute blocks can be compared efficiently.
*
* Attribute values are aligned to the end of the block, stored in
* no specific order. They are also padded to EXT2_XATTR_PAD byte
* boundaries. No additional gaps are left between them.
*
* Locking strategy
* ----------------
* EXT2_I(inode)->i_file_acl is protected by EXT2_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count will change. Multiple writers to an EA block are synchronized
* by the bh lock. No more than a single bh lock is held at any time
* to avoid deadlocks.
*/
#include <linux/buffer_head.h>
#include <linux/init.h>
#include <linux/printk.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/rwsem.h>
#include <linux/security.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
#define HDR(bh) ((struct ext2_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext2_xattr_entry *)(ptr))
#define FIRST_ENTRY(bh) ENTRY(HDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#ifdef EXT2_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%ld: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
printk(KERN_DEBUG "block %pg:%lu: ", \
bh->b_bdev, (unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(inode, f...) no_printk(f)
# define ea_bdebug(bh, f...) no_printk(f)
#endif
static int ext2_xattr_set2(struct inode *, struct buffer_head *,
struct ext2_xattr_header *);
static int ext2_xattr_cache_insert(struct mb_cache *, struct buffer_head *);
static struct buffer_head *ext2_xattr_cache_find(struct inode *,
struct ext2_xattr_header *);
static void ext2_xattr_rehash(struct ext2_xattr_header *,
struct ext2_xattr_entry *);
static const struct xattr_handler *ext2_xattr_handler_map[] = {
[EXT2_XATTR_INDEX_USER] = &ext2_xattr_user_handler,
#ifdef CONFIG_EXT2_FS_POSIX_ACL
[EXT2_XATTR_INDEX_POSIX_ACL_ACCESS] = &nop_posix_acl_access,
[EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT] = &nop_posix_acl_default,
#endif
[EXT2_XATTR_INDEX_TRUSTED] = &ext2_xattr_trusted_handler,
#ifdef CONFIG_EXT2_FS_SECURITY
[EXT2_XATTR_INDEX_SECURITY] = &ext2_xattr_security_handler,
#endif
};
const struct xattr_handler *ext2_xattr_handlers[] = {
&ext2_xattr_user_handler,
&ext2_xattr_trusted_handler,
#ifdef CONFIG_EXT2_FS_SECURITY
&ext2_xattr_security_handler,
#endif
NULL
};
#define EA_BLOCK_CACHE(inode) (EXT2_SB(inode->i_sb)->s_ea_block_cache)
static inline const char *ext2_xattr_prefix(int name_index,
struct dentry *dentry)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext2_xattr_handler_map))
handler = ext2_xattr_handler_map[name_index];
if (!xattr_handler_can_list(handler, dentry))
return NULL;
return xattr_prefix(handler);
}
static bool
ext2_xattr_header_valid(struct ext2_xattr_header *header)
{
if (header->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
header->h_blocks != cpu_to_le32(1))
return false;
return true;
}
static bool
ext2_xattr_entry_valid(struct ext2_xattr_entry *entry,
char *end, size_t end_offs)
{
struct ext2_xattr_entry *next;
size_t size;
next = EXT2_XATTR_NEXT(entry);
if ((char *)next >= end)
return false;
if (entry->e_value_block != 0)
return false;
size = le32_to_cpu(entry->e_value_size);
if (size > end_offs ||
le16_to_cpu(entry->e_value_offs) + size > end_offs)
return false;
return true;
}
static int
ext2_xattr_cmp_entry(int name_index, size_t name_len, const char *name,
struct ext2_xattr_entry *entry)
{
int cmp;
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
return cmp;
}
/*
* ext2_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext2_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext2_xattr_entry *entry;
size_t name_len, size;
char *end;
int error, not_found;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
if (name_len > 255)
return -ERANGE;
down_read(&EXT2_I(inode)->xattr_sem);
error = -ENODATA;
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
end = bh->b_data + bh->b_size;
if (!ext2_xattr_header_valid(HDR(bh))) {
bad_block:
ext2_error(inode->i_sb, "ext2_xattr_get",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* find named attribute */
entry = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(entry)) {
if (!ext2_xattr_entry_valid(entry, end,
inode->i_sb->s_blocksize))
goto bad_block;
not_found = ext2_xattr_cmp_entry(name_index, name_len, name,
entry);
if (!not_found)
goto found;
if (not_found < 0)
break;
entry = EXT2_XATTR_NEXT(entry);
}
if (ext2_xattr_cache_insert(ea_block_cache, bh))
ea_idebug(inode, "cache insert failed");
error = -ENODATA;
goto cleanup;
found:
size = le32_to_cpu(entry->e_value_size);
if (ext2_xattr_cache_insert(ea_block_cache, bh))
ea_idebug(inode, "cache insert failed");
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
/* return value of attribute */
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
up_read(&EXT2_I(inode)->xattr_sem);
return error;
}
/*
* ext2_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
struct ext2_xattr_entry *entry;
char *end;
size_t rest = buffer_size;
int error;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
down_read(&EXT2_I(inode)->xattr_sem);
error = 0;
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
end = bh->b_data + bh->b_size;
if (!ext2_xattr_header_valid(HDR(bh))) {
bad_block:
ext2_error(inode->i_sb, "ext2_xattr_list",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* check the on-disk data structure */
entry = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(entry)) {
if (!ext2_xattr_entry_valid(entry, end,
inode->i_sb->s_blocksize))
goto bad_block;
entry = EXT2_XATTR_NEXT(entry);
}
if (ext2_xattr_cache_insert(ea_block_cache, bh))
ea_idebug(inode, "cache insert failed");
/* list the attribute names */
for (entry = FIRST_ENTRY(bh); !IS_LAST_ENTRY(entry);
entry = EXT2_XATTR_NEXT(entry)) {
const char *prefix;
prefix = ext2_xattr_prefix(entry->e_name_index, dentry);
if (prefix) {
size_t prefix_len = strlen(prefix);
size_t size = prefix_len + entry->e_name_len + 1;
if (buffer) {
if (size > rest) {
error = -ERANGE;
goto cleanup;
}
memcpy(buffer, prefix, prefix_len);
buffer += prefix_len;
memcpy(buffer, entry->e_name, entry->e_name_len);
buffer += entry->e_name_len;
*buffer++ = 0;
}
rest -= size;
}
}
error = buffer_size - rest; /* total size */
cleanup:
brelse(bh);
up_read(&EXT2_I(inode)->xattr_sem);
return error;
}
/*
* Inode operation listxattr()
*
* d_inode(dentry)->i_mutex: don't care
*/
ssize_t
ext2_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext2_xattr_list(dentry, buffer, size);
}
/*
* If the EXT2_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext2_xattr_update_super_block(struct super_block *sb)
{
if (EXT2_HAS_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR))
return;
spin_lock(&EXT2_SB(sb)->s_lock);
ext2_update_dynamic_rev(sb);
EXT2_SET_COMPAT_FEATURE(sb, EXT2_FEATURE_COMPAT_EXT_ATTR);
spin_unlock(&EXT2_SB(sb)->s_lock);
mark_buffer_dirty(EXT2_SB(sb)->s_sbh);
}
/*
* ext2_xattr_set()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
ext2_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *bh = NULL;
struct ext2_xattr_header *header = NULL;
struct ext2_xattr_entry *here = NULL, *last = NULL;
size_t name_len, free, min_offs = sb->s_blocksize;
int not_found = 1, error;
char *end;
/*
* header -- Points either into bh, or to a temporarily
* allocated buffer.
* here -- The named entry found, or the place for inserting, within
* the block pointed to by header.
* last -- Points right after the last named entry within the block
* pointed to by header.
* min_offs -- The offset of the first value (values are aligned
* towards the end of the block).
* end -- Points right after the block pointed to by header.
*/
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
name_index, name, value, (long)value_len);
if (value == NULL)
value_len = 0;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
if (name_len > 255 || value_len > sb->s_blocksize)
return -ERANGE;
error = dquot_initialize(inode);
if (error)
return error;
down_write(&EXT2_I(inode)->xattr_sem);
if (EXT2_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bh = sb_bread(sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)),
le32_to_cpu(HDR(bh)->h_refcount));
header = HDR(bh);
end = bh->b_data + bh->b_size;
if (!ext2_xattr_header_valid(header)) {
bad_block:
ext2_error(sb, "ext2_xattr_set",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/*
* Find the named attribute. If not found, 'here' will point
* to entry where the new attribute should be inserted to
* maintain sorting.
*/
last = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(last)) {
if (!ext2_xattr_entry_valid(last, end, sb->s_blocksize))
goto bad_block;
if (last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
if (not_found > 0) {
not_found = ext2_xattr_cmp_entry(name_index,
name_len,
name, last);
if (not_found <= 0)
here = last;
}
last = EXT2_XATTR_NEXT(last);
}
if (not_found > 0)
here = last;
/* Check whether we have enough space left. */
free = min_offs - ((char*)last - (char*)header) - sizeof(__u32);
} else {
/* We will use a new extended attribute block. */
free = sb->s_blocksize -
sizeof(struct ext2_xattr_header) - sizeof(__u32);
}
if (not_found) {
/* Request to remove a nonexistent attribute? */
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (value == NULL)
goto cleanup;
} else {
/* Request to create an existing attribute? */
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
free += EXT2_XATTR_SIZE(le32_to_cpu(here->e_value_size));
free += EXT2_XATTR_LEN(name_len);
}
error = -ENOSPC;
if (free < EXT2_XATTR_LEN(name_len) + EXT2_XATTR_SIZE(value_len))
goto cleanup;
/* Here we know that we can set the new attribute. */
if (header) {
int offset;
lock_buffer(bh);
if (header->h_refcount == cpu_to_le32(1)) {
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *oe;
oe = mb_cache_entry_delete_or_get(EA_BLOCK_CACHE(inode),
hash, bh->b_blocknr);
if (!oe) {
ea_bdebug(bh, "modifying in-place");
goto update_block;
}
/*
* Someone is trying to reuse the block, leave it alone
*/
mb_cache_entry_put(EA_BLOCK_CACHE(inode), oe);
}
unlock_buffer(bh);
ea_bdebug(bh, "cloning");
header = kmemdup(HDR(bh), bh->b_size, GFP_KERNEL);
error = -ENOMEM;
if (header == NULL)
goto cleanup;
header->h_refcount = cpu_to_le32(1);
offset = (char *)here - bh->b_data;
here = ENTRY((char *)header + offset);
offset = (char *)last - bh->b_data;
last = ENTRY((char *)header + offset);
} else {
/* Allocate a buffer where we construct the new block. */
header = kzalloc(sb->s_blocksize, GFP_KERNEL);
error = -ENOMEM;
if (header == NULL)
goto cleanup;
header->h_magic = cpu_to_le32(EXT2_XATTR_MAGIC);
header->h_blocks = header->h_refcount = cpu_to_le32(1);
last = here = ENTRY(header+1);
}
update_block:
/* Iff we are modifying the block in-place, bh is locked here. */
if (not_found) {
/* Insert the new name. */
size_t size = EXT2_XATTR_LEN(name_len);
size_t rest = (char *)last - (char *)here;
memmove((char *)here + size, here, rest);
memset(here, 0, size);
here->e_name_index = name_index;
here->e_name_len = name_len;
memcpy(here->e_name, name, name_len);
} else {
if (here->e_value_size) {
char *first_val = (char *)header + min_offs;
size_t offs = le16_to_cpu(here->e_value_offs);
char *val = (char *)header + offs;
size_t size = EXT2_XATTR_SIZE(
le32_to_cpu(here->e_value_size));
if (size == EXT2_XATTR_SIZE(value_len)) {
/* The old and the new value have the same
size. Just replace. */
here->e_value_size = cpu_to_le32(value_len);
memset(val + size - EXT2_XATTR_PAD, 0,
EXT2_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, value, value_len);
goto skip_replace;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
min_offs += size;
/* Adjust all value offsets. */
last = ENTRY(header+1);
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT2_XATTR_NEXT(last);
}
here->e_value_offs = 0;
}
if (value == NULL) {
/* Remove the old name. */
size_t size = EXT2_XATTR_LEN(name_len);
last = ENTRY((char *)last - size);
memmove(here, (char*)here + size,
(char*)last - (char*)here);
memset(last, 0, size);
}
}
if (value != NULL) {
/* Insert the new value. */
here->e_value_size = cpu_to_le32(value_len);
if (value_len) {
size_t size = EXT2_XATTR_SIZE(value_len);
char *val = (char *)header + min_offs - size;
here->e_value_offs =
cpu_to_le16((char *)val - (char *)header);
memset(val + size - EXT2_XATTR_PAD, 0,
EXT2_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, value, value_len);
}
}
skip_replace:
if (IS_LAST_ENTRY(ENTRY(header+1))) {
/* This block is now empty. */
if (bh && header == HDR(bh))
unlock_buffer(bh); /* we were modifying in-place. */
error = ext2_xattr_set2(inode, bh, NULL);
} else {
ext2_xattr_rehash(header, here);
if (bh && header == HDR(bh))
unlock_buffer(bh); /* we were modifying in-place. */
error = ext2_xattr_set2(inode, bh, header);
}
cleanup:
if (!(bh && header == HDR(bh)))
kfree(header);
brelse(bh);
up_write(&EXT2_I(inode)->xattr_sem);
return error;
}
static void ext2_xattr_release_block(struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
retry_ref:
lock_buffer(bh);
if (HDR(bh)->h_refcount == cpu_to_le32(1)) {
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
struct mb_cache_entry *oe;
/*
* This must happen under buffer lock to properly
* serialize with ext2_xattr_set() reusing the block.
*/
oe = mb_cache_entry_delete_or_get(ea_block_cache, hash,
bh->b_blocknr);
if (oe) {
/*
* Someone is trying to reuse the block. Wait
* and retry.
*/
unlock_buffer(bh);
mb_cache_entry_wait_unused(oe);
mb_cache_entry_put(ea_block_cache, oe);
goto retry_ref;
}
/* Free the old block. */
ea_bdebug(bh, "freeing");
ext2_free_blocks(inode, bh->b_blocknr, 1);
/* We let our caller release bh, so we
* need to duplicate the buffer before. */
get_bh(bh);
bforget(bh);
unlock_buffer(bh);
} else {
/* Decrement the refcount only. */
le32_add_cpu(&HDR(bh)->h_refcount, -1);
dquot_free_block(inode, 1);
mark_buffer_dirty(bh);
unlock_buffer(bh);
ea_bdebug(bh, "refcount now=%d",
le32_to_cpu(HDR(bh)->h_refcount));
if (IS_SYNC(inode))
sync_dirty_buffer(bh);
}
}
/*
* Second half of ext2_xattr_set(): Update the file system.
*/
static int
ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh,
struct ext2_xattr_header *header)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
int error;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
if (header) {
new_bh = ext2_xattr_cache_find(inode, header);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == old_bh) {
ea_bdebug(new_bh, "keeping this block");
} else {
/* The old block is released after updating
the inode. */
ea_bdebug(new_bh, "reusing block");
error = dquot_alloc_block(inode, 1);
if (error) {
unlock_buffer(new_bh);
goto cleanup;
}
le32_add_cpu(&HDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "refcount now=%d",
le32_to_cpu(HDR(new_bh)->h_refcount));
}
unlock_buffer(new_bh);
} else if (old_bh && header == HDR(old_bh)) {
/* Keep this block. No need to lock the block as we
don't need to change the reference count. */
new_bh = old_bh;
get_bh(new_bh);
ext2_xattr_cache_insert(ea_block_cache, new_bh);
} else {
/* We need to allocate a new block */
ext2_fsblk_t goal = ext2_group_first_block_no(sb,
EXT2_I(inode)->i_block_group);
unsigned long count = 1;
ext2_fsblk_t block = ext2_new_blocks(inode, goal,
&count, &error,
EXT2_ALLOC_NORESERVE);
if (error)
goto cleanup;
ea_idebug(inode, "creating block %lu", block);
new_bh = sb_getblk(sb, block);
if (unlikely(!new_bh)) {
ext2_free_blocks(inode, block, 1);
mark_inode_dirty(inode);
error = -ENOMEM;
goto cleanup;
}
lock_buffer(new_bh);
memcpy(new_bh->b_data, header, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext2_xattr_cache_insert(ea_block_cache, new_bh);
ext2_xattr_update_super_block(sb);
}
mark_buffer_dirty(new_bh);
if (IS_SYNC(inode)) {
sync_dirty_buffer(new_bh);
error = -EIO;
if (buffer_req(new_bh) && !buffer_uptodate(new_bh))
goto cleanup;
}
}
/* Update the inode. */
EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
inode_set_ctime_current(inode);
if (IS_SYNC(inode)) {
error = sync_inode_metadata(inode, 1);
/* In case sync failed due to ENOSPC the inode was actually
* written (only some dirty data were not) so we just proceed
* as if nothing happened and cleanup the unused block */
if (error && error != -ENOSPC) {
if (new_bh && new_bh != old_bh) {
dquot_free_block_nodirty(inode, 1);
mark_inode_dirty(inode);
}
goto cleanup;
}
} else
mark_inode_dirty(inode);
error = 0;
if (old_bh && old_bh != new_bh) {
/*
* If there was an old block and we are no longer using it,
* release the old block.
*/
ext2_xattr_release_block(inode, old_bh);
}
cleanup:
brelse(new_bh);
return error;
}
/*
* ext2_xattr_delete_inode()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed.
*/
void
ext2_xattr_delete_inode(struct inode *inode)
{
struct buffer_head *bh = NULL;
struct ext2_sb_info *sbi = EXT2_SB(inode->i_sb);
/*
* We are the only ones holding inode reference. The xattr_sem should
* better be unlocked! We could as well just not acquire xattr_sem at
* all but this makes the code more futureproof. OTOH we need trylock
* here to avoid false-positive warning from lockdep about reclaim
* circular dependency.
*/
if (WARN_ON_ONCE(!down_write_trylock(&EXT2_I(inode)->xattr_sem)))
return;
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
if (!ext2_data_block_valid(sbi, EXT2_I(inode)->i_file_acl, 1)) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: xattr block %d is out of data blocks range",
inode->i_ino, EXT2_I(inode)->i_file_acl);
goto cleanup;
}
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: block %d read error", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count)));
if (!ext2_xattr_header_valid(HDR(bh))) {
ext2_error(inode->i_sb, "ext2_xattr_delete_inode",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
goto cleanup;
}
ext2_xattr_release_block(inode, bh);
EXT2_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
up_write(&EXT2_I(inode)->xattr_sem);
}
/*
* ext2_xattr_cache_insert()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static int
ext2_xattr_cache_insert(struct mb_cache *cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
int error;
error = mb_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr,
true);
if (error) {
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
return error;
}
/*
* ext2_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext2_xattr_cmp(struct ext2_xattr_header *header1,
struct ext2_xattr_header *header2)
{
struct ext2_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT2_XATTR_NEXT(entry1);
entry2 = EXT2_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext2_xattr_cache_find()
*
* Find an identical extended attribute block.
*
* Returns a locked buffer head to the block found, or NULL if such
* a block was not found or an error occurred.
*/
static struct buffer_head *
ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
ce = mb_cache_entry_find_first(ea_block_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_value);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_value);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_value,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_touch(ea_block_cache, ce);
mb_cache_entry_put(ea_block_cache, ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ea_block_cache, ce);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext2_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static inline void ext2_xattr_hash_entry(struct ext2_xattr_header *header,
struct ext2_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n=0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT2_XATTR_ROUND) >> EXT2_XATTR_PAD_BITS; n; n--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext2_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext2_xattr_rehash(struct ext2_xattr_header *header,
struct ext2_xattr_entry *entry)
{
struct ext2_xattr_entry *here;
__u32 hash = 0;
ext2_xattr_hash_entry(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT2_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
#define HASH_BUCKET_BITS 10
struct mb_cache *ext2_xattr_create_cache(void)
{
return mb_cache_create(HASH_BUCKET_BITS);
}
void ext2_xattr_destroy_cache(struct mb_cache *cache)
{
if (cache)
mb_cache_destroy(cache);
}
| linux-master | fs/ext2/xattr.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/xattr_user.c
* Handler for extended user attributes.
*
* Copyright (C) 2001 by Andreas Gruenbacher, <[email protected]>
*/
#include <linux/init.h>
#include <linux/string.h>
#include "ext2.h"
#include "xattr.h"
static bool
ext2_xattr_user_list(struct dentry *dentry)
{
return test_opt(dentry->d_sb, XATTR_USER);
}
static int
ext2_xattr_user_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext2_xattr_get(inode, EXT2_XATTR_INDEX_USER,
name, buffer, size);
}
static int
ext2_xattr_user_set(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)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext2_xattr_set(inode, EXT2_XATTR_INDEX_USER,
name, value, size, flags);
}
const struct xattr_handler ext2_xattr_user_handler = {
.prefix = XATTR_USER_PREFIX,
.list = ext2_xattr_user_list,
.get = ext2_xattr_user_get,
.set = ext2_xattr_user_set,
};
| linux-master | fs/ext2/xattr_user.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/dir.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/dir.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext2 directory handling functions
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*
* All code that works with directory layout had been switched to pagecache
* and moved here. AV
*/
#include "ext2.h"
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/iversion.h>
typedef struct ext2_dir_entry_2 ext2_dirent;
/*
* Tests against MAX_REC_LEN etc were put in place for 64k block
* sizes; if that is not possible on this arch, we can skip
* those tests and speed things up.
*/
static inline unsigned ext2_rec_len_from_disk(__le16 dlen)
{
unsigned len = le16_to_cpu(dlen);
#if (PAGE_SIZE >= 65536)
if (len == EXT2_MAX_REC_LEN)
return 1 << 16;
#endif
return len;
}
static inline __le16 ext2_rec_len_to_disk(unsigned len)
{
#if (PAGE_SIZE >= 65536)
if (len == (1 << 16))
return cpu_to_le16(EXT2_MAX_REC_LEN);
else
BUG_ON(len > (1 << 16));
#endif
return cpu_to_le16(len);
}
/*
* ext2 uses block-sized chunks. Arguably, sector-sized ones would be
* more robust, but we have what we have
*/
static inline unsigned ext2_chunk_size(struct inode *inode)
{
return inode->i_sb->s_blocksize;
}
/*
* Return the offset into page `page_nr' of the last valid
* byte in that page, plus one.
*/
static unsigned
ext2_last_byte(struct inode *inode, unsigned long page_nr)
{
unsigned last_byte = inode->i_size;
last_byte -= page_nr << PAGE_SHIFT;
if (last_byte > PAGE_SIZE)
last_byte = PAGE_SIZE;
return last_byte;
}
static void ext2_commit_chunk(struct page *page, loff_t pos, unsigned len)
{
struct address_space *mapping = page->mapping;
struct inode *dir = mapping->host;
inode_inc_iversion(dir);
block_write_end(NULL, mapping, pos, len, len, page, NULL);
if (pos+len > dir->i_size) {
i_size_write(dir, pos+len);
mark_inode_dirty(dir);
}
unlock_page(page);
}
static bool ext2_check_page(struct page *page, int quiet, char *kaddr)
{
struct inode *dir = page->mapping->host;
struct super_block *sb = dir->i_sb;
unsigned chunk_size = ext2_chunk_size(dir);
u32 max_inumber = le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count);
unsigned offs, rec_len;
unsigned limit = PAGE_SIZE;
ext2_dirent *p;
char *error;
if ((dir->i_size >> PAGE_SHIFT) == page->index) {
limit = dir->i_size & ~PAGE_MASK;
if (limit & (chunk_size - 1))
goto Ebadsize;
if (!limit)
goto out;
}
for (offs = 0; offs <= limit - EXT2_DIR_REC_LEN(1); offs += rec_len) {
p = (ext2_dirent *)(kaddr + offs);
rec_len = ext2_rec_len_from_disk(p->rec_len);
if (unlikely(rec_len < EXT2_DIR_REC_LEN(1)))
goto Eshort;
if (unlikely(rec_len & 3))
goto Ealign;
if (unlikely(rec_len < EXT2_DIR_REC_LEN(p->name_len)))
goto Enamelen;
if (unlikely(((offs + rec_len - 1) ^ offs) & ~(chunk_size-1)))
goto Espan;
if (unlikely(le32_to_cpu(p->inode) > max_inumber))
goto Einumber;
}
if (offs != limit)
goto Eend;
out:
SetPageChecked(page);
return true;
/* Too bad, we had an error */
Ebadsize:
if (!quiet)
ext2_error(sb, __func__,
"size of directory #%lu is not a multiple "
"of chunk size", dir->i_ino);
goto fail;
Eshort:
error = "rec_len is smaller than minimal";
goto bad_entry;
Ealign:
error = "unaligned directory entry";
goto bad_entry;
Enamelen:
error = "rec_len is too small for name_len";
goto bad_entry;
Espan:
error = "directory entry across blocks";
goto bad_entry;
Einumber:
error = "inode out of bounds";
bad_entry:
if (!quiet)
ext2_error(sb, __func__, "bad entry in directory #%lu: : %s - "
"offset=%lu, inode=%lu, rec_len=%d, name_len=%d",
dir->i_ino, error, (page->index<<PAGE_SHIFT)+offs,
(unsigned long) le32_to_cpu(p->inode),
rec_len, p->name_len);
goto fail;
Eend:
if (!quiet) {
p = (ext2_dirent *)(kaddr + offs);
ext2_error(sb, "ext2_check_page",
"entry in directory #%lu spans the page boundary"
"offset=%lu, inode=%lu",
dir->i_ino, (page->index<<PAGE_SHIFT)+offs,
(unsigned long) le32_to_cpu(p->inode));
}
fail:
SetPageError(page);
return false;
}
/*
* Calls to ext2_get_page()/ext2_put_page() must be nested according to the
* rules documented in kmap_local_page()/kunmap_local().
*
* NOTE: ext2_find_entry() and ext2_dotdot() act as a call to ext2_get_page()
* and should be treated as a call to ext2_get_page() for nesting purposes.
*/
static void *ext2_get_page(struct inode *dir, unsigned long n,
int quiet, struct page **page)
{
struct address_space *mapping = dir->i_mapping;
struct folio *folio = read_mapping_folio(mapping, n, NULL);
void *page_addr;
if (IS_ERR(folio))
return ERR_CAST(folio);
page_addr = kmap_local_folio(folio, n & (folio_nr_pages(folio) - 1));
if (unlikely(!folio_test_checked(folio))) {
if (!ext2_check_page(&folio->page, quiet, page_addr))
goto fail;
}
*page = &folio->page;
return page_addr;
fail:
ext2_put_page(&folio->page, page_addr);
return ERR_PTR(-EIO);
}
/*
* NOTE! unlike strncmp, ext2_match returns 1 for success, 0 for failure.
*
* len <= EXT2_NAME_LEN and de != NULL are guaranteed by caller.
*/
static inline int ext2_match (int len, const char * const name,
struct ext2_dir_entry_2 * de)
{
if (len != de->name_len)
return 0;
if (!de->inode)
return 0;
return !memcmp(name, de->name, len);
}
/*
* p is at least 6 bytes before the end of page
*/
static inline ext2_dirent *ext2_next_entry(ext2_dirent *p)
{
return (ext2_dirent *)((char *)p +
ext2_rec_len_from_disk(p->rec_len));
}
static inline unsigned
ext2_validate_entry(char *base, unsigned offset, unsigned mask)
{
ext2_dirent *de = (ext2_dirent*)(base + offset);
ext2_dirent *p = (ext2_dirent*)(base + (offset&mask));
while ((char*)p < (char*)de) {
if (p->rec_len == 0)
break;
p = ext2_next_entry(p);
}
return offset_in_page(p);
}
static inline void ext2_set_de_type(ext2_dirent *de, struct inode *inode)
{
if (EXT2_HAS_INCOMPAT_FEATURE(inode->i_sb, EXT2_FEATURE_INCOMPAT_FILETYPE))
de->file_type = fs_umode_to_ftype(inode->i_mode);
else
de->file_type = 0;
}
static int
ext2_readdir(struct file *file, struct dir_context *ctx)
{
loff_t pos = ctx->pos;
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
unsigned int offset = pos & ~PAGE_MASK;
unsigned long n = pos >> PAGE_SHIFT;
unsigned long npages = dir_pages(inode);
unsigned chunk_mask = ~(ext2_chunk_size(inode)-1);
bool need_revalidate = !inode_eq_iversion(inode, file->f_version);
bool has_filetype;
if (pos > inode->i_size - EXT2_DIR_REC_LEN(1))
return 0;
has_filetype =
EXT2_HAS_INCOMPAT_FEATURE(sb, EXT2_FEATURE_INCOMPAT_FILETYPE);
for ( ; n < npages; n++, offset = 0) {
ext2_dirent *de;
struct page *page;
char *kaddr = ext2_get_page(inode, n, 0, &page);
char *limit;
if (IS_ERR(kaddr)) {
ext2_error(sb, __func__,
"bad page in #%lu",
inode->i_ino);
ctx->pos += PAGE_SIZE - offset;
return PTR_ERR(kaddr);
}
if (unlikely(need_revalidate)) {
if (offset) {
offset = ext2_validate_entry(kaddr, offset, chunk_mask);
ctx->pos = (n<<PAGE_SHIFT) + offset;
}
file->f_version = inode_query_iversion(inode);
need_revalidate = false;
}
de = (ext2_dirent *)(kaddr+offset);
limit = kaddr + ext2_last_byte(inode, n) - EXT2_DIR_REC_LEN(1);
for ( ;(char*)de <= limit; de = ext2_next_entry(de)) {
if (de->rec_len == 0) {
ext2_error(sb, __func__,
"zero-length directory entry");
ext2_put_page(page, de);
return -EIO;
}
if (de->inode) {
unsigned char d_type = DT_UNKNOWN;
if (has_filetype)
d_type = fs_ftype_to_dtype(de->file_type);
if (!dir_emit(ctx, de->name, de->name_len,
le32_to_cpu(de->inode),
d_type)) {
ext2_put_page(page, de);
return 0;
}
}
ctx->pos += ext2_rec_len_from_disk(de->rec_len);
}
ext2_put_page(page, kaddr);
}
return 0;
}
/*
* ext2_find_entry()
*
* finds an entry in the specified directory with the wanted name. It
* returns the page in which the entry was found (as a parameter - res_page),
* and the entry itself. Page is returned mapped and unlocked.
* Entry is guaranteed to be valid.
*
* On Success ext2_put_page() should be called on *res_page.
*
* NOTE: Calls to ext2_get_page()/ext2_put_page() must be nested according to
* the rules documented in kmap_local_page()/kunmap_local().
*
* ext2_find_entry() and ext2_dotdot() act as a call to ext2_get_page() and
* should be treated as a call to ext2_get_page() for nesting purposes.
*/
struct ext2_dir_entry_2 *ext2_find_entry (struct inode *dir,
const struct qstr *child, struct page **res_page)
{
const char *name = child->name;
int namelen = child->len;
unsigned reclen = EXT2_DIR_REC_LEN(namelen);
unsigned long start, n;
unsigned long npages = dir_pages(dir);
struct page *page = NULL;
struct ext2_inode_info *ei = EXT2_I(dir);
ext2_dirent * de;
if (npages == 0)
goto out;
/* OFFSET_CACHE */
*res_page = NULL;
start = ei->i_dir_start_lookup;
if (start >= npages)
start = 0;
n = start;
do {
char *kaddr = ext2_get_page(dir, n, 0, &page);
if (IS_ERR(kaddr))
return ERR_CAST(kaddr);
de = (ext2_dirent *) kaddr;
kaddr += ext2_last_byte(dir, n) - reclen;
while ((char *) de <= kaddr) {
if (de->rec_len == 0) {
ext2_error(dir->i_sb, __func__,
"zero-length directory entry");
ext2_put_page(page, de);
goto out;
}
if (ext2_match(namelen, name, de))
goto found;
de = ext2_next_entry(de);
}
ext2_put_page(page, kaddr);
if (++n >= npages)
n = 0;
/* next page is past the blocks we've got */
if (unlikely(n > (dir->i_blocks >> (PAGE_SHIFT - 9)))) {
ext2_error(dir->i_sb, __func__,
"dir %lu size %lld exceeds block count %llu",
dir->i_ino, dir->i_size,
(unsigned long long)dir->i_blocks);
goto out;
}
} while (n != start);
out:
return ERR_PTR(-ENOENT);
found:
*res_page = page;
ei->i_dir_start_lookup = n;
return de;
}
/*
* Return the '..' directory entry and the page in which the entry was found
* (as a parameter - p).
*
* On Success ext2_put_page() should be called on *p.
*
* NOTE: Calls to ext2_get_page()/ext2_put_page() must be nested according to
* the rules documented in kmap_local_page()/kunmap_local().
*
* ext2_find_entry() and ext2_dotdot() act as a call to ext2_get_page() and
* should be treated as a call to ext2_get_page() for nesting purposes.
*/
struct ext2_dir_entry_2 *ext2_dotdot(struct inode *dir, struct page **p)
{
ext2_dirent *de = ext2_get_page(dir, 0, 0, p);
if (!IS_ERR(de))
return ext2_next_entry(de);
return NULL;
}
int ext2_inode_by_name(struct inode *dir, const struct qstr *child, ino_t *ino)
{
struct ext2_dir_entry_2 *de;
struct page *page;
de = ext2_find_entry(dir, child, &page);
if (IS_ERR(de))
return PTR_ERR(de);
*ino = le32_to_cpu(de->inode);
ext2_put_page(page, de);
return 0;
}
static int ext2_prepare_chunk(struct page *page, loff_t pos, unsigned len)
{
return __block_write_begin(page, pos, len, ext2_get_block);
}
static int ext2_handle_dirsync(struct inode *dir)
{
int err;
err = filemap_write_and_wait(dir->i_mapping);
if (!err)
err = sync_inode_metadata(dir, 1);
return err;
}
int ext2_set_link(struct inode *dir, struct ext2_dir_entry_2 *de,
struct page *page, struct inode *inode, bool update_times)
{
loff_t pos = page_offset(page) + offset_in_page(de);
unsigned len = ext2_rec_len_from_disk(de->rec_len);
int err;
lock_page(page);
err = ext2_prepare_chunk(page, pos, len);
if (err) {
unlock_page(page);
return err;
}
de->inode = cpu_to_le32(inode->i_ino);
ext2_set_de_type(de, inode);
ext2_commit_chunk(page, pos, len);
if (update_times)
dir->i_mtime = inode_set_ctime_current(dir);
EXT2_I(dir)->i_flags &= ~EXT2_BTREE_FL;
mark_inode_dirty(dir);
return ext2_handle_dirsync(dir);
}
/*
* Parent is locked.
*/
int ext2_add_link (struct dentry *dentry, struct inode *inode)
{
struct inode *dir = d_inode(dentry->d_parent);
const char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
unsigned chunk_size = ext2_chunk_size(dir);
unsigned reclen = EXT2_DIR_REC_LEN(namelen);
unsigned short rec_len, name_len;
struct page *page = NULL;
ext2_dirent * de;
unsigned long npages = dir_pages(dir);
unsigned long n;
loff_t pos;
int err;
/*
* We take care of directory expansion in the same loop.
* This code plays outside i_size, so it locks the page
* to protect that region.
*/
for (n = 0; n <= npages; n++) {
char *kaddr = ext2_get_page(dir, n, 0, &page);
char *dir_end;
if (IS_ERR(kaddr))
return PTR_ERR(kaddr);
lock_page(page);
dir_end = kaddr + ext2_last_byte(dir, n);
de = (ext2_dirent *)kaddr;
kaddr += PAGE_SIZE - reclen;
while ((char *)de <= kaddr) {
if ((char *)de == dir_end) {
/* We hit i_size */
name_len = 0;
rec_len = chunk_size;
de->rec_len = ext2_rec_len_to_disk(chunk_size);
de->inode = 0;
goto got_it;
}
if (de->rec_len == 0) {
ext2_error(dir->i_sb, __func__,
"zero-length directory entry");
err = -EIO;
goto out_unlock;
}
err = -EEXIST;
if (ext2_match (namelen, name, de))
goto out_unlock;
name_len = EXT2_DIR_REC_LEN(de->name_len);
rec_len = ext2_rec_len_from_disk(de->rec_len);
if (!de->inode && rec_len >= reclen)
goto got_it;
if (rec_len >= name_len + reclen)
goto got_it;
de = (ext2_dirent *) ((char *) de + rec_len);
}
unlock_page(page);
ext2_put_page(page, kaddr);
}
BUG();
return -EINVAL;
got_it:
pos = page_offset(page) + offset_in_page(de);
err = ext2_prepare_chunk(page, pos, rec_len);
if (err)
goto out_unlock;
if (de->inode) {
ext2_dirent *de1 = (ext2_dirent *) ((char *) de + name_len);
de1->rec_len = ext2_rec_len_to_disk(rec_len - name_len);
de->rec_len = ext2_rec_len_to_disk(name_len);
de = de1;
}
de->name_len = namelen;
memcpy(de->name, name, namelen);
de->inode = cpu_to_le32(inode->i_ino);
ext2_set_de_type (de, inode);
ext2_commit_chunk(page, pos, rec_len);
dir->i_mtime = inode_set_ctime_current(dir);
EXT2_I(dir)->i_flags &= ~EXT2_BTREE_FL;
mark_inode_dirty(dir);
err = ext2_handle_dirsync(dir);
/* OFFSET_CACHE */
out_put:
ext2_put_page(page, de);
return err;
out_unlock:
unlock_page(page);
goto out_put;
}
/*
* ext2_delete_entry deletes a directory entry by merging it with the
* previous entry. Page is up-to-date.
*/
int ext2_delete_entry(struct ext2_dir_entry_2 *dir, struct page *page)
{
struct inode *inode = page->mapping->host;
char *kaddr = (char *)((unsigned long)dir & PAGE_MASK);
unsigned from = offset_in_page(dir) & ~(ext2_chunk_size(inode)-1);
unsigned to = offset_in_page(dir) +
ext2_rec_len_from_disk(dir->rec_len);
loff_t pos;
ext2_dirent *pde = NULL;
ext2_dirent *de = (ext2_dirent *)(kaddr + from);
int err;
while ((char*)de < (char*)dir) {
if (de->rec_len == 0) {
ext2_error(inode->i_sb, __func__,
"zero-length directory entry");
return -EIO;
}
pde = de;
de = ext2_next_entry(de);
}
if (pde)
from = offset_in_page(pde);
pos = page_offset(page) + from;
lock_page(page);
err = ext2_prepare_chunk(page, pos, to - from);
if (err) {
unlock_page(page);
return err;
}
if (pde)
pde->rec_len = ext2_rec_len_to_disk(to - from);
dir->inode = 0;
ext2_commit_chunk(page, pos, to - from);
inode->i_mtime = inode_set_ctime_current(inode);
EXT2_I(inode)->i_flags &= ~EXT2_BTREE_FL;
mark_inode_dirty(inode);
return ext2_handle_dirsync(inode);
}
/*
* Set the first fragment of directory.
*/
int ext2_make_empty(struct inode *inode, struct inode *parent)
{
struct page *page = grab_cache_page(inode->i_mapping, 0);
unsigned chunk_size = ext2_chunk_size(inode);
struct ext2_dir_entry_2 * de;
int err;
void *kaddr;
if (!page)
return -ENOMEM;
err = ext2_prepare_chunk(page, 0, chunk_size);
if (err) {
unlock_page(page);
goto fail;
}
kaddr = kmap_local_page(page);
memset(kaddr, 0, chunk_size);
de = (struct ext2_dir_entry_2 *)kaddr;
de->name_len = 1;
de->rec_len = ext2_rec_len_to_disk(EXT2_DIR_REC_LEN(1));
memcpy (de->name, ".\0\0", 4);
de->inode = cpu_to_le32(inode->i_ino);
ext2_set_de_type (de, inode);
de = (struct ext2_dir_entry_2 *)(kaddr + EXT2_DIR_REC_LEN(1));
de->name_len = 2;
de->rec_len = ext2_rec_len_to_disk(chunk_size - EXT2_DIR_REC_LEN(1));
de->inode = cpu_to_le32(parent->i_ino);
memcpy (de->name, "..\0", 4);
ext2_set_de_type (de, inode);
kunmap_local(kaddr);
ext2_commit_chunk(page, 0, chunk_size);
err = ext2_handle_dirsync(inode);
fail:
put_page(page);
return err;
}
/*
* routine to check that the specified directory is empty (for rmdir)
*/
int ext2_empty_dir (struct inode * inode)
{
struct page *page;
char *kaddr;
unsigned long i, npages = dir_pages(inode);
for (i = 0; i < npages; i++) {
ext2_dirent *de;
kaddr = ext2_get_page(inode, i, 0, &page);
if (IS_ERR(kaddr))
return 0;
de = (ext2_dirent *)kaddr;
kaddr += ext2_last_byte(inode, i) - EXT2_DIR_REC_LEN(1);
while ((char *)de <= kaddr) {
if (de->rec_len == 0) {
ext2_error(inode->i_sb, __func__,
"zero-length directory entry");
printk("kaddr=%p, de=%p\n", kaddr, de);
goto not_empty;
}
if (de->inode != 0) {
/* check for . and .. */
if (de->name[0] != '.')
goto not_empty;
if (de->name_len > 2)
goto not_empty;
if (de->name_len < 2) {
if (de->inode !=
cpu_to_le32(inode->i_ino))
goto not_empty;
} else if (de->name[1] != '.')
goto not_empty;
}
de = ext2_next_entry(de);
}
ext2_put_page(page, kaddr);
}
return 1;
not_empty:
ext2_put_page(page, kaddr);
return 0;
}
const struct file_operations ext2_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.iterate_shared = ext2_readdir,
.unlocked_ioctl = ext2_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ext2_compat_ioctl,
#endif
.fsync = ext2_fsync,
};
| linux-master | fs/ext2/dir.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie
* ([email protected]), 1993, 1998
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* ([email protected])
*
* Assorted race fixes, rewrite of ext2_get_block() by Al Viro, 2000
*/
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/dax.h>
#include <linux/blkdev.h>
#include <linux/quotaops.h>
#include <linux/writeback.h>
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/fiemap.h>
#include <linux/iomap.h>
#include <linux/namei.h>
#include <linux/uio.h>
#include "ext2.h"
#include "acl.h"
#include "xattr.h"
static int __ext2_write_inode(struct inode *inode, int do_sync);
/*
* Test whether an inode is a fast symlink.
*/
static inline int ext2_inode_is_fast_symlink(struct inode *inode)
{
int ea_blocks = EXT2_I(inode)->i_file_acl ?
(inode->i_sb->s_blocksize >> 9) : 0;
return (S_ISLNK(inode->i_mode) &&
inode->i_blocks - ea_blocks == 0);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset);
void ext2_write_failed(struct address_space *mapping, loff_t to)
{
struct inode *inode = mapping->host;
if (to > inode->i_size) {
truncate_pagecache(inode, inode->i_size);
ext2_truncate_blocks(inode, inode->i_size);
}
}
/*
* Called at the last iput() if i_nlink is zero.
*/
void ext2_evict_inode(struct inode * inode)
{
struct ext2_block_alloc_info *rsv;
int want_delete = 0;
if (!inode->i_nlink && !is_bad_inode(inode)) {
want_delete = 1;
dquot_initialize(inode);
} else {
dquot_drop(inode);
}
truncate_inode_pages_final(&inode->i_data);
if (want_delete) {
sb_start_intwrite(inode->i_sb);
/* set dtime */
EXT2_I(inode)->i_dtime = ktime_get_real_seconds();
mark_inode_dirty(inode);
__ext2_write_inode(inode, inode_needs_sync(inode));
/* truncate to 0 */
inode->i_size = 0;
if (inode->i_blocks)
ext2_truncate_blocks(inode, 0);
ext2_xattr_delete_inode(inode);
}
invalidate_inode_buffers(inode);
clear_inode(inode);
ext2_discard_reservation(inode);
rsv = EXT2_I(inode)->i_block_alloc_info;
EXT2_I(inode)->i_block_alloc_info = NULL;
if (unlikely(rsv))
kfree(rsv);
if (want_delete) {
ext2_free_inode(inode);
sb_end_intwrite(inode->i_sb);
}
}
typedef struct {
__le32 *p;
__le32 key;
struct buffer_head *bh;
} Indirect;
static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
{
p->key = *(p->p = v);
p->bh = bh;
}
static inline int verify_chain(Indirect *from, Indirect *to)
{
while (from <= to && from->key == *from->p)
from++;
return (from > to);
}
/**
* ext2_block_to_path - parse the block number into array of offsets
* @inode: inode in question (we are only interested in its superblock)
* @i_block: block number to be parsed
* @offsets: array to store the offsets in
* @boundary: set this non-zero if the referred-to block is likely to be
* followed (on disk) by an indirect block.
* To store the locations of file's data ext2 uses a data structure common
* for UNIX filesystems - tree of pointers anchored in the inode, with
* data blocks at leaves and indirect blocks in intermediate nodes.
* This function translates the block number into path in that tree -
* return value is the path length and @offsets[n] is the offset of
* pointer to (n+1)th node in the nth one. If @block is out of range
* (negative or too large) warning is printed and zero returned.
*
* Note: function doesn't find node addresses, so no IO is needed. All
* we need to know is the capacity of indirect blocks (taken from the
* inode->i_sb).
*/
/*
* Portability note: the last comparison (check that we fit into triple
* indirect block) is spelled differently, because otherwise on an
* architecture with 32-bit longs and 8Kb pages we might get into trouble
* if our filesystem had 8Kb blocks. We might use long long, but that would
* kill us on x86. Oh, well, at least the sign propagation does not matter -
* i_block would have to be negative in the very beginning, so we would not
* get there at all.
*/
static int ext2_block_to_path(struct inode *inode,
long i_block, int offsets[4], int *boundary)
{
int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
const long direct_blocks = EXT2_NDIR_BLOCKS,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
int final = 0;
if (i_block < 0) {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block < 0", __func__);
} else if (i_block < direct_blocks) {
offsets[n++] = i_block;
final = direct_blocks;
} else if ( (i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = EXT2_IND_BLOCK;
offsets[n++] = i_block;
final = ptrs;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = EXT2_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = EXT2_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block is too big", __func__);
}
if (boundary)
*boundary = final - 1 - (i_block & (ptrs - 1));
return n;
}
/**
* ext2_get_branch - read the chain of indirect blocks leading to data
* @inode: inode in question
* @depth: depth of the chain (1 - direct pointer, etc.)
* @offsets: offsets of pointers in inode/indirect blocks
* @chain: place to store the result
* @err: here we store the error value
*
* Function fills the array of triples <key, p, bh> and returns %NULL
* if everything went OK or the pointer to the last filled triple
* (incomplete one) otherwise. Upon the return chain[i].key contains
* the number of (i+1)-th block in the chain (as it is stored in memory,
* i.e. little-endian 32-bit), chain[i].p contains the address of that
* number (it points into struct inode for i==0 and into the bh->b_data
* for i>0) and chain[i].bh points to the buffer_head of i-th indirect
* block for i>0 and NULL for i==0. In other words, it holds the block
* numbers of the chain, addresses they were taken from (and where we can
* verify that chain did not change) and buffer_heads hosting these
* numbers.
*
* Function stops when it stumbles upon zero pointer (absent block)
* (pointer to last triple returned, *@err == 0)
* or when it gets an IO error reading an indirect block
* (ditto, *@err == -EIO)
* or when it notices that chain had been changed while it was reading
* (ditto, *@err == -EAGAIN)
* or when it reads all @depth-1 indirect blocks successfully and finds
* the whole chain, all way to the data (returns %NULL, *err == 0).
*/
static Indirect *ext2_get_branch(struct inode *inode,
int depth,
int *offsets,
Indirect chain[4],
int *err)
{
struct super_block *sb = inode->i_sb;
Indirect *p = chain;
struct buffer_head *bh;
*err = 0;
/* i_data is not going away, no lock needed */
add_chain (chain, NULL, EXT2_I(inode)->i_data + *offsets);
if (!p->key)
goto no_block;
while (--depth) {
bh = sb_bread(sb, le32_to_cpu(p->key));
if (!bh)
goto failure;
read_lock(&EXT2_I(inode)->i_meta_lock);
if (!verify_chain(chain, p))
goto changed;
add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
read_unlock(&EXT2_I(inode)->i_meta_lock);
if (!p->key)
goto no_block;
}
return NULL;
changed:
read_unlock(&EXT2_I(inode)->i_meta_lock);
brelse(bh);
*err = -EAGAIN;
goto no_block;
failure:
*err = -EIO;
no_block:
return p;
}
/**
* ext2_find_near - find a place for allocation with sufficient locality
* @inode: owner
* @ind: descriptor of indirect block.
*
* This function returns the preferred place for block allocation.
* It is used when heuristic for sequential allocation fails.
* Rules are:
* + if there is a block to the left of our position - allocate near it.
* + if pointer will live in indirect block - allocate near that block.
* + if pointer will live in inode - allocate in the same cylinder group.
*
* In the latter case we colour the starting block by the callers PID to
* prevent it from clashing with concurrent allocations for a different inode
* in the same block group. The PID is used here so that functionally related
* files will be close-by on-disk.
*
* Caller must make sure that @ind is valid and will stay that way.
*/
static ext2_fsblk_t ext2_find_near(struct inode *inode, Indirect *ind)
{
struct ext2_inode_info *ei = EXT2_I(inode);
__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
__le32 *p;
ext2_fsblk_t bg_start;
ext2_fsblk_t colour;
/* Try to find previous block */
for (p = ind->p - 1; p >= start; p--)
if (*p)
return le32_to_cpu(*p);
/* No such thing, so let's try location of indirect block */
if (ind->bh)
return ind->bh->b_blocknr;
/*
* It is going to be referred from inode itself? OK, just put it into
* the same cylinder group then.
*/
bg_start = ext2_group_first_block_no(inode->i_sb, ei->i_block_group);
colour = (current->pid % 16) *
(EXT2_BLOCKS_PER_GROUP(inode->i_sb) / 16);
return bg_start + colour;
}
/**
* ext2_find_goal - find a preferred place for allocation.
* @inode: owner
* @block: block we want
* @partial: pointer to the last triple within a chain
*
* Returns preferred place for a block (the goal).
*/
static inline ext2_fsblk_t ext2_find_goal(struct inode *inode, long block,
Indirect *partial)
{
struct ext2_block_alloc_info *block_i;
block_i = EXT2_I(inode)->i_block_alloc_info;
/*
* try the heuristic for sequential allocation,
* failing that at least try to get decent locality.
*/
if (block_i && (block == block_i->last_alloc_logical_block + 1)
&& (block_i->last_alloc_physical_block != 0)) {
return block_i->last_alloc_physical_block + 1;
}
return ext2_find_near(inode, partial);
}
/**
* ext2_blks_to_allocate: Look up the block map and count the number
* of direct blocks need to be allocated for the given branch.
*
* @branch: chain of indirect blocks
* @k: number of blocks need for indirect blocks
* @blks: number of data blocks to be mapped.
* @blocks_to_boundary: the offset in the indirect block
*
* return the number of direct blocks to allocate.
*/
static int
ext2_blks_to_allocate(Indirect * branch, int k, unsigned long blks,
int blocks_to_boundary)
{
unsigned long count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now don't hanel cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary
&& le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
/**
* ext2_alloc_blocks: Allocate multiple blocks needed for a branch.
* @inode: Owner.
* @goal: Preferred place for allocation.
* @indirect_blks: The number of blocks needed to allocate for indirect blocks.
* @blks: The number of blocks need to allocate for direct blocks.
* @new_blocks: On return it will store the new block numbers for
* the indirect blocks(if needed) and the first direct block.
* @err: Error pointer.
*
* Return: Number of blocks allocated.
*/
static int ext2_alloc_blocks(struct inode *inode,
ext2_fsblk_t goal, int indirect_blks, int blks,
ext2_fsblk_t new_blocks[4], int *err)
{
int target, i;
unsigned long count = 0;
int index = 0;
ext2_fsblk_t current_block = 0;
int ret = 0;
/*
* Here we try to allocate the requested multiple blocks at once,
* on a best-effort basis.
* To build a branch, we should allocate blocks for
* the indirect blocks(if not allocated yet), and at least
* the first direct block of this branch. That's the
* minimum number of blocks need to allocate(required)
*/
target = blks + indirect_blks;
while (1) {
count = target;
/* allocating blocks for indirect blocks and direct blocks */
current_block = ext2_new_blocks(inode, goal, &count, err, 0);
if (*err)
goto failed_out;
target -= count;
/* allocate blocks for indirect blocks */
while (index < indirect_blks && count) {
new_blocks[index++] = current_block++;
count--;
}
if (count > 0)
break;
}
/* save the new block number for the first direct block */
new_blocks[index] = current_block;
/* total number of blocks allocated for direct blocks */
ret = count;
*err = 0;
return ret;
failed_out:
for (i = 0; i <index; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
if (index)
mark_inode_dirty(inode);
return ret;
}
/**
* ext2_alloc_branch - allocate and set up a chain of blocks.
* @inode: owner
* @indirect_blks: depth of the chain (number of blocks to allocate)
* @blks: number of allocated direct blocks
* @goal: preferred place for allocation
* @offsets: offsets (in the blocks) to store the pointers to next.
* @branch: place to store the chain in.
*
* This function allocates @num blocks, zeroes out all but the last one,
* links them into chain and (if we are synchronous) writes them to disk.
* In other words, it prepares a branch that can be spliced onto the
* inode. It stores the information about that chain in the branch[], in
* the same format as ext2_get_branch() would do. We are calling it after
* we had read the existing part of chain and partial points to the last
* triple of that (one with zero ->key). Upon the exit we have the same
* picture as after the successful ext2_get_block(), except that in one
* place chain is disconnected - *branch->p is still zero (we did not
* set the last link), but branch->key contains the number that should
* be placed into *branch->p to fill that gap.
*
* If allocation fails we free all blocks we've allocated (and forget
* their buffer_heads) and return the error value the from failed
* ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
* as described above and return 0.
*/
static int ext2_alloc_branch(struct inode *inode,
int indirect_blks, int *blks, ext2_fsblk_t goal,
int *offsets, Indirect *branch)
{
int blocksize = inode->i_sb->s_blocksize;
int i, n = 0;
int err = 0;
struct buffer_head *bh;
int num;
ext2_fsblk_t new_blocks[4];
ext2_fsblk_t current_block;
num = ext2_alloc_blocks(inode, goal, indirect_blks,
*blks, new_blocks, &err);
if (err)
return err;
branch[0].key = cpu_to_le32(new_blocks[0]);
/*
* metadata blocks and data blocks are allocated.
*/
for (n = 1; n <= indirect_blks; n++) {
/*
* Get buffer_head for parent block, zero it out
* and set the pointer to new one, then send
* parent to disk.
*/
bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
if (unlikely(!bh)) {
err = -ENOMEM;
goto failed;
}
branch[n].bh = bh;
lock_buffer(bh);
memset(bh->b_data, 0, blocksize);
branch[n].p = (__le32 *) bh->b_data + offsets[n];
branch[n].key = cpu_to_le32(new_blocks[n]);
*branch[n].p = branch[n].key;
if ( n == indirect_blks) {
current_block = new_blocks[n];
/*
* End of chain, update the last new metablock of
* the chain to point to the new allocated
* data blocks numbers
*/
for (i=1; i < num; i++)
*(branch[n].p + i) = cpu_to_le32(++current_block);
}
set_buffer_uptodate(bh);
unlock_buffer(bh);
mark_buffer_dirty_inode(bh, inode);
/* We used to sync bh here if IS_SYNC(inode).
* But we now rely upon generic_write_sync()
* and b_inode_buffers. But not for directories.
*/
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
sync_dirty_buffer(bh);
}
*blks = num;
return err;
failed:
for (i = 1; i < n; i++)
bforget(branch[i].bh);
for (i = 0; i < indirect_blks; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
ext2_free_blocks(inode, new_blocks[i], num);
return err;
}
/**
* ext2_splice_branch - splice the allocated branch onto inode.
* @inode: owner
* @block: (logical) number of block we are adding
* @where: location of missing link
* @num: number of indirect blocks we are adding
* @blks: number of direct blocks we are adding
*
* This function fills the missing link and does all housekeeping needed in
* inode (->i_blocks, etc.). In case of success we end up with the full
* chain to new block and return 0.
*/
static void ext2_splice_branch(struct inode *inode,
long block, Indirect *where, int num, int blks)
{
int i;
struct ext2_block_alloc_info *block_i;
ext2_fsblk_t current_block;
block_i = EXT2_I(inode)->i_block_alloc_info;
/* XXX LOCKING probably should have i_meta_lock ?*/
/* That's it */
*where->p = where->key;
/*
* Update the host buffer_head or inode to point to more just allocated
* direct blocks blocks
*/
if (num == 0 && blks > 1) {
current_block = le32_to_cpu(where->key) + 1;
for (i = 1; i < blks; i++)
*(where->p + i ) = cpu_to_le32(current_block++);
}
/*
* update the most recently allocated logical & physical block
* in i_block_alloc_info, to assist find the proper goal block for next
* allocation
*/
if (block_i) {
block_i->last_alloc_logical_block = block + blks - 1;
block_i->last_alloc_physical_block =
le32_to_cpu(where[num].key) + blks - 1;
}
/* We are done with atomic stuff, now do the rest of housekeeping */
/* had we spliced it onto indirect block? */
if (where->bh)
mark_buffer_dirty_inode(where->bh, inode);
inode_set_ctime_current(inode);
mark_inode_dirty(inode);
}
/*
* Allocation strategy is simple: if we have to allocate something, we will
* have to go the whole way to leaf. So let's do it before attaching anything
* to tree, set linkage between the newborn blocks, write them if sync is
* required, recheck the path, free and repeat if check fails, otherwise
* set the last missing link (that will protect us from any truncate-generated
* removals - all blocks on the path are immune now) and possibly force the
* write on the parent block.
* That has a nice additional property: no special recovery from the failed
* allocations is needed - we simply release blocks and do not touch anything
* reachable from inode.
*
* `handle' can be NULL if create == 0.
*
* return > 0, # of blocks mapped or allocated.
* return = 0, if plain lookup failed.
* return < 0, error case.
*/
static int ext2_get_blocks(struct inode *inode,
sector_t iblock, unsigned long maxblocks,
u32 *bno, bool *new, bool *boundary,
int create)
{
int err;
int offsets[4];
Indirect chain[4];
Indirect *partial;
ext2_fsblk_t goal;
int indirect_blks;
int blocks_to_boundary = 0;
int depth;
struct ext2_inode_info *ei = EXT2_I(inode);
int count = 0;
ext2_fsblk_t first_block = 0;
BUG_ON(maxblocks == 0);
depth = ext2_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
if (depth == 0)
return -EIO;
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
/* Simplest case - block found, no allocation needed */
if (!partial) {
first_block = le32_to_cpu(chain[depth - 1].key);
count++;
/*map more blocks*/
while (count < maxblocks && count <= blocks_to_boundary) {
ext2_fsblk_t blk;
if (!verify_chain(chain, chain + depth - 1)) {
/*
* Indirect block might be removed by
* truncate while we were reading it.
* Handling of that case: forget what we've
* got now, go to reread.
*/
err = -EAGAIN;
count = 0;
partial = chain + depth - 1;
break;
}
blk = le32_to_cpu(*(chain[depth-1].p + count));
if (blk == first_block + count)
count++;
else
break;
}
if (err != -EAGAIN)
goto got_it;
}
/* Next simple case - plain lookup or failed read of indirect block */
if (!create || err == -EIO)
goto cleanup;
mutex_lock(&ei->truncate_mutex);
/*
* If the indirect block is missing while we are reading
* the chain(ext2_get_branch() returns -EAGAIN err), or
* if the chain has been changed after we grab the semaphore,
* (either because another process truncated this branch, or
* another get_block allocated this branch) re-grab the chain to see if
* the request block has been allocated or not.
*
* Since we already block the truncate/other get_block
* at this point, we will have the current copy of the chain when we
* splice the branch into the tree.
*/
if (err == -EAGAIN || !verify_chain(chain, partial)) {
while (partial > chain) {
brelse(partial->bh);
partial--;
}
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
if (!partial) {
count++;
mutex_unlock(&ei->truncate_mutex);
goto got_it;
}
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
}
/*
* Okay, we need to do block allocation. Lazily initialize the block
* allocation info here if necessary
*/
if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
ext2_init_block_alloc_info(inode);
goal = ext2_find_goal(inode, iblock, partial);
/* the number of blocks need to allocate for [d,t]indirect blocks */
indirect_blks = (chain + depth) - partial - 1;
/*
* Next look up the indirect map to count the total number of
* direct blocks to allocate for this branch.
*/
count = ext2_blks_to_allocate(partial, indirect_blks,
maxblocks, blocks_to_boundary);
/*
* XXX ???? Block out ext2_truncate while we alter the tree
*/
err = ext2_alloc_branch(inode, indirect_blks, &count, goal,
offsets + (partial - chain), partial);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
if (IS_DAX(inode)) {
/*
* We must unmap blocks before zeroing so that writeback cannot
* overwrite zeros with stale data from block device page cache.
*/
clean_bdev_aliases(inode->i_sb->s_bdev,
le32_to_cpu(chain[depth-1].key),
count);
/*
* block must be initialised before we put it in the tree
* so that it's not found by another thread before it's
* initialised
*/
err = sb_issue_zeroout(inode->i_sb,
le32_to_cpu(chain[depth-1].key), count,
GFP_NOFS);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
}
*new = true;
ext2_splice_branch(inode, iblock, partial, indirect_blks, count);
mutex_unlock(&ei->truncate_mutex);
got_it:
if (count > blocks_to_boundary)
*boundary = true;
err = count;
/* Clean up and exit */
partial = chain + depth - 1; /* the whole chain */
cleanup:
while (partial > chain) {
brelse(partial->bh);
partial--;
}
if (err > 0)
*bno = le32_to_cpu(chain[depth-1].key);
return err;
}
int ext2_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
bool new = false, boundary = false;
u32 bno;
int ret;
ret = ext2_get_blocks(inode, iblock, max_blocks, &bno, &new, &boundary,
create);
if (ret <= 0)
return ret;
map_bh(bh_result, inode->i_sb, bno);
bh_result->b_size = (ret << inode->i_blkbits);
if (new)
set_buffer_new(bh_result);
if (boundary)
set_buffer_boundary(bh_result);
return 0;
}
static int ext2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
unsigned flags, struct iomap *iomap, struct iomap *srcmap)
{
unsigned int blkbits = inode->i_blkbits;
unsigned long first_block = offset >> blkbits;
unsigned long max_blocks = (length + (1 << blkbits) - 1) >> blkbits;
struct ext2_sb_info *sbi = EXT2_SB(inode->i_sb);
bool new = false, boundary = false;
u32 bno;
int ret;
bool create = flags & IOMAP_WRITE;
/*
* For writes that could fill holes inside i_size on a
* DIO_SKIP_HOLES filesystem we forbid block creations: only
* overwrites are permitted.
*/
if ((flags & IOMAP_DIRECT) &&
(first_block << blkbits) < i_size_read(inode))
create = 0;
/*
* Writes that span EOF might trigger an IO size update on completion,
* so consider them to be dirty for the purposes of O_DSYNC even if
* there is no other metadata changes pending or have been made here.
*/
if ((flags & IOMAP_WRITE) && offset + length > i_size_read(inode))
iomap->flags |= IOMAP_F_DIRTY;
ret = ext2_get_blocks(inode, first_block, max_blocks,
&bno, &new, &boundary, create);
if (ret < 0)
return ret;
iomap->flags = 0;
iomap->offset = (u64)first_block << blkbits;
if (flags & IOMAP_DAX)
iomap->dax_dev = sbi->s_daxdev;
else
iomap->bdev = inode->i_sb->s_bdev;
if (ret == 0) {
/*
* Switch to buffered-io for writing to holes in a non-extent
* based filesystem to avoid stale data exposure problem.
*/
if (!create && (flags & IOMAP_WRITE) && (flags & IOMAP_DIRECT))
return -ENOTBLK;
iomap->type = IOMAP_HOLE;
iomap->addr = IOMAP_NULL_ADDR;
iomap->length = 1 << blkbits;
} else {
iomap->type = IOMAP_MAPPED;
iomap->addr = (u64)bno << blkbits;
if (flags & IOMAP_DAX)
iomap->addr += sbi->s_dax_part_off;
iomap->length = (u64)ret << blkbits;
iomap->flags |= IOMAP_F_MERGED;
}
if (new)
iomap->flags |= IOMAP_F_NEW;
return 0;
}
static int
ext2_iomap_end(struct inode *inode, loff_t offset, loff_t length,
ssize_t written, unsigned flags, struct iomap *iomap)
{
/*
* Switch to buffered-io in case of any error.
* Blocks allocated can be used by the buffered-io path.
*/
if ((flags & IOMAP_DIRECT) && (flags & IOMAP_WRITE) && written == 0)
return -ENOTBLK;
if (iomap->type == IOMAP_MAPPED &&
written < length &&
(flags & IOMAP_WRITE))
ext2_write_failed(inode->i_mapping, offset + length);
return 0;
}
const struct iomap_ops ext2_iomap_ops = {
.iomap_begin = ext2_iomap_begin,
.iomap_end = ext2_iomap_end,
};
int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
int ret;
inode_lock(inode);
len = min_t(u64, len, i_size_read(inode));
ret = iomap_fiemap(inode, fieinfo, start, len, &ext2_iomap_ops);
inode_unlock(inode);
return ret;
}
static int ext2_read_folio(struct file *file, struct folio *folio)
{
return mpage_read_folio(folio, ext2_get_block);
}
static void ext2_readahead(struct readahead_control *rac)
{
mpage_readahead(rac, ext2_get_block);
}
static int
ext2_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, struct page **pagep, void **fsdata)
{
int ret;
ret = block_write_begin(mapping, pos, len, pagep, ext2_get_block);
if (ret < 0)
ext2_write_failed(mapping, pos + len);
return ret;
}
static int ext2_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
int ret;
ret = generic_write_end(file, mapping, pos, len, copied, page, fsdata);
if (ret < len)
ext2_write_failed(mapping, pos + len);
return ret;
}
static sector_t ext2_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping,block,ext2_get_block);
}
static int
ext2_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
return mpage_writepages(mapping, wbc, ext2_get_block);
}
static int
ext2_dax_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
struct ext2_sb_info *sbi = EXT2_SB(mapping->host->i_sb);
return dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
}
const struct address_space_operations ext2_aops = {
.dirty_folio = block_dirty_folio,
.invalidate_folio = block_invalidate_folio,
.read_folio = ext2_read_folio,
.readahead = ext2_readahead,
.write_begin = ext2_write_begin,
.write_end = ext2_write_end,
.bmap = ext2_bmap,
.direct_IO = noop_direct_IO,
.writepages = ext2_writepages,
.migrate_folio = buffer_migrate_folio,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations ext2_dax_aops = {
.writepages = ext2_dax_writepages,
.direct_IO = noop_direct_IO,
.dirty_folio = noop_dirty_folio,
};
/*
* Probably it should be a library function... search for first non-zero word
* or memcmp with zero_page, whatever is better for particular architecture.
* Linus?
*/
static inline int all_zeroes(__le32 *p, __le32 *q)
{
while (p < q)
if (*p++)
return 0;
return 1;
}
/**
* ext2_find_shared - find the indirect blocks for partial truncation.
* @inode: inode in question
* @depth: depth of the affected branch
* @offsets: offsets of pointers in that branch (see ext2_block_to_path)
* @chain: place to store the pointers to partial indirect blocks
* @top: place to the (detached) top of branch
*
* This is a helper function used by ext2_truncate().
*
* When we do truncate() we may have to clean the ends of several indirect
* blocks but leave the blocks themselves alive. Block is partially
* truncated if some data below the new i_size is referred from it (and
* it is on the path to the first completely truncated data block, indeed).
* We have to free the top of that path along with everything to the right
* of the path. Since no allocation past the truncation point is possible
* until ext2_truncate() finishes, we may safely do the latter, but top
* of branch may require special attention - pageout below the truncation
* point might try to populate it.
*
* We atomically detach the top of branch from the tree, store the block
* number of its root in *@top, pointers to buffer_heads of partially
* truncated blocks - in @chain[].bh and pointers to their last elements
* that should not be removed - in @chain[].p. Return value is the pointer
* to last filled element of @chain.
*
* The work left to caller to do the actual freeing of subtrees:
* a) free the subtree starting from *@top
* b) free the subtrees whose roots are stored in
* (@chain[i].p+1 .. end of @chain[i].bh->b_data)
* c) free the subtrees growing from the inode past the @chain[0].p
* (no partially truncated stuff there).
*/
static Indirect *ext2_find_shared(struct inode *inode,
int depth,
int offsets[4],
Indirect chain[4],
__le32 *top)
{
Indirect *partial, *p;
int k, err;
*top = 0;
for (k = depth; k > 1 && !offsets[k-1]; k--)
;
partial = ext2_get_branch(inode, k, offsets, chain, &err);
if (!partial)
partial = chain + k-1;
/*
* If the branch acquired continuation since we've looked at it -
* fine, it should all survive and (new) top doesn't belong to us.
*/
write_lock(&EXT2_I(inode)->i_meta_lock);
if (!partial->key && *partial->p) {
write_unlock(&EXT2_I(inode)->i_meta_lock);
goto no_top;
}
for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
;
/*
* OK, we've found the last block that must survive. The rest of our
* branch should be detached before unlocking. However, if that rest
* of branch is all ours and does not grow immediately from the inode
* it's easier to cheat and just decrement partial->p.
*/
if (p == chain + k - 1 && p > chain) {
p->p--;
} else {
*top = *p->p;
*p->p = 0;
}
write_unlock(&EXT2_I(inode)->i_meta_lock);
while(partial > p)
{
brelse(partial->bh);
partial--;
}
no_top:
return partial;
}
/**
* ext2_free_data - free a list of data blocks
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: points immediately past the end of array
*
* We are freeing all blocks referred from that array (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static inline void ext2_free_data(struct inode *inode, __le32 *p, __le32 *q)
{
ext2_fsblk_t block_to_free = 0, count = 0;
ext2_fsblk_t nr;
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (nr) {
*p = 0;
/* accumulate blocks to free if they're contiguous */
if (count == 0)
goto free_this;
else if (block_to_free == nr - count)
count++;
else {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
free_this:
block_to_free = nr;
count = 1;
}
}
}
if (count > 0) {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
}
}
/**
* ext2_free_branches - free an array of branches
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: pointer immediately past the end of array
* @depth: depth of the branches to free
*
* We are freeing all blocks referred from these branches (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static void ext2_free_branches(struct inode *inode, __le32 *p, __le32 *q, int depth)
{
struct buffer_head * bh;
ext2_fsblk_t nr;
if (depth--) {
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (!nr)
continue;
*p = 0;
bh = sb_bread(inode->i_sb, nr);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (!bh) {
ext2_error(inode->i_sb, "ext2_free_branches",
"Read failure, inode=%ld, block=%ld",
inode->i_ino, nr);
continue;
}
ext2_free_branches(inode,
(__le32*)bh->b_data,
(__le32*)bh->b_data + addr_per_block,
depth);
bforget(bh);
ext2_free_blocks(inode, nr, 1);
mark_inode_dirty(inode);
}
} else
ext2_free_data(inode, p, q);
}
/* mapping->invalidate_lock must be held when calling this function */
static void __ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
__le32 *i_data = EXT2_I(inode)->i_data;
struct ext2_inode_info *ei = EXT2_I(inode);
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int offsets[4];
Indirect chain[4];
Indirect *partial;
__le32 nr = 0;
int n;
long iblock;
unsigned blocksize;
blocksize = inode->i_sb->s_blocksize;
iblock = (offset + blocksize-1) >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
#ifdef CONFIG_FS_DAX
WARN_ON(!rwsem_is_locked(&inode->i_mapping->invalidate_lock));
#endif
n = ext2_block_to_path(inode, iblock, offsets, NULL);
if (n == 0)
return;
/*
* From here we block out all ext2_get_block() callers who want to
* modify the block allocation tree.
*/
mutex_lock(&ei->truncate_mutex);
if (n == 1) {
ext2_free_data(inode, i_data+offsets[0],
i_data + EXT2_NDIR_BLOCKS);
goto do_indirects;
}
partial = ext2_find_shared(inode, n, offsets, chain, &nr);
/* Kill the top of shared branch (already detached) */
if (nr) {
if (partial == chain)
mark_inode_dirty(inode);
else
mark_buffer_dirty_inode(partial->bh, inode);
ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
}
/* Clear the ends of indirect blocks on the shared branch */
while (partial > chain) {
ext2_free_branches(inode,
partial->p + 1,
(__le32*)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
mark_buffer_dirty_inode(partial->bh, inode);
brelse (partial->bh);
partial--;
}
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
nr = i_data[EXT2_IND_BLOCK];
if (nr) {
i_data[EXT2_IND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 1);
}
fallthrough;
case EXT2_IND_BLOCK:
nr = i_data[EXT2_DIND_BLOCK];
if (nr) {
i_data[EXT2_DIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 2);
}
fallthrough;
case EXT2_DIND_BLOCK:
nr = i_data[EXT2_TIND_BLOCK];
if (nr) {
i_data[EXT2_TIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 3);
}
break;
case EXT2_TIND_BLOCK:
;
}
ext2_discard_reservation(inode);
mutex_unlock(&ei->truncate_mutex);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return;
if (ext2_inode_is_fast_symlink(inode))
return;
filemap_invalidate_lock(inode->i_mapping);
__ext2_truncate_blocks(inode, offset);
filemap_invalidate_unlock(inode->i_mapping);
}
static int ext2_setsize(struct inode *inode, loff_t newsize)
{
int error;
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return -EINVAL;
if (ext2_inode_is_fast_symlink(inode))
return -EINVAL;
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
inode_dio_wait(inode);
if (IS_DAX(inode))
error = dax_truncate_page(inode, newsize, NULL,
&ext2_iomap_ops);
else
error = block_truncate_page(inode->i_mapping,
newsize, ext2_get_block);
if (error)
return error;
filemap_invalidate_lock(inode->i_mapping);
truncate_setsize(inode, newsize);
__ext2_truncate_blocks(inode, newsize);
filemap_invalidate_unlock(inode->i_mapping);
inode->i_mtime = inode_set_ctime_current(inode);
if (inode_needs_sync(inode)) {
sync_mapping_buffers(inode->i_mapping);
sync_inode_metadata(inode, 1);
} else {
mark_inode_dirty(inode);
}
return 0;
}
static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino,
struct buffer_head **p)
{
struct buffer_head * bh;
unsigned long block_group;
unsigned long block;
unsigned long offset;
struct ext2_group_desc * gdp;
*p = NULL;
if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) ||
ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
goto Einval;
block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
gdp = ext2_get_group_desc(sb, block_group, NULL);
if (!gdp)
goto Egdp;
/*
* Figure out the offset within the block group inode table
*/
offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb);
block = le32_to_cpu(gdp->bg_inode_table) +
(offset >> EXT2_BLOCK_SIZE_BITS(sb));
if (!(bh = sb_bread(sb, block)))
goto Eio;
*p = bh;
offset &= (EXT2_BLOCK_SIZE(sb) - 1);
return (struct ext2_inode *) (bh->b_data + offset);
Einval:
ext2_error(sb, "ext2_get_inode", "bad inode number: %lu",
(unsigned long) ino);
return ERR_PTR(-EINVAL);
Eio:
ext2_error(sb, "ext2_get_inode",
"unable to read inode block - inode=%lu, block=%lu",
(unsigned long) ino, block);
Egdp:
return ERR_PTR(-EIO);
}
void ext2_set_inode_flags(struct inode *inode)
{
unsigned int flags = EXT2_I(inode)->i_flags;
inode->i_flags &= ~(S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME |
S_DIRSYNC | S_DAX);
if (flags & EXT2_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & EXT2_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & EXT2_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & EXT2_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & EXT2_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode))
inode->i_flags |= S_DAX;
}
void ext2_set_file_ops(struct inode *inode)
{
inode->i_op = &ext2_file_inode_operations;
inode->i_fop = &ext2_file_operations;
if (IS_DAX(inode))
inode->i_mapping->a_ops = &ext2_dax_aops;
else
inode->i_mapping->a_ops = &ext2_aops;
}
struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
{
struct ext2_inode_info *ei;
struct buffer_head * bh = NULL;
struct ext2_inode *raw_inode;
struct inode *inode;
long ret = -EIO;
int n;
uid_t i_uid;
gid_t i_gid;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
ei = EXT2_I(inode);
ei->i_block_alloc_info = NULL;
raw_inode = ext2_get_inode(inode->i_sb, ino, &bh);
if (IS_ERR(raw_inode)) {
ret = PTR_ERR(raw_inode);
goto bad_inode;
}
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if (!(test_opt (inode->i_sb, NO_UID32))) {
i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
i_uid_write(inode, i_uid);
i_gid_write(inode, i_gid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
inode->i_size = le32_to_cpu(raw_inode->i_size);
inode->i_atime.tv_sec = (signed)le32_to_cpu(raw_inode->i_atime);
inode_set_ctime(inode, (signed)le32_to_cpu(raw_inode->i_ctime), 0);
inode->i_mtime.tv_sec = (signed)le32_to_cpu(raw_inode->i_mtime);
inode->i_atime.tv_nsec = inode->i_mtime.tv_nsec = 0;
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0 && (inode->i_mode == 0 || ei->i_dtime)) {
/* this inode is deleted */
ret = -ESTALE;
goto bad_inode;
}
inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
ext2_set_inode_flags(inode);
ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
ei->i_frag_no = raw_inode->i_frag;
ei->i_frag_size = raw_inode->i_fsize;
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
ei->i_dir_acl = 0;
if (ei->i_file_acl &&
!ext2_data_block_valid(EXT2_SB(sb), ei->i_file_acl, 1)) {
ext2_error(sb, "ext2_iget", "bad extended attribute block %u",
ei->i_file_acl);
ret = -EFSCORRUPTED;
goto bad_inode;
}
if (S_ISREG(inode->i_mode))
inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
else
ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
if (i_size_read(inode) < 0) {
ret = -EFSCORRUPTED;
goto bad_inode;
}
ei->i_dtime = 0;
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_state = 0;
ei->i_block_group = (ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
ei->i_dir_start_lookup = 0;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (n = 0; n < EXT2_N_BLOCKS; n++)
ei->i_data[n] = raw_inode->i_block[n];
if (S_ISREG(inode->i_mode)) {
ext2_set_file_ops(inode);
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext2_dir_inode_operations;
inode->i_fop = &ext2_dir_operations;
inode->i_mapping->a_ops = &ext2_aops;
} else if (S_ISLNK(inode->i_mode)) {
if (ext2_inode_is_fast_symlink(inode)) {
inode->i_link = (char *)ei->i_data;
inode->i_op = &ext2_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext2_symlink_inode_operations;
inode_nohighmem(inode);
inode->i_mapping->a_ops = &ext2_aops;
}
} else {
inode->i_op = &ext2_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
}
brelse (bh);
unlock_new_inode(inode);
return inode;
bad_inode:
brelse(bh);
iget_failed(inode);
return ERR_PTR(ret);
}
static int __ext2_write_inode(struct inode *inode, int do_sync)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
uid_t uid = i_uid_read(inode);
gid_t gid = i_gid_read(inode);
struct buffer_head * bh;
struct ext2_inode * raw_inode = ext2_get_inode(sb, ino, &bh);
int n;
int err = 0;
if (IS_ERR(raw_inode))
return -EIO;
/* For fields not tracking in the in-memory inode,
* initialise them to zero for new inodes. */
if (ei->i_state & EXT2_STATE_NEW)
memset(raw_inode, 0, EXT2_SB(sb)->s_inode_size);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
if (!(test_opt(sb, NO_UID32))) {
raw_inode->i_uid_low = cpu_to_le16(low_16_bits(uid));
raw_inode->i_gid_low = cpu_to_le16(low_16_bits(gid));
/*
* Fix up interoperability with old kernels. Otherwise, old inodes get
* re-used with the upper 16 bits of the uid/gid intact
*/
if (!ei->i_dtime) {
raw_inode->i_uid_high = cpu_to_le16(high_16_bits(uid));
raw_inode->i_gid_high = cpu_to_le16(high_16_bits(gid));
} else {
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
} else {
raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(uid));
raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(gid));
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
raw_inode->i_size = cpu_to_le32(inode->i_size);
raw_inode->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
raw_inode->i_ctime = cpu_to_le32(inode_get_ctime(inode).tv_sec);
raw_inode->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
raw_inode->i_flags = cpu_to_le32(ei->i_flags);
raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
raw_inode->i_frag = ei->i_frag_no;
raw_inode->i_fsize = ei->i_frag_size;
raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
if (!S_ISREG(inode->i_mode))
raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
else {
raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
if (inode->i_size > 0x7fffffffULL) {
if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
EXT2_SB(sb)->s_es->s_rev_level ==
cpu_to_le32(EXT2_GOOD_OLD_REV)) {
/* If this is the first large file
* created, add a flag to the superblock.
*/
spin_lock(&EXT2_SB(sb)->s_lock);
ext2_update_dynamic_rev(sb);
EXT2_SET_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
spin_unlock(&EXT2_SB(sb)->s_lock);
ext2_sync_super(sb, EXT2_SB(sb)->s_es, 1);
}
}
}
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
raw_inode->i_block[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
raw_inode->i_block[1] = 0;
} else {
raw_inode->i_block[0] = 0;
raw_inode->i_block[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
raw_inode->i_block[2] = 0;
}
} else for (n = 0; n < EXT2_N_BLOCKS; n++)
raw_inode->i_block[n] = ei->i_data[n];
mark_buffer_dirty(bh);
if (do_sync) {
sync_dirty_buffer(bh);
if (buffer_req(bh) && !buffer_uptodate(bh)) {
printk ("IO error syncing ext2 inode [%s:%08lx]\n",
sb->s_id, (unsigned long) ino);
err = -EIO;
}
}
ei->i_state &= ~EXT2_STATE_NEW;
brelse (bh);
return err;
}
int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return __ext2_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
}
int ext2_getattr(struct mnt_idmap *idmap, const struct path *path,
struct kstat *stat, u32 request_mask, unsigned int query_flags)
{
struct inode *inode = d_inode(path->dentry);
struct ext2_inode_info *ei = EXT2_I(inode);
unsigned int flags;
flags = ei->i_flags & EXT2_FL_USER_VISIBLE;
if (flags & EXT2_APPEND_FL)
stat->attributes |= STATX_ATTR_APPEND;
if (flags & EXT2_COMPR_FL)
stat->attributes |= STATX_ATTR_COMPRESSED;
if (flags & EXT2_IMMUTABLE_FL)
stat->attributes |= STATX_ATTR_IMMUTABLE;
if (flags & EXT2_NODUMP_FL)
stat->attributes |= STATX_ATTR_NODUMP;
stat->attributes_mask |= (STATX_ATTR_APPEND |
STATX_ATTR_COMPRESSED |
STATX_ATTR_ENCRYPTED |
STATX_ATTR_IMMUTABLE |
STATX_ATTR_NODUMP);
generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
return 0;
}
int ext2_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
struct iattr *iattr)
{
struct inode *inode = d_inode(dentry);
int error;
error = setattr_prepare(&nop_mnt_idmap, dentry, iattr);
if (error)
return error;
if (is_quota_modification(&nop_mnt_idmap, inode, iattr)) {
error = dquot_initialize(inode);
if (error)
return error;
}
if (i_uid_needs_update(&nop_mnt_idmap, iattr, inode) ||
i_gid_needs_update(&nop_mnt_idmap, iattr, inode)) {
error = dquot_transfer(&nop_mnt_idmap, inode, iattr);
if (error)
return error;
}
if (iattr->ia_valid & ATTR_SIZE && iattr->ia_size != inode->i_size) {
error = ext2_setsize(inode, iattr->ia_size);
if (error)
return error;
}
setattr_copy(&nop_mnt_idmap, inode, iattr);
if (iattr->ia_valid & ATTR_MODE)
error = posix_acl_chmod(&nop_mnt_idmap, dentry, inode->i_mode);
mark_inode_dirty(inode);
return error;
}
| linux-master | fs/ext2/inode.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/ioctl.c
*
* Copyright (C) 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include "ext2.h"
#include <linux/capability.h>
#include <linux/time.h>
#include <linux/sched.h>
#include <linux/compat.h>
#include <linux/mount.h>
#include <asm/current.h>
#include <linux/uaccess.h>
#include <linux/fileattr.h>
int ext2_fileattr_get(struct dentry *dentry, struct fileattr *fa)
{
struct ext2_inode_info *ei = EXT2_I(d_inode(dentry));
fileattr_fill_flags(fa, ei->i_flags & EXT2_FL_USER_VISIBLE);
return 0;
}
int ext2_fileattr_set(struct mnt_idmap *idmap,
struct dentry *dentry, struct fileattr *fa)
{
struct inode *inode = d_inode(dentry);
struct ext2_inode_info *ei = EXT2_I(inode);
if (fileattr_has_fsx(fa))
return -EOPNOTSUPP;
/* Is it quota file? Do not allow user to mess with it */
if (IS_NOQUOTA(inode))
return -EPERM;
ei->i_flags = (ei->i_flags & ~EXT2_FL_USER_MODIFIABLE) |
(fa->flags & EXT2_FL_USER_MODIFIABLE);
ext2_set_inode_flags(inode);
inode_set_ctime_current(inode);
mark_inode_dirty(inode);
return 0;
}
long ext2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = file_inode(filp);
struct ext2_inode_info *ei = EXT2_I(inode);
unsigned short rsv_window_size;
int ret;
ext2_debug ("cmd = %u, arg = %lu\n", cmd, arg);
switch (cmd) {
case EXT2_IOC_GETVERSION:
return put_user(inode->i_generation, (int __user *) arg);
case EXT2_IOC_SETVERSION: {
__u32 generation;
if (!inode_owner_or_capable(&nop_mnt_idmap, inode))
return -EPERM;
ret = mnt_want_write_file(filp);
if (ret)
return ret;
if (get_user(generation, (int __user *) arg)) {
ret = -EFAULT;
goto setversion_out;
}
inode_lock(inode);
inode_set_ctime_current(inode);
inode->i_generation = generation;
inode_unlock(inode);
mark_inode_dirty(inode);
setversion_out:
mnt_drop_write_file(filp);
return ret;
}
case EXT2_IOC_GETRSVSZ:
if (test_opt(inode->i_sb, RESERVATION)
&& S_ISREG(inode->i_mode)
&& ei->i_block_alloc_info) {
rsv_window_size = ei->i_block_alloc_info->rsv_window_node.rsv_goal_size;
return put_user(rsv_window_size, (int __user *)arg);
}
return -ENOTTY;
case EXT2_IOC_SETRSVSZ: {
if (!test_opt(inode->i_sb, RESERVATION) ||!S_ISREG(inode->i_mode))
return -ENOTTY;
if (!inode_owner_or_capable(&nop_mnt_idmap, inode))
return -EACCES;
if (get_user(rsv_window_size, (int __user *)arg))
return -EFAULT;
ret = mnt_want_write_file(filp);
if (ret)
return ret;
if (rsv_window_size > EXT2_MAX_RESERVE_BLOCKS)
rsv_window_size = EXT2_MAX_RESERVE_BLOCKS;
/*
* need to allocate reservation structure for this inode
* before set the window size
*/
/*
* XXX What lock should protect the rsv_goal_size?
* Accessed in ext2_get_block only. ext3 uses i_truncate.
*/
mutex_lock(&ei->truncate_mutex);
if (!ei->i_block_alloc_info)
ext2_init_block_alloc_info(inode);
if (ei->i_block_alloc_info){
struct ext2_reserve_window_node *rsv = &ei->i_block_alloc_info->rsv_window_node;
rsv->rsv_goal_size = rsv_window_size;
} else {
ret = -ENOMEM;
}
mutex_unlock(&ei->truncate_mutex);
mnt_drop_write_file(filp);
return ret;
}
default:
return -ENOTTY;
}
}
#ifdef CONFIG_COMPAT
long ext2_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
/* These are just misnamed, they actually get/put from/to user an int */
switch (cmd) {
case EXT2_IOC32_GETVERSION:
cmd = EXT2_IOC_GETVERSION;
break;
case EXT2_IOC32_SETVERSION:
cmd = EXT2_IOC_SETVERSION;
break;
default:
return -ENOIOCTLCMD;
}
return ext2_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
}
#endif
| linux-master | fs/ext2/ioctl.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/xattr_security.c
* Handler for storing security labels as extended attributes.
*/
#include "ext2.h"
#include <linux/security.h>
#include "xattr.h"
static int
ext2_xattr_security_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
return ext2_xattr_get(inode, EXT2_XATTR_INDEX_SECURITY, name,
buffer, size);
}
static int
ext2_xattr_security_set(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)
{
return ext2_xattr_set(inode, EXT2_XATTR_INDEX_SECURITY, name,
value, size, flags);
}
static int ext2_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *fs_info)
{
const struct xattr *xattr;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
err = ext2_xattr_set(inode, EXT2_XATTR_INDEX_SECURITY,
xattr->name, xattr->value,
xattr->value_len, 0);
if (err < 0)
break;
}
return err;
}
int
ext2_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
return security_inode_init_security(inode, dir, qstr,
&ext2_initxattrs, NULL);
}
const struct xattr_handler ext2_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.get = ext2_xattr_security_get,
.set = ext2_xattr_security_set,
};
| linux-master | fs/ext2/xattr_security.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/namei.c
*
* Rewrite to pagecache. Almost all code had been changed, so blame me
* if the things go wrong. Please, send bug reports to
* [email protected]
*
* Stuff here is basically a glue between the VFS and generic UNIXish
* filesystem that keeps everything in pagecache. All knowledge of the
* directory layout is in fs/ext2/dir.c - it turned out to be easily separatable
* and it's easier to debug that way. In principle we might want to
* generalize that a bit and turn it into a library. Or not.
*
* The only non-static object here is ext2_dir_inode_operations.
*
* TODO: get rid of kmap() use, add readahead.
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
static inline int ext2_add_nondir(struct dentry *dentry, struct inode *inode)
{
int err = ext2_add_link(dentry, inode);
if (!err) {
d_instantiate_new(dentry, inode);
return 0;
}
inode_dec_link_count(inode);
discard_new_inode(inode);
return err;
}
/*
* Methods themselves.
*/
static struct dentry *ext2_lookup(struct inode * dir, struct dentry *dentry, unsigned int flags)
{
struct inode * inode;
ino_t ino;
int res;
if (dentry->d_name.len > EXT2_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
res = ext2_inode_by_name(dir, &dentry->d_name, &ino);
if (res) {
if (res != -ENOENT)
return ERR_PTR(res);
inode = NULL;
} else {
inode = ext2_iget(dir->i_sb, ino);
if (inode == ERR_PTR(-ESTALE)) {
ext2_error(dir->i_sb, __func__,
"deleted inode referenced: %lu",
(unsigned long) ino);
return ERR_PTR(-EIO);
}
}
return d_splice_alias(inode, dentry);
}
struct dentry *ext2_get_parent(struct dentry *child)
{
ino_t ino;
int res;
res = ext2_inode_by_name(d_inode(child), &dotdot_name, &ino);
if (res)
return ERR_PTR(res);
return d_obtain_alias(ext2_iget(child->d_sb, ino));
}
/*
* By the time this is called, we already have created
* the directory cache entry for the new file, but it
* is so far negative - it has no inode.
*
* If the create succeeds, we fill in the inode information
* with d_instantiate().
*/
static int ext2_create (struct mnt_idmap * idmap,
struct inode * dir, struct dentry * dentry,
umode_t mode, bool excl)
{
struct inode *inode;
int err;
err = dquot_initialize(dir);
if (err)
return err;
inode = ext2_new_inode(dir, mode, &dentry->d_name);
if (IS_ERR(inode))
return PTR_ERR(inode);
ext2_set_file_ops(inode);
mark_inode_dirty(inode);
return ext2_add_nondir(dentry, inode);
}
static int ext2_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
struct file *file, umode_t mode)
{
struct inode *inode = ext2_new_inode(dir, mode, NULL);
if (IS_ERR(inode))
return PTR_ERR(inode);
ext2_set_file_ops(inode);
mark_inode_dirty(inode);
d_tmpfile(file, inode);
unlock_new_inode(inode);
return finish_open_simple(file, 0);
}
static int ext2_mknod (struct mnt_idmap * idmap, struct inode * dir,
struct dentry *dentry, umode_t mode, dev_t rdev)
{
struct inode * inode;
int err;
err = dquot_initialize(dir);
if (err)
return err;
inode = ext2_new_inode (dir, mode, &dentry->d_name);
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
init_special_inode(inode, inode->i_mode, rdev);
inode->i_op = &ext2_special_inode_operations;
mark_inode_dirty(inode);
err = ext2_add_nondir(dentry, inode);
}
return err;
}
static int ext2_symlink (struct mnt_idmap * idmap, struct inode * dir,
struct dentry * dentry, const char * symname)
{
struct super_block * sb = dir->i_sb;
int err = -ENAMETOOLONG;
unsigned l = strlen(symname)+1;
struct inode * inode;
if (l > sb->s_blocksize)
goto out;
err = dquot_initialize(dir);
if (err)
goto out;
inode = ext2_new_inode (dir, S_IFLNK | S_IRWXUGO, &dentry->d_name);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out;
if (l > sizeof (EXT2_I(inode)->i_data)) {
/* slow symlink */
inode->i_op = &ext2_symlink_inode_operations;
inode_nohighmem(inode);
inode->i_mapping->a_ops = &ext2_aops;
err = page_symlink(inode, symname, l);
if (err)
goto out_fail;
} else {
/* fast symlink */
inode->i_op = &ext2_fast_symlink_inode_operations;
inode->i_link = (char*)EXT2_I(inode)->i_data;
memcpy(inode->i_link, symname, l);
inode->i_size = l-1;
}
mark_inode_dirty(inode);
err = ext2_add_nondir(dentry, inode);
out:
return err;
out_fail:
inode_dec_link_count(inode);
discard_new_inode(inode);
goto out;
}
static int ext2_link (struct dentry * old_dentry, struct inode * dir,
struct dentry *dentry)
{
struct inode *inode = d_inode(old_dentry);
int err;
err = dquot_initialize(dir);
if (err)
return err;
inode_set_ctime_current(inode);
inode_inc_link_count(inode);
ihold(inode);
err = ext2_add_link(dentry, inode);
if (!err) {
d_instantiate(dentry, inode);
return 0;
}
inode_dec_link_count(inode);
iput(inode);
return err;
}
static int ext2_mkdir(struct mnt_idmap * idmap,
struct inode * dir, struct dentry * dentry, umode_t mode)
{
struct inode * inode;
int err;
err = dquot_initialize(dir);
if (err)
return err;
inode_inc_link_count(dir);
inode = ext2_new_inode(dir, S_IFDIR | mode, &dentry->d_name);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_dir;
inode->i_op = &ext2_dir_inode_operations;
inode->i_fop = &ext2_dir_operations;
inode->i_mapping->a_ops = &ext2_aops;
inode_inc_link_count(inode);
err = ext2_make_empty(inode, dir);
if (err)
goto out_fail;
err = ext2_add_link(dentry, inode);
if (err)
goto out_fail;
d_instantiate_new(dentry, inode);
out:
return err;
out_fail:
inode_dec_link_count(inode);
inode_dec_link_count(inode);
discard_new_inode(inode);
out_dir:
inode_dec_link_count(dir);
goto out;
}
static int ext2_unlink(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
struct ext2_dir_entry_2 *de;
struct page *page;
int err;
err = dquot_initialize(dir);
if (err)
goto out;
de = ext2_find_entry(dir, &dentry->d_name, &page);
if (IS_ERR(de)) {
err = PTR_ERR(de);
goto out;
}
err = ext2_delete_entry(de, page);
ext2_put_page(page, de);
if (err)
goto out;
inode_set_ctime_to_ts(inode, inode_get_ctime(dir));
inode_dec_link_count(inode);
err = 0;
out:
return err;
}
static int ext2_rmdir (struct inode * dir, struct dentry *dentry)
{
struct inode * inode = d_inode(dentry);
int err = -ENOTEMPTY;
if (ext2_empty_dir(inode)) {
err = ext2_unlink(dir, dentry);
if (!err) {
inode->i_size = 0;
inode_dec_link_count(inode);
inode_dec_link_count(dir);
}
}
return err;
}
static int ext2_rename (struct mnt_idmap * idmap,
struct inode * old_dir, struct dentry * old_dentry,
struct inode * new_dir, struct dentry * new_dentry,
unsigned int flags)
{
struct inode * old_inode = d_inode(old_dentry);
struct inode * new_inode = d_inode(new_dentry);
struct page * dir_page = NULL;
struct ext2_dir_entry_2 * dir_de = NULL;
struct page * old_page;
struct ext2_dir_entry_2 * old_de;
int err;
if (flags & ~RENAME_NOREPLACE)
return -EINVAL;
err = dquot_initialize(old_dir);
if (err)
return err;
err = dquot_initialize(new_dir);
if (err)
return err;
old_de = ext2_find_entry(old_dir, &old_dentry->d_name, &old_page);
if (IS_ERR(old_de))
return PTR_ERR(old_de);
if (S_ISDIR(old_inode->i_mode)) {
err = -EIO;
dir_de = ext2_dotdot(old_inode, &dir_page);
if (!dir_de)
goto out_old;
}
if (new_inode) {
struct page *new_page;
struct ext2_dir_entry_2 *new_de;
err = -ENOTEMPTY;
if (dir_de && !ext2_empty_dir (new_inode))
goto out_dir;
new_de = ext2_find_entry(new_dir, &new_dentry->d_name,
&new_page);
if (IS_ERR(new_de)) {
err = PTR_ERR(new_de);
goto out_dir;
}
err = ext2_set_link(new_dir, new_de, new_page, old_inode, true);
ext2_put_page(new_page, new_de);
if (err)
goto out_dir;
inode_set_ctime_current(new_inode);
if (dir_de)
drop_nlink(new_inode);
inode_dec_link_count(new_inode);
} else {
err = ext2_add_link(new_dentry, old_inode);
if (err)
goto out_dir;
if (dir_de)
inode_inc_link_count(new_dir);
}
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
inode_set_ctime_current(old_inode);
mark_inode_dirty(old_inode);
err = ext2_delete_entry(old_de, old_page);
if (!err && dir_de) {
if (old_dir != new_dir)
err = ext2_set_link(old_inode, dir_de, dir_page,
new_dir, false);
inode_dec_link_count(old_dir);
}
out_dir:
if (dir_de)
ext2_put_page(dir_page, dir_de);
out_old:
ext2_put_page(old_page, old_de);
return err;
}
const struct inode_operations ext2_dir_inode_operations = {
.create = ext2_create,
.lookup = ext2_lookup,
.link = ext2_link,
.unlink = ext2_unlink,
.symlink = ext2_symlink,
.mkdir = ext2_mkdir,
.rmdir = ext2_rmdir,
.mknod = ext2_mknod,
.rename = ext2_rename,
.listxattr = ext2_listxattr,
.getattr = ext2_getattr,
.setattr = ext2_setattr,
.get_inode_acl = ext2_get_acl,
.set_acl = ext2_set_acl,
.tmpfile = ext2_tmpfile,
.fileattr_get = ext2_fileattr_get,
.fileattr_set = ext2_fileattr_set,
};
const struct inode_operations ext2_special_inode_operations = {
.listxattr = ext2_listxattr,
.getattr = ext2_getattr,
.setattr = ext2_setattr,
.get_inode_acl = ext2_get_acl,
.set_acl = ext2_set_acl,
};
| linux-master | fs/ext2/namei.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <[email protected]>
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext2_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext2_acl_header))
return ERR_PTR(-EINVAL);
if (((ext2_acl_header *)value)->a_version !=
cpu_to_le32(EXT2_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext2_acl_header);
count = ext2_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n=0; n < count; n++) {
ext2_acl_entry *entry =
(ext2_acl_entry *)value;
if ((char *)value + sizeof(ext2_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext2_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext2_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext2_acl_header *ext_acl;
char *e;
size_t n;
*size = ext2_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext2_acl_header) + acl->a_count *
sizeof(ext2_acl_entry), GFP_KERNEL);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT2_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext2_acl_header);
for (n=0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext2_acl_entry *entry = (ext2_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext2_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext2_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext2_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* inode->i_mutex: don't care
*/
struct posix_acl *
ext2_get_acl(struct inode *inode, int type, bool rcu)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
if (rcu)
return ERR_PTR(-ECHILD);
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext2_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext2_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext2_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
static int
__ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch(type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext2_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
/*
* inode->i_mutex: down
*/
int
ext2_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
struct posix_acl *acl, int type)
{
int error;
int update_mode = 0;
struct inode *inode = d_inode(dentry);
umode_t mode = inode->i_mode;
if (type == ACL_TYPE_ACCESS && acl) {
error = posix_acl_update_mode(&nop_mnt_idmap, inode, &mode,
&acl);
if (error)
return error;
update_mode = 1;
}
error = __ext2_set_acl(inode, acl, type);
if (!error && update_mode) {
inode->i_mode = mode;
inode_set_ctime_current(inode);
mark_inode_dirty(inode);
}
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext2_new_inode.
*
* dir->i_mutex: down
* inode->i_mutex: up (access to inode is still exclusive)
*/
int
ext2_init_acl(struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = __ext2_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
} else {
inode->i_default_acl = NULL;
}
if (acl) {
if (!error)
error = __ext2_set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
} else {
inode->i_acl = NULL;
}
return error;
}
| linux-master | fs/ext2/acl.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/symlink.c
*
* Only fast symlinks left here - the rest is done by generic code. AV, 1999
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/symlink.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext2 symlink handling code
*/
#include "ext2.h"
#include "xattr.h"
const struct inode_operations ext2_symlink_inode_operations = {
.get_link = page_get_link,
.getattr = ext2_getattr,
.setattr = ext2_setattr,
.listxattr = ext2_listxattr,
};
const struct inode_operations ext2_fast_symlink_inode_operations = {
.get_link = simple_get_link,
.getattr = ext2_getattr,
.setattr = ext2_setattr,
.listxattr = ext2_listxattr,
};
| linux-master | fs/ext2/symlink.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/file.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/file.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext2 fs regular file handling primitives
*
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* ([email protected])
*/
#include <linux/time.h>
#include <linux/pagemap.h>
#include <linux/dax.h>
#include <linux/quotaops.h>
#include <linux/iomap.h>
#include <linux/uio.h>
#include <linux/buffer_head.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
#include "trace.h"
#ifdef CONFIG_FS_DAX
static ssize_t ext2_dax_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct inode *inode = iocb->ki_filp->f_mapping->host;
ssize_t ret;
if (!iov_iter_count(to))
return 0; /* skip atime */
inode_lock_shared(inode);
ret = dax_iomap_rw(iocb, to, &ext2_iomap_ops);
inode_unlock_shared(inode);
file_accessed(iocb->ki_filp);
return ret;
}
static ssize_t ext2_dax_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
inode_lock(inode);
ret = generic_write_checks(iocb, from);
if (ret <= 0)
goto out_unlock;
ret = file_remove_privs(file);
if (ret)
goto out_unlock;
ret = file_update_time(file);
if (ret)
goto out_unlock;
ret = dax_iomap_rw(iocb, from, &ext2_iomap_ops);
if (ret > 0 && iocb->ki_pos > i_size_read(inode)) {
i_size_write(inode, iocb->ki_pos);
mark_inode_dirty(inode);
}
out_unlock:
inode_unlock(inode);
if (ret > 0)
ret = generic_write_sync(iocb, ret);
return ret;
}
/*
* The lock ordering for ext2 DAX fault paths is:
*
* mmap_lock (MM)
* sb_start_pagefault (vfs, freeze)
* address_space->invalidate_lock
* address_space->i_mmap_rwsem or page_lock (mutually exclusive in DAX)
* ext2_inode_info->truncate_mutex
*
* The default page_lock and i_size verification done by non-DAX fault paths
* is sufficient because ext2 doesn't support hole punching.
*/
static vm_fault_t ext2_dax_fault(struct vm_fault *vmf)
{
struct inode *inode = file_inode(vmf->vma->vm_file);
vm_fault_t ret;
bool write = (vmf->flags & FAULT_FLAG_WRITE) &&
(vmf->vma->vm_flags & VM_SHARED);
if (write) {
sb_start_pagefault(inode->i_sb);
file_update_time(vmf->vma->vm_file);
}
filemap_invalidate_lock_shared(inode->i_mapping);
ret = dax_iomap_fault(vmf, 0, NULL, NULL, &ext2_iomap_ops);
filemap_invalidate_unlock_shared(inode->i_mapping);
if (write)
sb_end_pagefault(inode->i_sb);
return ret;
}
static const struct vm_operations_struct ext2_dax_vm_ops = {
.fault = ext2_dax_fault,
/*
* .huge_fault is not supported for DAX because allocation in ext2
* cannot be reliably aligned to huge page sizes and so pmd faults
* will always fail and fail back to regular faults.
*/
.page_mkwrite = ext2_dax_fault,
.pfn_mkwrite = ext2_dax_fault,
};
static int ext2_file_mmap(struct file *file, struct vm_area_struct *vma)
{
if (!IS_DAX(file_inode(file)))
return generic_file_mmap(file, vma);
file_accessed(file);
vma->vm_ops = &ext2_dax_vm_ops;
return 0;
}
#else
#define ext2_file_mmap generic_file_mmap
#endif
/*
* Called when filp is released. This happens when all file descriptors
* for a single struct file are closed. Note that different open() calls
* for the same file yield different struct file structures.
*/
static int ext2_release_file (struct inode * inode, struct file * filp)
{
if (filp->f_mode & FMODE_WRITE) {
mutex_lock(&EXT2_I(inode)->truncate_mutex);
ext2_discard_reservation(inode);
mutex_unlock(&EXT2_I(inode)->truncate_mutex);
}
return 0;
}
int ext2_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
int ret;
struct super_block *sb = file->f_mapping->host->i_sb;
ret = generic_buffers_fsync(file, start, end, datasync);
if (ret == -EIO)
/* We don't really know where the IO error happened... */
ext2_error(sb, __func__,
"detected IO error when writing metadata buffers");
return ret;
}
static ssize_t ext2_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
trace_ext2_dio_read_begin(iocb, to, 0);
inode_lock_shared(inode);
ret = iomap_dio_rw(iocb, to, &ext2_iomap_ops, NULL, 0, NULL, 0);
inode_unlock_shared(inode);
trace_ext2_dio_read_end(iocb, to, ret);
return ret;
}
static int ext2_dio_write_end_io(struct kiocb *iocb, ssize_t size,
int error, unsigned int flags)
{
loff_t pos = iocb->ki_pos;
struct inode *inode = file_inode(iocb->ki_filp);
if (error)
goto out;
/*
* If we are extending the file, we have to update i_size here before
* page cache gets invalidated in iomap_dio_rw(). This prevents racing
* buffered reads from zeroing out too much from page cache pages.
* Note that all extending writes always happens synchronously with
* inode lock held by ext2_dio_write_iter(). So it is safe to update
* inode size here for extending file writes.
*/
pos += size;
if (pos > i_size_read(inode)) {
i_size_write(inode, pos);
mark_inode_dirty(inode);
}
out:
trace_ext2_dio_write_endio(iocb, size, error);
return error;
}
static const struct iomap_dio_ops ext2_dio_write_ops = {
.end_io = ext2_dio_write_end_io,
};
static ssize_t ext2_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
unsigned int flags = 0;
unsigned long blocksize = inode->i_sb->s_blocksize;
loff_t offset = iocb->ki_pos;
loff_t count = iov_iter_count(from);
ssize_t status = 0;
trace_ext2_dio_write_begin(iocb, from, 0);
inode_lock(inode);
ret = generic_write_checks(iocb, from);
if (ret <= 0)
goto out_unlock;
ret = kiocb_modified(iocb);
if (ret)
goto out_unlock;
/* use IOMAP_DIO_FORCE_WAIT for unaligned or extending writes */
if (iocb->ki_pos + iov_iter_count(from) > i_size_read(inode) ||
(!IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(from), blocksize)))
flags |= IOMAP_DIO_FORCE_WAIT;
ret = iomap_dio_rw(iocb, from, &ext2_iomap_ops, &ext2_dio_write_ops,
flags, NULL, 0);
/* ENOTBLK is magic return value for fallback to buffered-io */
if (ret == -ENOTBLK)
ret = 0;
if (ret < 0 && ret != -EIOCBQUEUED)
ext2_write_failed(inode->i_mapping, offset + count);
/* handle case for partial write and for fallback to buffered write */
if (ret >= 0 && iov_iter_count(from)) {
loff_t pos, endbyte;
int ret2;
iocb->ki_flags &= ~IOCB_DIRECT;
pos = iocb->ki_pos;
status = generic_perform_write(iocb, from);
if (unlikely(status < 0)) {
ret = status;
goto out_unlock;
}
iocb->ki_pos += status;
ret += status;
endbyte = pos + status - 1;
ret2 = filemap_write_and_wait_range(inode->i_mapping, pos,
endbyte);
if (!ret2)
invalidate_mapping_pages(inode->i_mapping,
pos >> PAGE_SHIFT,
endbyte >> PAGE_SHIFT);
if (ret > 0)
generic_write_sync(iocb, ret);
}
out_unlock:
inode_unlock(inode);
if (status)
trace_ext2_dio_write_buff_end(iocb, from, status);
trace_ext2_dio_write_end(iocb, from, ret);
return ret;
}
static ssize_t ext2_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
#ifdef CONFIG_FS_DAX
if (IS_DAX(iocb->ki_filp->f_mapping->host))
return ext2_dax_read_iter(iocb, to);
#endif
if (iocb->ki_flags & IOCB_DIRECT)
return ext2_dio_read_iter(iocb, to);
return generic_file_read_iter(iocb, to);
}
static ssize_t ext2_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
#ifdef CONFIG_FS_DAX
if (IS_DAX(iocb->ki_filp->f_mapping->host))
return ext2_dax_write_iter(iocb, from);
#endif
if (iocb->ki_flags & IOCB_DIRECT)
return ext2_dio_write_iter(iocb, from);
return generic_file_write_iter(iocb, from);
}
const struct file_operations ext2_file_operations = {
.llseek = generic_file_llseek,
.read_iter = ext2_file_read_iter,
.write_iter = ext2_file_write_iter,
.unlocked_ioctl = ext2_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ext2_compat_ioctl,
#endif
.mmap = ext2_file_mmap,
.open = dquot_file_open,
.release = ext2_release_file,
.fsync = ext2_fsync,
.get_unmapped_area = thp_get_unmapped_area,
.splice_read = filemap_splice_read,
.splice_write = iter_file_splice_write,
};
const struct inode_operations ext2_file_inode_operations = {
.listxattr = ext2_listxattr,
.getattr = ext2_getattr,
.setattr = ext2_setattr,
.get_inode_acl = ext2_get_acl,
.set_acl = ext2_set_acl,
.fiemap = ext2_fiemap,
.fileattr_get = ext2_fileattr_get,
.fileattr_set = ext2_fileattr_set,
};
| linux-master | fs/ext2/file.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/ialloc.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* BSD ufs-inspired inode and directory allocation by
* Stephen Tweedie ([email protected]), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/quotaops.h>
#include <linux/sched.h>
#include <linux/backing-dev.h>
#include <linux/buffer_head.h>
#include <linux/random.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
/*
* ialloc.c contains the inodes allocation and deallocation routines
*/
/*
* The free inodes are managed by bitmaps. A file system contains several
* blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap
* block for inodes, N blocks for the inode table and data blocks.
*
* The file system contains group descriptors which are located after the
* super block. Each descriptor contains the number of the bitmap block and
* the free blocks count in the block.
*/
/*
* Read the inode allocation bitmap for a given block_group, reading
* into the specified slot in the superblock's bitmap cache.
*
* Return buffer_head of bitmap on success or NULL.
*/
static struct buffer_head *
read_inode_bitmap(struct super_block * sb, unsigned long block_group)
{
struct ext2_group_desc *desc;
struct buffer_head *bh = NULL;
desc = ext2_get_group_desc(sb, block_group, NULL);
if (!desc)
goto error_out;
bh = sb_bread(sb, le32_to_cpu(desc->bg_inode_bitmap));
if (!bh)
ext2_error(sb, "read_inode_bitmap",
"Cannot read inode bitmap - "
"block_group = %lu, inode_bitmap = %u",
block_group, le32_to_cpu(desc->bg_inode_bitmap));
error_out:
return bh;
}
static void ext2_release_inode(struct super_block *sb, int group, int dir)
{
struct ext2_group_desc * desc;
struct buffer_head *bh;
desc = ext2_get_group_desc(sb, group, &bh);
if (!desc) {
ext2_error(sb, "ext2_release_inode",
"can't get descriptor for group %d", group);
return;
}
spin_lock(sb_bgl_lock(EXT2_SB(sb), group));
le16_add_cpu(&desc->bg_free_inodes_count, 1);
if (dir)
le16_add_cpu(&desc->bg_used_dirs_count, -1);
spin_unlock(sb_bgl_lock(EXT2_SB(sb), group));
percpu_counter_inc(&EXT2_SB(sb)->s_freeinodes_counter);
if (dir)
percpu_counter_dec(&EXT2_SB(sb)->s_dirs_counter);
mark_buffer_dirty(bh);
}
/*
* NOTE! When we get the inode, we're the only people
* that have access to it, and as such there are no
* race conditions we have to worry about. The inode
* is not on the hash-lists, and it cannot be reached
* through the filesystem because the directory entry
* has been deleted earlier.
*
* HOWEVER: we must make sure that we get no aliases,
* which means that we have to call "clear_inode()"
* _before_ we mark the inode not in use in the inode
* bitmaps. Otherwise a newly created file might use
* the same inode number (not actually the same pointer
* though), and then we'd have two inodes sharing the
* same inode number and space on the harddisk.
*/
void ext2_free_inode (struct inode * inode)
{
struct super_block * sb = inode->i_sb;
int is_directory;
unsigned long ino;
struct buffer_head *bitmap_bh;
unsigned long block_group;
unsigned long bit;
struct ext2_super_block * es;
ino = inode->i_ino;
ext2_debug ("freeing inode %lu\n", ino);
/*
* Note: we must free any quota before locking the superblock,
* as writing the quota to disk may need the lock as well.
*/
/* Quota is already initialized in iput() */
dquot_free_inode(inode);
dquot_drop(inode);
es = EXT2_SB(sb)->s_es;
is_directory = S_ISDIR(inode->i_mode);
if (ino < EXT2_FIRST_INO(sb) ||
ino > le32_to_cpu(es->s_inodes_count)) {
ext2_error (sb, "ext2_free_inode",
"reserved or nonexistent inode %lu", ino);
return;
}
block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
bit = (ino - 1) % EXT2_INODES_PER_GROUP(sb);
bitmap_bh = read_inode_bitmap(sb, block_group);
if (!bitmap_bh)
return;
/* Ok, now we can actually update the inode bitmaps.. */
if (!ext2_clear_bit_atomic(sb_bgl_lock(EXT2_SB(sb), block_group),
bit, (void *) bitmap_bh->b_data))
ext2_error (sb, "ext2_free_inode",
"bit already cleared for inode %lu", ino);
else
ext2_release_inode(sb, block_group, is_directory);
mark_buffer_dirty(bitmap_bh);
if (sb->s_flags & SB_SYNCHRONOUS)
sync_dirty_buffer(bitmap_bh);
brelse(bitmap_bh);
}
/*
* We perform asynchronous prereading of the new inode's inode block when
* we create the inode, in the expectation that the inode will be written
* back soon. There are two reasons:
*
* - When creating a large number of files, the async prereads will be
* nicely merged into large reads
* - When writing out a large number of inodes, we don't need to keep on
* stalling the writes while we read the inode block.
*
* FIXME: ext2_get_group_desc() needs to be simplified.
*/
static void ext2_preread_inode(struct inode *inode)
{
unsigned long block_group;
unsigned long offset;
unsigned long block;
struct ext2_group_desc * gdp;
block_group = (inode->i_ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
gdp = ext2_get_group_desc(inode->i_sb, block_group, NULL);
if (gdp == NULL)
return;
/*
* Figure out the offset within the block group inode table
*/
offset = ((inode->i_ino - 1) % EXT2_INODES_PER_GROUP(inode->i_sb)) *
EXT2_INODE_SIZE(inode->i_sb);
block = le32_to_cpu(gdp->bg_inode_table) +
(offset >> EXT2_BLOCK_SIZE_BITS(inode->i_sb));
sb_breadahead(inode->i_sb, block);
}
/*
* There are two policies for allocating an inode. If the new inode is
* a directory, then a forward search is made for a block group with both
* free space and a low directory-to-inode ratio; if that fails, then of
* the groups with above-average free space, that group with the fewest
* directories already is chosen.
*
* For other inodes, search forward from the parent directory\'s block
* group to find a free inode.
*/
static int find_group_dir(struct super_block *sb, struct inode *parent)
{
int ngroups = EXT2_SB(sb)->s_groups_count;
int avefreei = ext2_count_free_inodes(sb) / ngroups;
struct ext2_group_desc *desc, *best_desc = NULL;
int group, best_group = -1;
for (group = 0; group < ngroups; group++) {
desc = ext2_get_group_desc (sb, group, NULL);
if (!desc || !desc->bg_free_inodes_count)
continue;
if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
continue;
if (!best_desc ||
(le16_to_cpu(desc->bg_free_blocks_count) >
le16_to_cpu(best_desc->bg_free_blocks_count))) {
best_group = group;
best_desc = desc;
}
}
return best_group;
}
/*
* Orlov's allocator for directories.
*
* We always try to spread first-level directories.
*
* If there are blockgroups with both free inodes and free blocks counts
* not worse than average we return one with smallest directory count.
* Otherwise we simply return a random group.
*
* For the rest rules look so:
*
* It's OK to put directory into a group unless
* it has too many directories already (max_dirs) or
* it has too few free inodes left (min_inodes) or
* it has too few free blocks left (min_blocks) or
* it's already running too large debt (max_debt).
* Parent's group is preferred, if it doesn't satisfy these
* conditions we search cyclically through the rest. If none
* of the groups look good we just look for a group with more
* free inodes than average (starting at parent's group).
*
* Debt is incremented each time we allocate a directory and decremented
* when we allocate an inode, within 0--255.
*/
#define INODE_COST 64
#define BLOCK_COST 256
static int find_group_orlov(struct super_block *sb, struct inode *parent)
{
int parent_group = EXT2_I(parent)->i_block_group;
struct ext2_sb_info *sbi = EXT2_SB(sb);
struct ext2_super_block *es = sbi->s_es;
int ngroups = sbi->s_groups_count;
int inodes_per_group = EXT2_INODES_PER_GROUP(sb);
int freei;
int avefreei;
int free_blocks;
int avefreeb;
int blocks_per_dir;
int ndirs;
int max_debt, max_dirs, min_blocks, min_inodes;
int group = -1, i;
struct ext2_group_desc *desc;
freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
avefreei = freei / ngroups;
free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
avefreeb = free_blocks / ngroups;
ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
if ((parent == d_inode(sb->s_root)) ||
(EXT2_I(parent)->i_flags & EXT2_TOPDIR_FL)) {
int best_ndir = inodes_per_group;
int best_group = -1;
parent_group = get_random_u32_below(ngroups);
for (i = 0; i < ngroups; i++) {
group = (parent_group + i) % ngroups;
desc = ext2_get_group_desc (sb, group, NULL);
if (!desc || !desc->bg_free_inodes_count)
continue;
if (le16_to_cpu(desc->bg_used_dirs_count) >= best_ndir)
continue;
if (le16_to_cpu(desc->bg_free_inodes_count) < avefreei)
continue;
if (le16_to_cpu(desc->bg_free_blocks_count) < avefreeb)
continue;
best_group = group;
best_ndir = le16_to_cpu(desc->bg_used_dirs_count);
}
if (best_group >= 0) {
group = best_group;
goto found;
}
goto fallback;
}
if (ndirs == 0)
ndirs = 1; /* percpu_counters are approximate... */
blocks_per_dir = (le32_to_cpu(es->s_blocks_count)-free_blocks) / ndirs;
max_dirs = ndirs / ngroups + inodes_per_group / 16;
min_inodes = avefreei - inodes_per_group / 4;
min_blocks = avefreeb - EXT2_BLOCKS_PER_GROUP(sb) / 4;
max_debt = EXT2_BLOCKS_PER_GROUP(sb) / max(blocks_per_dir, BLOCK_COST);
if (max_debt * INODE_COST > inodes_per_group)
max_debt = inodes_per_group / INODE_COST;
if (max_debt > 255)
max_debt = 255;
if (max_debt == 0)
max_debt = 1;
for (i = 0; i < ngroups; i++) {
group = (parent_group + i) % ngroups;
desc = ext2_get_group_desc (sb, group, NULL);
if (!desc || !desc->bg_free_inodes_count)
continue;
if (sbi->s_debts[group] >= max_debt)
continue;
if (le16_to_cpu(desc->bg_used_dirs_count) >= max_dirs)
continue;
if (le16_to_cpu(desc->bg_free_inodes_count) < min_inodes)
continue;
if (le16_to_cpu(desc->bg_free_blocks_count) < min_blocks)
continue;
goto found;
}
fallback:
for (i = 0; i < ngroups; i++) {
group = (parent_group + i) % ngroups;
desc = ext2_get_group_desc (sb, group, NULL);
if (!desc || !desc->bg_free_inodes_count)
continue;
if (le16_to_cpu(desc->bg_free_inodes_count) >= avefreei)
goto found;
}
if (avefreei) {
/*
* The free-inodes counter is approximate, and for really small
* filesystems the above test can fail to find any blockgroups
*/
avefreei = 0;
goto fallback;
}
return -1;
found:
return group;
}
static int find_group_other(struct super_block *sb, struct inode *parent)
{
int parent_group = EXT2_I(parent)->i_block_group;
int ngroups = EXT2_SB(sb)->s_groups_count;
struct ext2_group_desc *desc;
int group, i;
/*
* Try to place the inode in its parent directory
*/
group = parent_group;
desc = ext2_get_group_desc (sb, group, NULL);
if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
le16_to_cpu(desc->bg_free_blocks_count))
goto found;
/*
* We're going to place this inode in a different blockgroup from its
* parent. We want to cause files in a common directory to all land in
* the same blockgroup. But we want files which are in a different
* directory which shares a blockgroup with our parent to land in a
* different blockgroup.
*
* So add our directory's i_ino into the starting point for the hash.
*/
group = (group + parent->i_ino) % ngroups;
/*
* Use a quadratic hash to find a group with a free inode and some
* free blocks.
*/
for (i = 1; i < ngroups; i <<= 1) {
group += i;
if (group >= ngroups)
group -= ngroups;
desc = ext2_get_group_desc (sb, group, NULL);
if (desc && le16_to_cpu(desc->bg_free_inodes_count) &&
le16_to_cpu(desc->bg_free_blocks_count))
goto found;
}
/*
* That failed: try linear search for a free inode, even if that group
* has no free blocks.
*/
group = parent_group;
for (i = 0; i < ngroups; i++) {
if (++group >= ngroups)
group = 0;
desc = ext2_get_group_desc (sb, group, NULL);
if (desc && le16_to_cpu(desc->bg_free_inodes_count))
goto found;
}
return -1;
found:
return group;
}
struct inode *ext2_new_inode(struct inode *dir, umode_t mode,
const struct qstr *qstr)
{
struct super_block *sb;
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *bh2;
int group, i;
ino_t ino = 0;
struct inode * inode;
struct ext2_group_desc *gdp;
struct ext2_super_block *es;
struct ext2_inode_info *ei;
struct ext2_sb_info *sbi;
int err;
sb = dir->i_sb;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
ei = EXT2_I(inode);
sbi = EXT2_SB(sb);
es = sbi->s_es;
if (S_ISDIR(mode)) {
if (test_opt(sb, OLDALLOC))
group = find_group_dir(sb, dir);
else
group = find_group_orlov(sb, dir);
} else
group = find_group_other(sb, dir);
if (group == -1) {
err = -ENOSPC;
goto fail;
}
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext2_get_group_desc(sb, group, &bh2);
if (!gdp) {
if (++group == sbi->s_groups_count)
group = 0;
continue;
}
brelse(bitmap_bh);
bitmap_bh = read_inode_bitmap(sb, group);
if (!bitmap_bh) {
err = -EIO;
goto fail;
}
ino = 0;
repeat_in_this_group:
ino = ext2_find_next_zero_bit((unsigned long *)bitmap_bh->b_data,
EXT2_INODES_PER_GROUP(sb), ino);
if (ino >= EXT2_INODES_PER_GROUP(sb)) {
/*
* Rare race: find_group_xx() decided that there were
* free inodes in this group, but by the time we tried
* to allocate one, they're all gone. This can also
* occur because the counters which find_group_orlov()
* uses are approximate. So just go and search the
* next block group.
*/
if (++group == sbi->s_groups_count)
group = 0;
continue;
}
if (ext2_set_bit_atomic(sb_bgl_lock(sbi, group),
ino, bitmap_bh->b_data)) {
/* we lost this inode */
if (++ino >= EXT2_INODES_PER_GROUP(sb)) {
/* this group is exhausted, try next group */
if (++group == sbi->s_groups_count)
group = 0;
continue;
}
/* try to find free inode in the same group */
goto repeat_in_this_group;
}
goto got;
}
/*
* Scanned all blockgroups.
*/
brelse(bitmap_bh);
err = -ENOSPC;
goto fail;
got:
mark_buffer_dirty(bitmap_bh);
if (sb->s_flags & SB_SYNCHRONOUS)
sync_dirty_buffer(bitmap_bh);
brelse(bitmap_bh);
ino += group * EXT2_INODES_PER_GROUP(sb) + 1;
if (ino < EXT2_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
ext2_error (sb, "ext2_new_inode",
"reserved inode or inode > inodes count - "
"block_group = %d,inode=%lu", group,
(unsigned long) ino);
err = -EIO;
goto fail;
}
percpu_counter_dec(&sbi->s_freeinodes_counter);
if (S_ISDIR(mode))
percpu_counter_inc(&sbi->s_dirs_counter);
spin_lock(sb_bgl_lock(sbi, group));
le16_add_cpu(&gdp->bg_free_inodes_count, -1);
if (S_ISDIR(mode)) {
if (sbi->s_debts[group] < 255)
sbi->s_debts[group]++;
le16_add_cpu(&gdp->bg_used_dirs_count, 1);
} else {
if (sbi->s_debts[group])
sbi->s_debts[group]--;
}
spin_unlock(sb_bgl_lock(sbi, group));
mark_buffer_dirty(bh2);
if (test_opt(sb, GRPID)) {
inode->i_mode = mode;
inode->i_uid = current_fsuid();
inode->i_gid = dir->i_gid;
} else
inode_init_owner(&nop_mnt_idmap, inode, dir, mode);
inode->i_ino = ino;
inode->i_blocks = 0;
inode->i_mtime = inode->i_atime = inode_set_ctime_current(inode);
memset(ei->i_data, 0, sizeof(ei->i_data));
ei->i_flags =
ext2_mask_flags(mode, EXT2_I(dir)->i_flags & EXT2_FL_INHERITED);
ei->i_faddr = 0;
ei->i_frag_no = 0;
ei->i_frag_size = 0;
ei->i_file_acl = 0;
ei->i_dir_acl = 0;
ei->i_dtime = 0;
ei->i_block_alloc_info = NULL;
ei->i_block_group = group;
ei->i_dir_start_lookup = 0;
ei->i_state = EXT2_STATE_NEW;
ext2_set_inode_flags(inode);
spin_lock(&sbi->s_next_gen_lock);
inode->i_generation = sbi->s_next_generation++;
spin_unlock(&sbi->s_next_gen_lock);
if (insert_inode_locked(inode) < 0) {
ext2_error(sb, "ext2_new_inode",
"inode number already in use - inode=%lu",
(unsigned long) ino);
err = -EIO;
goto fail;
}
err = dquot_initialize(inode);
if (err)
goto fail_drop;
err = dquot_alloc_inode(inode);
if (err)
goto fail_drop;
err = ext2_init_acl(inode, dir);
if (err)
goto fail_free_drop;
err = ext2_init_security(inode, dir, qstr);
if (err)
goto fail_free_drop;
mark_inode_dirty(inode);
ext2_debug("allocating inode %lu\n", inode->i_ino);
ext2_preread_inode(inode);
return inode;
fail_free_drop:
dquot_free_inode(inode);
fail_drop:
dquot_drop(inode);
inode->i_flags |= S_NOQUOTA;
clear_nlink(inode);
discard_new_inode(inode);
return ERR_PTR(err);
fail:
make_bad_inode(inode);
iput(inode);
return ERR_PTR(err);
}
unsigned long ext2_count_free_inodes (struct super_block * sb)
{
struct ext2_group_desc *desc;
unsigned long desc_count = 0;
int i;
#ifdef EXT2FS_DEBUG
struct ext2_super_block *es;
unsigned long bitmap_count = 0;
struct buffer_head *bitmap_bh = NULL;
es = EXT2_SB(sb)->s_es;
for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
unsigned x;
desc = ext2_get_group_desc (sb, i, NULL);
if (!desc)
continue;
desc_count += le16_to_cpu(desc->bg_free_inodes_count);
brelse(bitmap_bh);
bitmap_bh = read_inode_bitmap(sb, i);
if (!bitmap_bh)
continue;
x = ext2_count_free(bitmap_bh, EXT2_INODES_PER_GROUP(sb) / 8);
printk("group %d: stored = %d, counted = %u\n",
i, le16_to_cpu(desc->bg_free_inodes_count), x);
bitmap_count += x;
}
brelse(bitmap_bh);
printk("ext2_count_free_inodes: stored = %lu, computed = %lu, %lu\n",
(unsigned long)
percpu_counter_read(&EXT2_SB(sb)->s_freeinodes_counter),
desc_count, bitmap_count);
return desc_count;
#else
for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
desc = ext2_get_group_desc (sb, i, NULL);
if (!desc)
continue;
desc_count += le16_to_cpu(desc->bg_free_inodes_count);
}
return desc_count;
#endif
}
/* Called at mount-time, super-block is locked */
unsigned long ext2_count_dirs (struct super_block * sb)
{
unsigned long count = 0;
int i;
for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
struct ext2_group_desc *gdp = ext2_get_group_desc (sb, i, NULL);
if (!gdp)
continue;
count += le16_to_cpu(gdp->bg_used_dirs_count);
}
return count;
}
| linux-master | fs/ext2/ialloc.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*
* terminology
*
* cluster - allocation unit - 512,1K,2K,4K,...,2M
* vcn - virtual cluster number - Offset inside the file in clusters.
* vbo - virtual byte offset - Offset inside the file in bytes.
* lcn - logical cluster number - 0 based cluster in clusters heap.
* lbo - logical byte offset - Absolute position inside volume.
* run - maps VCN to LCN - Stored in attributes in packed form.
* attr - attribute segment - std/name/data etc records inside MFT.
* mi - MFT inode - One MFT record(usually 1024 bytes or 4K), consists of attributes.
* ni - NTFS inode - Extends linux inode. consists of one or more mft inodes.
* index - unit inside directory - 2K, 4K, <=page size, does not depend on cluster size.
*
* WSL - Windows Subsystem for Linux
* https://docs.microsoft.com/en-us/windows/wsl/file-permissions
* It stores uid/gid/mode/dev in xattr
*
* ntfs allows up to 2^64 clusters per volume.
* It means you should use 64 bits lcn to operate with ntfs.
* Implementation of ntfs.sys uses only 32 bits lcn.
* Default ntfs3 uses 32 bits lcn too.
* ntfs3 built with CONFIG_NTFS3_64BIT_CLUSTER (ntfs3_64) uses 64 bits per lcn.
*
*
* ntfs limits, cluster size is 4K (2^12)
* -----------------------------------------------------------------------------
* | Volume size | Clusters | ntfs.sys | ntfs3 | ntfs3_64 | mkntfs | chkdsk |
* -----------------------------------------------------------------------------
* | < 16T, 2^44 | < 2^32 | yes | yes | yes | yes | yes |
* | > 16T, 2^44 | > 2^32 | no | no | yes | yes | yes |
* ----------------------------------------------------------|------------------
*
* To mount large volumes as ntfs one should use large cluster size (up to 2M)
* The maximum volume size in this case is 2^32 * 2^21 = 2^53 = 8P
*
* ntfs limits, cluster size is 2M (2^21)
* -----------------------------------------------------------------------------
* | < 8P, 2^53 | < 2^32 | yes | yes | yes | yes | yes |
* | > 8P, 2^53 | > 2^32 | no | no | yes | yes | yes |
* ----------------------------------------------------------|------------------
*
*/
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/fs.h>
#include <linux/fs_context.h>
#include <linux/fs_parser.h>
#include <linux/log2.h>
#include <linux/minmax.h>
#include <linux/module.h>
#include <linux/nls.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/statfs.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
#ifdef CONFIG_NTFS3_LZX_XPRESS
#include "lib/lib.h"
#endif
#ifdef CONFIG_PRINTK
/*
* ntfs_printk - Trace warnings/notices/errors.
*
* Thanks Joe Perches <[email protected]> for implementation
*/
void ntfs_printk(const struct super_block *sb, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
int level;
struct ntfs_sb_info *sbi = sb->s_fs_info;
/* Should we use different ratelimits for warnings/notices/errors? */
if (!___ratelimit(&sbi->msg_ratelimit, "ntfs3"))
return;
va_start(args, fmt);
level = printk_get_level(fmt);
vaf.fmt = printk_skip_level(fmt);
vaf.va = &args;
printk("%c%cntfs3: %s: %pV\n", KERN_SOH_ASCII, level, sb->s_id, &vaf);
va_end(args);
}
static char s_name_buf[512];
static atomic_t s_name_buf_cnt = ATOMIC_INIT(1); // 1 means 'free s_name_buf'.
/*
* ntfs_inode_printk
*
* Print warnings/notices/errors about inode using name or inode number.
*/
void ntfs_inode_printk(struct inode *inode, const char *fmt, ...)
{
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
char *name;
va_list args;
struct va_format vaf;
int level;
if (!___ratelimit(&sbi->msg_ratelimit, "ntfs3"))
return;
/* Use static allocated buffer, if possible. */
name = atomic_dec_and_test(&s_name_buf_cnt) ?
s_name_buf :
kmalloc(sizeof(s_name_buf), GFP_NOFS);
if (name) {
struct dentry *de = d_find_alias(inode);
const u32 name_len = ARRAY_SIZE(s_name_buf) - 1;
if (de) {
spin_lock(&de->d_lock);
snprintf(name, name_len, " \"%s\"", de->d_name.name);
spin_unlock(&de->d_lock);
name[name_len] = 0; /* To be sure. */
} else {
name[0] = 0;
}
dput(de); /* Cocci warns if placed in branch "if (de)" */
}
va_start(args, fmt);
level = printk_get_level(fmt);
vaf.fmt = printk_skip_level(fmt);
vaf.va = &args;
printk("%c%cntfs3: %s: ino=%lx,%s %pV\n", KERN_SOH_ASCII, level,
sb->s_id, inode->i_ino, name ? name : "", &vaf);
va_end(args);
atomic_inc(&s_name_buf_cnt);
if (name != s_name_buf)
kfree(name);
}
#endif
/*
* Shared memory struct.
*
* On-disk ntfs's upcase table is created by ntfs formatter.
* 'upcase' table is 128K bytes of memory.
* We should read it into memory when mounting.
* Several ntfs volumes likely use the same 'upcase' table.
* It is good idea to share in-memory 'upcase' table between different volumes.
* Unfortunately winxp/vista/win7 use different upcase tables.
*/
static DEFINE_SPINLOCK(s_shared_lock);
static struct {
void *ptr;
u32 len;
int cnt;
} s_shared[8];
/*
* ntfs_set_shared
*
* Return:
* * @ptr - If pointer was saved in shared memory.
* * NULL - If pointer was not shared.
*/
void *ntfs_set_shared(void *ptr, u32 bytes)
{
void *ret = NULL;
int i, j = -1;
spin_lock(&s_shared_lock);
for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
if (!s_shared[i].cnt) {
j = i;
} else if (bytes == s_shared[i].len &&
!memcmp(s_shared[i].ptr, ptr, bytes)) {
s_shared[i].cnt += 1;
ret = s_shared[i].ptr;
break;
}
}
if (!ret && j != -1) {
s_shared[j].ptr = ptr;
s_shared[j].len = bytes;
s_shared[j].cnt = 1;
ret = ptr;
}
spin_unlock(&s_shared_lock);
return ret;
}
/*
* ntfs_put_shared
*
* Return:
* * @ptr - If pointer is not shared anymore.
* * NULL - If pointer is still shared.
*/
void *ntfs_put_shared(void *ptr)
{
void *ret = ptr;
int i;
spin_lock(&s_shared_lock);
for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
if (s_shared[i].cnt && s_shared[i].ptr == ptr) {
if (--s_shared[i].cnt)
ret = NULL;
break;
}
}
spin_unlock(&s_shared_lock);
return ret;
}
static inline void put_mount_options(struct ntfs_mount_options *options)
{
kfree(options->nls_name);
unload_nls(options->nls);
kfree(options);
}
enum Opt {
Opt_uid,
Opt_gid,
Opt_umask,
Opt_dmask,
Opt_fmask,
Opt_immutable,
Opt_discard,
Opt_force,
Opt_sparse,
Opt_nohidden,
Opt_hide_dot_files,
Opt_windows_names,
Opt_showmeta,
Opt_acl,
Opt_iocharset,
Opt_prealloc,
Opt_nocase,
Opt_err,
};
// clang-format off
static const struct fs_parameter_spec ntfs_fs_parameters[] = {
fsparam_u32("uid", Opt_uid),
fsparam_u32("gid", Opt_gid),
fsparam_u32oct("umask", Opt_umask),
fsparam_u32oct("dmask", Opt_dmask),
fsparam_u32oct("fmask", Opt_fmask),
fsparam_flag_no("sys_immutable", Opt_immutable),
fsparam_flag_no("discard", Opt_discard),
fsparam_flag_no("force", Opt_force),
fsparam_flag_no("sparse", Opt_sparse),
fsparam_flag_no("hidden", Opt_nohidden),
fsparam_flag_no("hide_dot_files", Opt_hide_dot_files),
fsparam_flag_no("windows_names", Opt_windows_names),
fsparam_flag_no("showmeta", Opt_showmeta),
fsparam_flag_no("acl", Opt_acl),
fsparam_string("iocharset", Opt_iocharset),
fsparam_flag_no("prealloc", Opt_prealloc),
fsparam_flag_no("nocase", Opt_nocase),
{}
};
// clang-format on
/*
* Load nls table or if @nls is utf8 then return NULL.
*
* It is good idea to use here "const char *nls".
* But load_nls accepts "char*".
*/
static struct nls_table *ntfs_load_nls(char *nls)
{
struct nls_table *ret;
if (!nls)
nls = CONFIG_NLS_DEFAULT;
if (strcmp(nls, "utf8") == 0)
return NULL;
if (strcmp(nls, CONFIG_NLS_DEFAULT) == 0)
return load_nls_default();
ret = load_nls(nls);
if (ret)
return ret;
return ERR_PTR(-EINVAL);
}
static int ntfs_fs_parse_param(struct fs_context *fc,
struct fs_parameter *param)
{
struct ntfs_mount_options *opts = fc->fs_private;
struct fs_parse_result result;
int opt;
opt = fs_parse(fc, ntfs_fs_parameters, param, &result);
if (opt < 0)
return opt;
switch (opt) {
case Opt_uid:
opts->fs_uid = make_kuid(current_user_ns(), result.uint_32);
if (!uid_valid(opts->fs_uid))
return invalf(fc, "ntfs3: Invalid value for uid.");
break;
case Opt_gid:
opts->fs_gid = make_kgid(current_user_ns(), result.uint_32);
if (!gid_valid(opts->fs_gid))
return invalf(fc, "ntfs3: Invalid value for gid.");
break;
case Opt_umask:
if (result.uint_32 & ~07777)
return invalf(fc, "ntfs3: Invalid value for umask.");
opts->fs_fmask_inv = ~result.uint_32;
opts->fs_dmask_inv = ~result.uint_32;
opts->fmask = 1;
opts->dmask = 1;
break;
case Opt_dmask:
if (result.uint_32 & ~07777)
return invalf(fc, "ntfs3: Invalid value for dmask.");
opts->fs_dmask_inv = ~result.uint_32;
opts->dmask = 1;
break;
case Opt_fmask:
if (result.uint_32 & ~07777)
return invalf(fc, "ntfs3: Invalid value for fmask.");
opts->fs_fmask_inv = ~result.uint_32;
opts->fmask = 1;
break;
case Opt_immutable:
opts->sys_immutable = result.negated ? 0 : 1;
break;
case Opt_discard:
opts->discard = result.negated ? 0 : 1;
break;
case Opt_force:
opts->force = result.negated ? 0 : 1;
break;
case Opt_sparse:
opts->sparse = result.negated ? 0 : 1;
break;
case Opt_nohidden:
opts->nohidden = result.negated ? 1 : 0;
break;
case Opt_hide_dot_files:
opts->hide_dot_files = result.negated ? 0 : 1;
break;
case Opt_windows_names:
opts->windows_names = result.negated ? 0 : 1;
break;
case Opt_showmeta:
opts->showmeta = result.negated ? 0 : 1;
break;
case Opt_acl:
if (!result.negated)
#ifdef CONFIG_NTFS3_FS_POSIX_ACL
fc->sb_flags |= SB_POSIXACL;
#else
return invalf(
fc, "ntfs3: Support for ACL not compiled in!");
#endif
else
fc->sb_flags &= ~SB_POSIXACL;
break;
case Opt_iocharset:
kfree(opts->nls_name);
opts->nls_name = param->string;
param->string = NULL;
break;
case Opt_prealloc:
opts->prealloc = result.negated ? 0 : 1;
break;
case Opt_nocase:
opts->nocase = result.negated ? 1 : 0;
break;
default:
/* Should not be here unless we forget add case. */
return -EINVAL;
}
return 0;
}
static int ntfs_fs_reconfigure(struct fs_context *fc)
{
struct super_block *sb = fc->root->d_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_mount_options *new_opts = fc->fs_private;
int ro_rw;
ro_rw = sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY);
if (ro_rw && (sbi->flags & NTFS_FLAGS_NEED_REPLAY)) {
errorf(fc,
"ntfs3: Couldn't remount rw because journal is not replayed. Please umount/remount instead\n");
return -EINVAL;
}
new_opts->nls = ntfs_load_nls(new_opts->nls_name);
if (IS_ERR(new_opts->nls)) {
new_opts->nls = NULL;
errorf(fc, "ntfs3: Cannot load iocharset %s",
new_opts->nls_name);
return -EINVAL;
}
if (new_opts->nls != sbi->options->nls)
return invalf(
fc,
"ntfs3: Cannot use different iocharset when remounting!");
sync_filesystem(sb);
if (ro_rw && (sbi->volume.flags & VOLUME_FLAG_DIRTY) &&
!new_opts->force) {
errorf(fc,
"ntfs3: Volume is dirty and \"force\" flag is not set!");
return -EINVAL;
}
swap(sbi->options, fc->fs_private);
return 0;
}
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *proc_info_root;
/*
* ntfs3_volinfo:
*
* The content of /proc/fs/ntfs3/<dev>/volinfo
*
* ntfs3.1
* cluster size
* number of clusters
*/
static int ntfs3_volinfo(struct seq_file *m, void *o)
{
struct super_block *sb = m->private;
struct ntfs_sb_info *sbi = sb->s_fs_info;
seq_printf(m, "ntfs%d.%d\n%u\n%zu\n", sbi->volume.major_ver,
sbi->volume.minor_ver, sbi->cluster_size,
sbi->used.bitmap.nbits);
return 0;
}
static int ntfs3_volinfo_open(struct inode *inode, struct file *file)
{
return single_open(file, ntfs3_volinfo, pde_data(inode));
}
/* read /proc/fs/ntfs3/<dev>/label */
static int ntfs3_label_show(struct seq_file *m, void *o)
{
struct super_block *sb = m->private;
struct ntfs_sb_info *sbi = sb->s_fs_info;
seq_printf(m, "%s\n", sbi->volume.label);
return 0;
}
/* write /proc/fs/ntfs3/<dev>/label */
static ssize_t ntfs3_label_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
int err;
struct super_block *sb = pde_data(file_inode(file));
struct ntfs_sb_info *sbi = sb->s_fs_info;
ssize_t ret = count;
u8 *label = kmalloc(count, GFP_NOFS);
if (!label)
return -ENOMEM;
if (copy_from_user(label, buffer, ret)) {
ret = -EFAULT;
goto out;
}
while (ret > 0 && label[ret - 1] == '\n')
ret -= 1;
err = ntfs_set_label(sbi, label, ret);
if (err < 0) {
ntfs_err(sb, "failed (%d) to write label", err);
ret = err;
goto out;
}
*ppos += count;
ret = count;
out:
kfree(label);
return ret;
}
static int ntfs3_label_open(struct inode *inode, struct file *file)
{
return single_open(file, ntfs3_label_show, pde_data(inode));
}
static const struct proc_ops ntfs3_volinfo_fops = {
.proc_read = seq_read,
.proc_lseek = seq_lseek,
.proc_release = single_release,
.proc_open = ntfs3_volinfo_open,
};
static const struct proc_ops ntfs3_label_fops = {
.proc_read = seq_read,
.proc_lseek = seq_lseek,
.proc_release = single_release,
.proc_open = ntfs3_label_open,
.proc_write = ntfs3_label_write,
};
#endif
static struct kmem_cache *ntfs_inode_cachep;
static struct inode *ntfs_alloc_inode(struct super_block *sb)
{
struct ntfs_inode *ni = alloc_inode_sb(sb, ntfs_inode_cachep, GFP_NOFS);
if (!ni)
return NULL;
memset(ni, 0, offsetof(struct ntfs_inode, vfs_inode));
mutex_init(&ni->ni_lock);
return &ni->vfs_inode;
}
static void ntfs_free_inode(struct inode *inode)
{
struct ntfs_inode *ni = ntfs_i(inode);
mutex_destroy(&ni->ni_lock);
kmem_cache_free(ntfs_inode_cachep, ni);
}
static void init_once(void *foo)
{
struct ntfs_inode *ni = foo;
inode_init_once(&ni->vfs_inode);
}
/*
* Noinline to reduce binary size.
*/
static noinline void ntfs3_put_sbi(struct ntfs_sb_info *sbi)
{
wnd_close(&sbi->mft.bitmap);
wnd_close(&sbi->used.bitmap);
if (sbi->mft.ni)
iput(&sbi->mft.ni->vfs_inode);
if (sbi->security.ni)
iput(&sbi->security.ni->vfs_inode);
if (sbi->reparse.ni)
iput(&sbi->reparse.ni->vfs_inode);
if (sbi->objid.ni)
iput(&sbi->objid.ni->vfs_inode);
if (sbi->volume.ni)
iput(&sbi->volume.ni->vfs_inode);
ntfs_update_mftmirr(sbi, 0);
indx_clear(&sbi->security.index_sii);
indx_clear(&sbi->security.index_sdh);
indx_clear(&sbi->reparse.index_r);
indx_clear(&sbi->objid.index_o);
}
static void ntfs3_free_sbi(struct ntfs_sb_info *sbi)
{
kfree(sbi->new_rec);
kvfree(ntfs_put_shared(sbi->upcase));
kfree(sbi->def_table);
kfree(sbi->compress.lznt);
#ifdef CONFIG_NTFS3_LZX_XPRESS
xpress_free_decompressor(sbi->compress.xpress);
lzx_free_decompressor(sbi->compress.lzx);
#endif
kfree(sbi);
}
static void ntfs_put_super(struct super_block *sb)
{
struct ntfs_sb_info *sbi = sb->s_fs_info;
#ifdef CONFIG_PROC_FS
// Remove /proc/fs/ntfs3/..
if (sbi->procdir) {
remove_proc_entry("label", sbi->procdir);
remove_proc_entry("volinfo", sbi->procdir);
remove_proc_entry(sb->s_id, proc_info_root);
sbi->procdir = NULL;
}
#endif
/* Mark rw ntfs as clear, if possible. */
ntfs_set_state(sbi, NTFS_DIRTY_CLEAR);
ntfs3_put_sbi(sbi);
}
static int ntfs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct wnd_bitmap *wnd = &sbi->used.bitmap;
buf->f_type = sb->s_magic;
buf->f_bsize = sbi->cluster_size;
buf->f_blocks = wnd->nbits;
buf->f_bfree = buf->f_bavail = wnd_zeroes(wnd);
buf->f_fsid.val[0] = sbi->volume.ser_num;
buf->f_fsid.val[1] = (sbi->volume.ser_num >> 32);
buf->f_namelen = NTFS_NAME_LEN;
return 0;
}
static int ntfs_show_options(struct seq_file *m, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_mount_options *opts = sbi->options;
struct user_namespace *user_ns = seq_user_ns(m);
seq_printf(m, ",uid=%u", from_kuid_munged(user_ns, opts->fs_uid));
seq_printf(m, ",gid=%u", from_kgid_munged(user_ns, opts->fs_gid));
if (opts->dmask)
seq_printf(m, ",dmask=%04o", opts->fs_dmask_inv ^ 0xffff);
if (opts->fmask)
seq_printf(m, ",fmask=%04o", opts->fs_fmask_inv ^ 0xffff);
if (opts->sys_immutable)
seq_puts(m, ",sys_immutable");
if (opts->discard)
seq_puts(m, ",discard");
if (opts->force)
seq_puts(m, ",force");
if (opts->sparse)
seq_puts(m, ",sparse");
if (opts->nohidden)
seq_puts(m, ",nohidden");
if (opts->hide_dot_files)
seq_puts(m, ",hide_dot_files");
if (opts->windows_names)
seq_puts(m, ",windows_names");
if (opts->showmeta)
seq_puts(m, ",showmeta");
if (sb->s_flags & SB_POSIXACL)
seq_puts(m, ",acl");
if (opts->nls)
seq_printf(m, ",iocharset=%s", opts->nls->charset);
else
seq_puts(m, ",iocharset=utf8");
if (opts->prealloc)
seq_puts(m, ",prealloc");
if (opts->nocase)
seq_puts(m, ",nocase");
return 0;
}
/*
* ntfs_sync_fs - super_operations::sync_fs
*/
static int ntfs_sync_fs(struct super_block *sb, int wait)
{
int err = 0, err2;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *ni;
struct inode *inode;
ni = sbi->security.ni;
if (ni) {
inode = &ni->vfs_inode;
err2 = _ni_write_inode(inode, wait);
if (err2 && !err)
err = err2;
}
ni = sbi->objid.ni;
if (ni) {
inode = &ni->vfs_inode;
err2 = _ni_write_inode(inode, wait);
if (err2 && !err)
err = err2;
}
ni = sbi->reparse.ni;
if (ni) {
inode = &ni->vfs_inode;
err2 = _ni_write_inode(inode, wait);
if (err2 && !err)
err = err2;
}
if (!err)
ntfs_set_state(sbi, NTFS_DIRTY_CLEAR);
ntfs_update_mftmirr(sbi, wait);
return err;
}
static const struct super_operations ntfs_sops = {
.alloc_inode = ntfs_alloc_inode,
.free_inode = ntfs_free_inode,
.evict_inode = ntfs_evict_inode,
.put_super = ntfs_put_super,
.statfs = ntfs_statfs,
.show_options = ntfs_show_options,
.sync_fs = ntfs_sync_fs,
.write_inode = ntfs3_write_inode,
};
static struct inode *ntfs_export_get_inode(struct super_block *sb, u64 ino,
u32 generation)
{
struct MFT_REF ref;
struct inode *inode;
ref.low = cpu_to_le32(ino);
#ifdef CONFIG_NTFS3_64BIT_CLUSTER
ref.high = cpu_to_le16(ino >> 32);
#else
ref.high = 0;
#endif
ref.seq = cpu_to_le16(generation);
inode = ntfs_iget5(sb, &ref, NULL);
if (!IS_ERR(inode) && is_bad_inode(inode)) {
iput(inode);
inode = ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ntfs_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ntfs_export_get_inode);
}
static struct dentry *ntfs_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ntfs_export_get_inode);
}
/* TODO: == ntfs_sync_inode */
static int ntfs_nfs_commit_metadata(struct inode *inode)
{
return _ni_write_inode(inode, 1);
}
static const struct export_operations ntfs_export_ops = {
.fh_to_dentry = ntfs_fh_to_dentry,
.fh_to_parent = ntfs_fh_to_parent,
.get_parent = ntfs3_get_parent,
.commit_metadata = ntfs_nfs_commit_metadata,
};
/*
* format_size_gb - Return Gb,Mb to print with "%u.%02u Gb".
*/
static u32 format_size_gb(const u64 bytes, u32 *mb)
{
/* Do simple right 30 bit shift of 64 bit value. */
u64 kbytes = bytes >> 10;
u32 kbytes32 = kbytes;
*mb = (100 * (kbytes32 & 0xfffff) + 0x7ffff) >> 20;
if (*mb >= 100)
*mb = 99;
return (kbytes32 >> 20) | (((u32)(kbytes >> 32)) << 12);
}
static u32 true_sectors_per_clst(const struct NTFS_BOOT *boot)
{
if (boot->sectors_per_clusters <= 0x80)
return boot->sectors_per_clusters;
if (boot->sectors_per_clusters >= 0xf4) /* limit shift to 2MB max */
return 1U << (-(s8)boot->sectors_per_clusters);
return -EINVAL;
}
/*
* ntfs_init_from_boot - Init internal info from on-disk boot sector.
*
* NTFS mount begins from boot - special formatted 512 bytes.
* There are two boots: the first and the last 512 bytes of volume.
* The content of boot is not changed during ntfs life.
*
* NOTE: ntfs.sys checks only first (primary) boot.
* chkdsk checks both boots.
*/
static int ntfs_init_from_boot(struct super_block *sb, u32 sector_size,
u64 dev_size, struct NTFS_BOOT **boot2)
{
struct ntfs_sb_info *sbi = sb->s_fs_info;
int err;
u32 mb, gb, boot_sector_size, sct_per_clst, record_size;
u64 sectors, clusters, mlcn, mlcn2;
struct NTFS_BOOT *boot;
struct buffer_head *bh;
struct MFT_REC *rec;
u16 fn, ao;
u8 cluster_bits;
u32 boot_off = 0;
const char *hint = "Primary boot";
sbi->volume.blocks = dev_size >> PAGE_SHIFT;
bh = ntfs_bread(sb, 0);
if (!bh)
return -EIO;
check_boot:
err = -EINVAL;
boot = (struct NTFS_BOOT *)Add2Ptr(bh->b_data, boot_off);
if (memcmp(boot->system_id, "NTFS ", sizeof("NTFS ") - 1)) {
ntfs_err(sb, "%s signature is not NTFS.", hint);
goto out;
}
/* 0x55AA is not mandaroty. Thanks Maxim Suhanov*/
/*if (0x55 != boot->boot_magic[0] || 0xAA != boot->boot_magic[1])
* goto out;
*/
boot_sector_size = ((u32)boot->bytes_per_sector[1] << 8) |
boot->bytes_per_sector[0];
if (boot_sector_size < SECTOR_SIZE ||
!is_power_of_2(boot_sector_size)) {
ntfs_err(sb, "%s: invalid bytes per sector %u.", hint,
boot_sector_size);
goto out;
}
/* cluster size: 512, 1K, 2K, 4K, ... 2M */
sct_per_clst = true_sectors_per_clst(boot);
if ((int)sct_per_clst < 0 || !is_power_of_2(sct_per_clst)) {
ntfs_err(sb, "%s: invalid sectors per cluster %u.", hint,
sct_per_clst);
goto out;
}
sbi->cluster_size = boot_sector_size * sct_per_clst;
sbi->cluster_bits = cluster_bits = blksize_bits(sbi->cluster_size);
sbi->cluster_mask = sbi->cluster_size - 1;
sbi->cluster_mask_inv = ~(u64)sbi->cluster_mask;
mlcn = le64_to_cpu(boot->mft_clst);
mlcn2 = le64_to_cpu(boot->mft2_clst);
sectors = le64_to_cpu(boot->sectors_per_volume);
if (mlcn * sct_per_clst >= sectors || mlcn2 * sct_per_clst >= sectors) {
ntfs_err(
sb,
"%s: start of MFT 0x%llx (0x%llx) is out of volume 0x%llx.",
hint, mlcn, mlcn2, sectors);
goto out;
}
sbi->record_size = record_size =
boot->record_size < 0 ? 1 << (-boot->record_size) :
(u32)boot->record_size << cluster_bits;
sbi->record_bits = blksize_bits(record_size);
sbi->attr_size_tr = (5 * record_size >> 4); // ~320 bytes
/* Check MFT record size. */
if (record_size < SECTOR_SIZE || !is_power_of_2(record_size)) {
ntfs_err(sb, "%s: invalid bytes per MFT record %u (%d).", hint,
record_size, boot->record_size);
goto out;
}
if (record_size > MAXIMUM_BYTES_PER_MFT) {
ntfs_err(sb, "Unsupported bytes per MFT record %u.",
record_size);
goto out;
}
sbi->index_size = boot->index_size < 0 ?
1u << (-boot->index_size) :
(u32)boot->index_size << cluster_bits;
/* Check index record size. */
if (sbi->index_size < SECTOR_SIZE || !is_power_of_2(sbi->index_size)) {
ntfs_err(sb, "%s: invalid bytes per index %u(%d).", hint,
sbi->index_size, boot->index_size);
goto out;
}
if (sbi->index_size > MAXIMUM_BYTES_PER_INDEX) {
ntfs_err(sb, "%s: unsupported bytes per index %u.", hint,
sbi->index_size);
goto out;
}
sbi->volume.size = sectors * boot_sector_size;
gb = format_size_gb(sbi->volume.size + boot_sector_size, &mb);
/*
* - Volume formatted and mounted with the same sector size.
* - Volume formatted 4K and mounted as 512.
* - Volume formatted 512 and mounted as 4K.
*/
if (boot_sector_size != sector_size) {
ntfs_warn(
sb,
"Different NTFS sector size (%u) and media sector size (%u).",
boot_sector_size, sector_size);
dev_size += sector_size - 1;
}
sbi->mft.lbo = mlcn << cluster_bits;
sbi->mft.lbo2 = mlcn2 << cluster_bits;
/* Compare boot's cluster and sector. */
if (sbi->cluster_size < boot_sector_size) {
ntfs_err(sb, "%s: invalid bytes per cluster (%u).", hint,
sbi->cluster_size);
goto out;
}
/* Compare boot's cluster and media sector. */
if (sbi->cluster_size < sector_size) {
/* No way to use ntfs_get_block in this case. */
ntfs_err(
sb,
"Failed to mount 'cause NTFS's cluster size (%u) is less than media sector size (%u).",
sbi->cluster_size, sector_size);
goto out;
}
sbi->max_bytes_per_attr =
record_size - ALIGN(MFTRECORD_FIXUP_OFFSET, 8) -
ALIGN(((record_size >> SECTOR_SHIFT) * sizeof(short)), 8) -
ALIGN(sizeof(enum ATTR_TYPE), 8);
sbi->volume.ser_num = le64_to_cpu(boot->serial_num);
/* Warning if RAW volume. */
if (dev_size < sbi->volume.size + boot_sector_size) {
u32 mb0, gb0;
gb0 = format_size_gb(dev_size, &mb0);
ntfs_warn(
sb,
"RAW NTFS volume: Filesystem size %u.%02u Gb > volume size %u.%02u Gb. Mount in read-only.",
gb, mb, gb0, mb0);
sb->s_flags |= SB_RDONLY;
}
clusters = sbi->volume.size >> cluster_bits;
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
/* 32 bits per cluster. */
if (clusters >> 32) {
ntfs_notice(
sb,
"NTFS %u.%02u Gb is too big to use 32 bits per cluster.",
gb, mb);
goto out;
}
#elif BITS_PER_LONG < 64
#error "CONFIG_NTFS3_64BIT_CLUSTER incompatible in 32 bit OS"
#endif
sbi->used.bitmap.nbits = clusters;
rec = kzalloc(record_size, GFP_NOFS);
if (!rec) {
err = -ENOMEM;
goto out;
}
sbi->new_rec = rec;
rec->rhdr.sign = NTFS_FILE_SIGNATURE;
rec->rhdr.fix_off = cpu_to_le16(MFTRECORD_FIXUP_OFFSET);
fn = (sbi->record_size >> SECTOR_SHIFT) + 1;
rec->rhdr.fix_num = cpu_to_le16(fn);
ao = ALIGN(MFTRECORD_FIXUP_OFFSET + sizeof(short) * fn, 8);
rec->attr_off = cpu_to_le16(ao);
rec->used = cpu_to_le32(ao + ALIGN(sizeof(enum ATTR_TYPE), 8));
rec->total = cpu_to_le32(sbi->record_size);
((struct ATTRIB *)Add2Ptr(rec, ao))->type = ATTR_END;
sb_set_blocksize(sb, min_t(u32, sbi->cluster_size, PAGE_SIZE));
sbi->block_mask = sb->s_blocksize - 1;
sbi->blocks_per_cluster = sbi->cluster_size >> sb->s_blocksize_bits;
sbi->volume.blocks = sbi->volume.size >> sb->s_blocksize_bits;
/* Maximum size for normal files. */
sbi->maxbytes = (clusters << cluster_bits) - 1;
#ifdef CONFIG_NTFS3_64BIT_CLUSTER
if (clusters >= (1ull << (64 - cluster_bits)))
sbi->maxbytes = -1;
sbi->maxbytes_sparse = -1;
sb->s_maxbytes = MAX_LFS_FILESIZE;
#else
/* Maximum size for sparse file. */
sbi->maxbytes_sparse = (1ull << (cluster_bits + 32)) - 1;
sb->s_maxbytes = 0xFFFFFFFFull << cluster_bits;
#endif
/*
* Compute the MFT zone at two steps.
* It would be nice if we are able to allocate 1/8 of
* total clusters for MFT but not more then 512 MB.
*/
sbi->zone_max = min_t(CLST, 0x20000000 >> cluster_bits, clusters >> 3);
err = 0;
if (bh->b_blocknr && !sb_rdonly(sb)) {
/*
* Alternative boot is ok but primary is not ok.
* Do not update primary boot here 'cause it may be faked boot.
* Let ntfs to be mounted and update boot later.
*/
*boot2 = kmemdup(boot, sizeof(*boot), GFP_NOFS | __GFP_NOWARN);
}
out:
if (err == -EINVAL && !bh->b_blocknr && dev_size > PAGE_SHIFT) {
u32 block_size = min_t(u32, sector_size, PAGE_SIZE);
u64 lbo = dev_size - sizeof(*boot);
/*
* Try alternative boot (last sector)
*/
brelse(bh);
sb_set_blocksize(sb, block_size);
bh = ntfs_bread(sb, lbo >> blksize_bits(block_size));
if (!bh)
return -EINVAL;
boot_off = lbo & (block_size - 1);
hint = "Alternative boot";
goto check_boot;
}
brelse(bh);
return err;
}
/*
* ntfs_fill_super - Try to mount.
*/
static int ntfs_fill_super(struct super_block *sb, struct fs_context *fc)
{
int err;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct block_device *bdev = sb->s_bdev;
struct ntfs_mount_options *options;
struct inode *inode;
struct ntfs_inode *ni;
size_t i, tt, bad_len, bad_frags;
CLST vcn, lcn, len;
struct ATTRIB *attr;
const struct VOLUME_INFO *info;
u32 idx, done, bytes;
struct ATTR_DEF_ENTRY *t;
u16 *shared;
struct MFT_REF ref;
bool ro = sb_rdonly(sb);
struct NTFS_BOOT *boot2 = NULL;
ref.high = 0;
sbi->sb = sb;
sbi->options = options = fc->fs_private;
fc->fs_private = NULL;
sb->s_flags |= SB_NODIRATIME;
sb->s_magic = 0x7366746e; // "ntfs"
sb->s_op = &ntfs_sops;
sb->s_export_op = &ntfs_export_ops;
sb->s_time_gran = NTFS_TIME_GRAN; // 100 nsec
sb->s_xattr = ntfs_xattr_handlers;
sb->s_d_op = options->nocase ? &ntfs_dentry_ops : NULL;
options->nls = ntfs_load_nls(options->nls_name);
if (IS_ERR(options->nls)) {
options->nls = NULL;
errorf(fc, "Cannot load nls %s", options->nls_name);
err = -EINVAL;
goto out;
}
if (bdev_max_discard_sectors(bdev) && bdev_discard_granularity(bdev)) {
sbi->discard_granularity = bdev_discard_granularity(bdev);
sbi->discard_granularity_mask_inv =
~(u64)(sbi->discard_granularity - 1);
}
/* Parse boot. */
err = ntfs_init_from_boot(sb, bdev_logical_block_size(bdev),
bdev_nr_bytes(bdev), &boot2);
if (err)
goto out;
/*
* Load $Volume. This should be done before $LogFile
* 'cause 'sbi->volume.ni' is used 'ntfs_set_state'.
*/
ref.low = cpu_to_le32(MFT_REC_VOL);
ref.seq = cpu_to_le16(MFT_REC_VOL);
inode = ntfs_iget5(sb, &ref, &NAME_VOLUME);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $Volume (%d).", err);
goto out;
}
ni = ntfs_i(inode);
/* Load and save label (not necessary). */
attr = ni_find_attr(ni, NULL, NULL, ATTR_LABEL, NULL, 0, NULL, NULL);
if (!attr) {
/* It is ok if no ATTR_LABEL */
} else if (!attr->non_res && !is_attr_ext(attr)) {
/* $AttrDef allows labels to be up to 128 symbols. */
err = utf16s_to_utf8s(resident_data(attr),
le32_to_cpu(attr->res.data_size) >> 1,
UTF16_LITTLE_ENDIAN, sbi->volume.label,
sizeof(sbi->volume.label));
if (err < 0)
sbi->volume.label[0] = 0;
} else {
/* Should we break mounting here? */
//err = -EINVAL;
//goto put_inode_out;
}
attr = ni_find_attr(ni, attr, NULL, ATTR_VOL_INFO, NULL, 0, NULL, NULL);
if (!attr || is_attr_ext(attr) ||
!(info = resident_data_ex(attr, SIZEOF_ATTRIBUTE_VOLUME_INFO))) {
ntfs_err(sb, "$Volume is corrupted.");
err = -EINVAL;
goto put_inode_out;
}
sbi->volume.major_ver = info->major_ver;
sbi->volume.minor_ver = info->minor_ver;
sbi->volume.flags = info->flags;
sbi->volume.ni = ni;
if (info->flags & VOLUME_FLAG_DIRTY) {
sbi->volume.real_dirty = true;
ntfs_info(sb, "It is recommened to use chkdsk.");
}
/* Load $MFTMirr to estimate recs_mirr. */
ref.low = cpu_to_le32(MFT_REC_MIRR);
ref.seq = cpu_to_le16(MFT_REC_MIRR);
inode = ntfs_iget5(sb, &ref, &NAME_MIRROR);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $MFTMirr (%d).", err);
goto out;
}
sbi->mft.recs_mirr = ntfs_up_cluster(sbi, inode->i_size) >>
sbi->record_bits;
iput(inode);
/* Load LogFile to replay. */
ref.low = cpu_to_le32(MFT_REC_LOG);
ref.seq = cpu_to_le16(MFT_REC_LOG);
inode = ntfs_iget5(sb, &ref, &NAME_LOGFILE);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load \x24LogFile (%d).", err);
goto out;
}
ni = ntfs_i(inode);
err = ntfs_loadlog_and_replay(ni, sbi);
if (err)
goto put_inode_out;
iput(inode);
if ((sbi->flags & NTFS_FLAGS_NEED_REPLAY) && !ro) {
ntfs_warn(sb, "failed to replay log file. Can't mount rw!");
err = -EINVAL;
goto out;
}
if ((sbi->volume.flags & VOLUME_FLAG_DIRTY) && !ro && !options->force) {
ntfs_warn(sb, "volume is dirty and \"force\" flag is not set!");
err = -EINVAL;
goto out;
}
/* Load $MFT. */
ref.low = cpu_to_le32(MFT_REC_MFT);
ref.seq = cpu_to_le16(1);
inode = ntfs_iget5(sb, &ref, &NAME_MFT);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $MFT (%d).", err);
goto out;
}
ni = ntfs_i(inode);
sbi->mft.used = ni->i_valid >> sbi->record_bits;
tt = inode->i_size >> sbi->record_bits;
sbi->mft.next_free = MFT_REC_USER;
err = wnd_init(&sbi->mft.bitmap, sb, tt);
if (err)
goto put_inode_out;
err = ni_load_all_mi(ni);
if (err) {
ntfs_err(sb, "Failed to load $MFT's subrecords (%d).", err);
goto put_inode_out;
}
sbi->mft.ni = ni;
/* Load $Bitmap. */
ref.low = cpu_to_le32(MFT_REC_BITMAP);
ref.seq = cpu_to_le16(MFT_REC_BITMAP);
inode = ntfs_iget5(sb, &ref, &NAME_BITMAP);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $Bitmap (%d).", err);
goto out;
}
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
if (inode->i_size >> 32) {
err = -EINVAL;
goto put_inode_out;
}
#endif
/* Check bitmap boundary. */
tt = sbi->used.bitmap.nbits;
if (inode->i_size < bitmap_size(tt)) {
ntfs_err(sb, "$Bitmap is corrupted.");
err = -EINVAL;
goto put_inode_out;
}
err = wnd_init(&sbi->used.bitmap, sb, tt);
if (err) {
ntfs_err(sb, "Failed to initialize $Bitmap (%d).", err);
goto put_inode_out;
}
iput(inode);
/* Compute the MFT zone. */
err = ntfs_refresh_zone(sbi);
if (err) {
ntfs_err(sb, "Failed to initialize MFT zone (%d).", err);
goto out;
}
/* Load $BadClus. */
ref.low = cpu_to_le32(MFT_REC_BADCLUST);
ref.seq = cpu_to_le16(MFT_REC_BADCLUST);
inode = ntfs_iget5(sb, &ref, &NAME_BADCLUS);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $BadClus (%d).", err);
goto out;
}
ni = ntfs_i(inode);
bad_len = bad_frags = 0;
for (i = 0; run_get_entry(&ni->file.run, i, &vcn, &lcn, &len); i++) {
if (lcn == SPARSE_LCN)
continue;
bad_len += len;
bad_frags += 1;
if (ro)
continue;
if (wnd_set_used_safe(&sbi->used.bitmap, lcn, len, &tt) || tt) {
/* Bad blocks marked as free in bitmap. */
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
}
}
if (bad_len) {
/*
* Notice about bad blocks.
* In normal cases these blocks are marked as used in bitmap.
* And we never allocate space in it.
*/
ntfs_notice(sb,
"Volume contains %zu bad blocks in %zu fragments.",
bad_len, bad_frags);
}
iput(inode);
/* Load $AttrDef. */
ref.low = cpu_to_le32(MFT_REC_ATTR);
ref.seq = cpu_to_le16(MFT_REC_ATTR);
inode = ntfs_iget5(sb, &ref, &NAME_ATTRDEF);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $AttrDef (%d)", err);
goto out;
}
/*
* Typical $AttrDef contains up to 20 entries.
* Check for extremely large/small size.
*/
if (inode->i_size < sizeof(struct ATTR_DEF_ENTRY) ||
inode->i_size > 100 * sizeof(struct ATTR_DEF_ENTRY)) {
ntfs_err(sb, "Looks like $AttrDef is corrupted (size=%llu).",
inode->i_size);
err = -EINVAL;
goto put_inode_out;
}
bytes = inode->i_size;
sbi->def_table = t = kmalloc(bytes, GFP_NOFS | __GFP_NOWARN);
if (!t) {
err = -ENOMEM;
goto put_inode_out;
}
for (done = idx = 0; done < bytes; done += PAGE_SIZE, idx++) {
unsigned long tail = bytes - done;
struct page *page = ntfs_map_page(inode->i_mapping, idx);
if (IS_ERR(page)) {
err = PTR_ERR(page);
ntfs_err(sb, "Failed to read $AttrDef (%d).", err);
goto put_inode_out;
}
memcpy(Add2Ptr(t, done), page_address(page),
min(PAGE_SIZE, tail));
ntfs_unmap_page(page);
if (!idx && ATTR_STD != t->type) {
ntfs_err(sb, "$AttrDef is corrupted.");
err = -EINVAL;
goto put_inode_out;
}
}
t += 1;
sbi->def_entries = 1;
done = sizeof(struct ATTR_DEF_ENTRY);
sbi->reparse.max_size = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
sbi->ea_max_size = 0x10000; /* default formatter value */
while (done + sizeof(struct ATTR_DEF_ENTRY) <= bytes) {
u32 t32 = le32_to_cpu(t->type);
u64 sz = le64_to_cpu(t->max_sz);
if ((t32 & 0xF) || le32_to_cpu(t[-1].type) >= t32)
break;
if (t->type == ATTR_REPARSE)
sbi->reparse.max_size = sz;
else if (t->type == ATTR_EA)
sbi->ea_max_size = sz;
done += sizeof(struct ATTR_DEF_ENTRY);
t += 1;
sbi->def_entries += 1;
}
iput(inode);
/* Load $UpCase. */
ref.low = cpu_to_le32(MFT_REC_UPCASE);
ref.seq = cpu_to_le16(MFT_REC_UPCASE);
inode = ntfs_iget5(sb, &ref, &NAME_UPCASE);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $UpCase (%d).", err);
goto out;
}
if (inode->i_size != 0x10000 * sizeof(short)) {
err = -EINVAL;
ntfs_err(sb, "$UpCase is corrupted.");
goto put_inode_out;
}
for (idx = 0; idx < (0x10000 * sizeof(short) >> PAGE_SHIFT); idx++) {
const __le16 *src;
u16 *dst = Add2Ptr(sbi->upcase, idx << PAGE_SHIFT);
struct page *page = ntfs_map_page(inode->i_mapping, idx);
if (IS_ERR(page)) {
err = PTR_ERR(page);
ntfs_err(sb, "Failed to read $UpCase (%d).", err);
goto put_inode_out;
}
src = page_address(page);
#ifdef __BIG_ENDIAN
for (i = 0; i < PAGE_SIZE / sizeof(u16); i++)
*dst++ = le16_to_cpu(*src++);
#else
memcpy(dst, src, PAGE_SIZE);
#endif
ntfs_unmap_page(page);
}
shared = ntfs_set_shared(sbi->upcase, 0x10000 * sizeof(short));
if (shared && sbi->upcase != shared) {
kvfree(sbi->upcase);
sbi->upcase = shared;
}
iput(inode);
if (is_ntfs3(sbi)) {
/* Load $Secure. */
err = ntfs_security_init(sbi);
if (err) {
ntfs_err(sb, "Failed to initialize $Secure (%d).", err);
goto out;
}
/* Load $Extend. */
err = ntfs_extend_init(sbi);
if (err) {
ntfs_warn(sb, "Failed to initialize $Extend.");
goto load_root;
}
/* Load $Extend/$Reparse. */
err = ntfs_reparse_init(sbi);
if (err) {
ntfs_warn(sb, "Failed to initialize $Extend/$Reparse.");
goto load_root;
}
/* Load $Extend/$ObjId. */
err = ntfs_objid_init(sbi);
if (err) {
ntfs_warn(sb, "Failed to initialize $Extend/$ObjId.");
goto load_root;
}
}
load_root:
/* Load root. */
ref.low = cpu_to_le32(MFT_REC_ROOT);
ref.seq = cpu_to_le16(MFT_REC_ROOT);
inode = ntfs_iget5(sb, &ref, &NAME_ROOT);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load root (%d).", err);
goto out;
}
/*
* Final check. Looks like this case should never occurs.
*/
if (!inode->i_op) {
err = -EINVAL;
ntfs_err(sb, "Failed to load root (%d).", err);
goto put_inode_out;
}
sb->s_root = d_make_root(inode);
if (!sb->s_root) {
err = -ENOMEM;
goto put_inode_out;
}
if (boot2) {
/*
* Alternative boot is ok but primary is not ok.
* Volume is recognized as NTFS. Update primary boot.
*/
struct buffer_head *bh0 = sb_getblk(sb, 0);
if (bh0) {
if (buffer_locked(bh0))
__wait_on_buffer(bh0);
lock_buffer(bh0);
memcpy(bh0->b_data, boot2, sizeof(*boot2));
set_buffer_uptodate(bh0);
mark_buffer_dirty(bh0);
unlock_buffer(bh0);
if (!sync_dirty_buffer(bh0))
ntfs_warn(sb, "primary boot is updated");
put_bh(bh0);
}
kfree(boot2);
}
#ifdef CONFIG_PROC_FS
/* Create /proc/fs/ntfs3/.. */
if (proc_info_root) {
struct proc_dir_entry *e = proc_mkdir(sb->s_id, proc_info_root);
static_assert((S_IRUGO | S_IWUSR) == 0644);
if (e) {
proc_create_data("volinfo", S_IRUGO, e,
&ntfs3_volinfo_fops, sb);
proc_create_data("label", S_IRUGO | S_IWUSR, e,
&ntfs3_label_fops, sb);
sbi->procdir = e;
}
}
#endif
return 0;
put_inode_out:
iput(inode);
out:
kfree(boot2);
return err;
}
void ntfs_unmap_meta(struct super_block *sb, CLST lcn, CLST len)
{
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct block_device *bdev = sb->s_bdev;
sector_t devblock = (u64)lcn * sbi->blocks_per_cluster;
unsigned long blocks = (u64)len * sbi->blocks_per_cluster;
unsigned long cnt = 0;
unsigned long limit = global_zone_page_state(NR_FREE_PAGES)
<< (PAGE_SHIFT - sb->s_blocksize_bits);
if (limit >= 0x2000)
limit -= 0x1000;
else if (limit < 32)
limit = 32;
else
limit >>= 1;
while (blocks--) {
clean_bdev_aliases(bdev, devblock++, 1);
if (cnt++ >= limit) {
sync_blockdev(bdev);
cnt = 0;
}
}
}
/*
* ntfs_discard - Issue a discard request (trim for SSD).
*/
int ntfs_discard(struct ntfs_sb_info *sbi, CLST lcn, CLST len)
{
int err;
u64 lbo, bytes, start, end;
struct super_block *sb;
if (sbi->used.next_free_lcn == lcn + len)
sbi->used.next_free_lcn = lcn;
if (sbi->flags & NTFS_FLAGS_NODISCARD)
return -EOPNOTSUPP;
if (!sbi->options->discard)
return -EOPNOTSUPP;
lbo = (u64)lcn << sbi->cluster_bits;
bytes = (u64)len << sbi->cluster_bits;
/* Align up 'start' on discard_granularity. */
start = (lbo + sbi->discard_granularity - 1) &
sbi->discard_granularity_mask_inv;
/* Align down 'end' on discard_granularity. */
end = (lbo + bytes) & sbi->discard_granularity_mask_inv;
sb = sbi->sb;
if (start >= end)
return 0;
err = blkdev_issue_discard(sb->s_bdev, start >> 9, (end - start) >> 9,
GFP_NOFS);
if (err == -EOPNOTSUPP)
sbi->flags |= NTFS_FLAGS_NODISCARD;
return err;
}
static int ntfs_fs_get_tree(struct fs_context *fc)
{
return get_tree_bdev(fc, ntfs_fill_super);
}
/*
* ntfs_fs_free - Free fs_context.
*
* Note that this will be called after fill_super and reconfigure
* even when they pass. So they have to take pointers if they pass.
*/
static void ntfs_fs_free(struct fs_context *fc)
{
struct ntfs_mount_options *opts = fc->fs_private;
struct ntfs_sb_info *sbi = fc->s_fs_info;
if (sbi) {
ntfs3_put_sbi(sbi);
ntfs3_free_sbi(sbi);
}
if (opts)
put_mount_options(opts);
}
// clang-format off
static const struct fs_context_operations ntfs_context_ops = {
.parse_param = ntfs_fs_parse_param,
.get_tree = ntfs_fs_get_tree,
.reconfigure = ntfs_fs_reconfigure,
.free = ntfs_fs_free,
};
// clang-format on
/*
* ntfs_init_fs_context - Initialize sbi and opts
*
* This will called when mount/remount. We will first initialize
* options so that if remount we can use just that.
*/
static int ntfs_init_fs_context(struct fs_context *fc)
{
struct ntfs_mount_options *opts;
struct ntfs_sb_info *sbi;
opts = kzalloc(sizeof(struct ntfs_mount_options), GFP_NOFS);
if (!opts)
return -ENOMEM;
/* Default options. */
opts->fs_uid = current_uid();
opts->fs_gid = current_gid();
opts->fs_fmask_inv = ~current_umask();
opts->fs_dmask_inv = ~current_umask();
if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE)
goto ok;
sbi = kzalloc(sizeof(struct ntfs_sb_info), GFP_NOFS);
if (!sbi)
goto free_opts;
sbi->upcase = kvmalloc(0x10000 * sizeof(short), GFP_KERNEL);
if (!sbi->upcase)
goto free_sbi;
ratelimit_state_init(&sbi->msg_ratelimit, DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST);
mutex_init(&sbi->compress.mtx_lznt);
#ifdef CONFIG_NTFS3_LZX_XPRESS
mutex_init(&sbi->compress.mtx_xpress);
mutex_init(&sbi->compress.mtx_lzx);
#endif
fc->s_fs_info = sbi;
ok:
fc->fs_private = opts;
fc->ops = &ntfs_context_ops;
return 0;
free_sbi:
kfree(sbi);
free_opts:
kfree(opts);
return -ENOMEM;
}
static void ntfs3_kill_sb(struct super_block *sb)
{
struct ntfs_sb_info *sbi = sb->s_fs_info;
kill_block_super(sb);
if (sbi->options)
put_mount_options(sbi->options);
ntfs3_free_sbi(sbi);
}
// clang-format off
static struct file_system_type ntfs_fs_type = {
.owner = THIS_MODULE,
.name = "ntfs3",
.init_fs_context = ntfs_init_fs_context,
.parameters = ntfs_fs_parameters,
.kill_sb = ntfs3_kill_sb,
.fs_flags = FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
};
// clang-format on
static int __init init_ntfs_fs(void)
{
int err;
pr_info("ntfs3: Max link count %u\n", NTFS_LINK_MAX);
if (IS_ENABLED(CONFIG_NTFS3_FS_POSIX_ACL))
pr_info("ntfs3: Enabled Linux POSIX ACLs support\n");
if (IS_ENABLED(CONFIG_NTFS3_64BIT_CLUSTER))
pr_notice(
"ntfs3: Warning: Activated 64 bits per cluster. Windows does not support this\n");
if (IS_ENABLED(CONFIG_NTFS3_LZX_XPRESS))
pr_info("ntfs3: Read-only LZX/Xpress compression included\n");
#ifdef CONFIG_PROC_FS
/* Create "/proc/fs/ntfs3" */
proc_info_root = proc_mkdir("fs/ntfs3", NULL);
#endif
err = ntfs3_init_bitmap();
if (err)
return err;
ntfs_inode_cachep = kmem_cache_create(
"ntfs_inode_cache", sizeof(struct ntfs_inode), 0,
(SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT),
init_once);
if (!ntfs_inode_cachep) {
err = -ENOMEM;
goto out1;
}
err = register_filesystem(&ntfs_fs_type);
if (err)
goto out;
return 0;
out:
kmem_cache_destroy(ntfs_inode_cachep);
out1:
ntfs3_exit_bitmap();
return err;
}
static void __exit exit_ntfs_fs(void)
{
rcu_barrier();
kmem_cache_destroy(ntfs_inode_cachep);
unregister_filesystem(&ntfs_fs_type);
ntfs3_exit_bitmap();
#ifdef CONFIG_PROC_FS
if (proc_info_root)
remove_proc_entry("fs/ntfs3", NULL);
#endif
}
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ntfs3 read/write filesystem");
#ifdef CONFIG_NTFS3_FS_POSIX_ACL
MODULE_INFO(behaviour, "Enabled Linux POSIX ACLs support");
#endif
#ifdef CONFIG_NTFS3_64BIT_CLUSTER
MODULE_INFO(
cluster,
"Warning: Activated 64 bits per cluster. Windows does not support this");
#endif
#ifdef CONFIG_NTFS3_LZX_XPRESS
MODULE_INFO(compression, "Read-only lzx/xpress compression included");
#endif
MODULE_AUTHOR("Konstantin Komarov");
MODULE_ALIAS_FS("ntfs3");
module_init(init_ntfs_fs);
module_exit(exit_ntfs_fs);
| linux-master | fs/ntfs3/super.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <linux/types.h>
#include "debug.h"
#include "ntfs_fs.h"
// clang-format off
/* Src buffer is zero. */
#define LZNT_ERROR_ALL_ZEROS 1
#define LZNT_CHUNK_SIZE 0x1000
// clang-format on
struct lznt_hash {
const u8 *p1;
const u8 *p2;
};
struct lznt {
const u8 *unc;
const u8 *unc_end;
const u8 *best_match;
size_t max_len;
bool std;
struct lznt_hash hash[LZNT_CHUNK_SIZE];
};
static inline size_t get_match_len(const u8 *ptr, const u8 *end, const u8 *prev,
size_t max_len)
{
size_t len = 0;
while (ptr + len < end && ptr[len] == prev[len] && ++len < max_len)
;
return len;
}
static size_t longest_match_std(const u8 *src, struct lznt *ctx)
{
size_t hash_index;
size_t len1 = 0, len2 = 0;
const u8 **hash;
hash_index =
((40543U * ((((src[0] << 4) ^ src[1]) << 4) ^ src[2])) >> 4) &
(LZNT_CHUNK_SIZE - 1);
hash = &(ctx->hash[hash_index].p1);
if (hash[0] >= ctx->unc && hash[0] < src && hash[0][0] == src[0] &&
hash[0][1] == src[1] && hash[0][2] == src[2]) {
len1 = 3;
if (ctx->max_len > 3)
len1 += get_match_len(src + 3, ctx->unc_end,
hash[0] + 3, ctx->max_len - 3);
}
if (hash[1] >= ctx->unc && hash[1] < src && hash[1][0] == src[0] &&
hash[1][1] == src[1] && hash[1][2] == src[2]) {
len2 = 3;
if (ctx->max_len > 3)
len2 += get_match_len(src + 3, ctx->unc_end,
hash[1] + 3, ctx->max_len - 3);
}
/* Compare two matches and select the best one. */
if (len1 < len2) {
ctx->best_match = hash[1];
len1 = len2;
} else {
ctx->best_match = hash[0];
}
hash[1] = hash[0];
hash[0] = src;
return len1;
}
static size_t longest_match_best(const u8 *src, struct lznt *ctx)
{
size_t max_len;
const u8 *ptr;
if (ctx->unc >= src || !ctx->max_len)
return 0;
max_len = 0;
for (ptr = ctx->unc; ptr < src; ++ptr) {
size_t len =
get_match_len(src, ctx->unc_end, ptr, ctx->max_len);
if (len >= max_len) {
max_len = len;
ctx->best_match = ptr;
}
}
return max_len >= 3 ? max_len : 0;
}
static const size_t s_max_len[] = {
0x1002, 0x802, 0x402, 0x202, 0x102, 0x82, 0x42, 0x22, 0x12,
};
static const size_t s_max_off[] = {
0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
};
static inline u16 make_pair(size_t offset, size_t len, size_t index)
{
return ((offset - 1) << (12 - index)) |
((len - 3) & (((1 << (12 - index)) - 1)));
}
static inline size_t parse_pair(u16 pair, size_t *offset, size_t index)
{
*offset = 1 + (pair >> (12 - index));
return 3 + (pair & ((1 << (12 - index)) - 1));
}
/*
* compress_chunk
*
* Return:
* * 0 - Ok, @cmpr contains @cmpr_chunk_size bytes of compressed data.
* * 1 - Input buffer is full zero.
* * -2 - The compressed buffer is too small to hold the compressed data.
*/
static inline int compress_chunk(size_t (*match)(const u8 *, struct lznt *),
const u8 *unc, const u8 *unc_end, u8 *cmpr,
u8 *cmpr_end, size_t *cmpr_chunk_size,
struct lznt *ctx)
{
size_t cnt = 0;
size_t idx = 0;
const u8 *up = unc;
u8 *cp = cmpr + 3;
u8 *cp2 = cmpr + 2;
u8 not_zero = 0;
/* Control byte of 8-bit values: ( 0 - means byte as is, 1 - short pair ). */
u8 ohdr = 0;
u8 *last;
u16 t16;
if (unc + LZNT_CHUNK_SIZE < unc_end)
unc_end = unc + LZNT_CHUNK_SIZE;
last = min(cmpr + LZNT_CHUNK_SIZE + sizeof(short), cmpr_end);
ctx->unc = unc;
ctx->unc_end = unc_end;
ctx->max_len = s_max_len[0];
while (up < unc_end) {
size_t max_len;
while (unc + s_max_off[idx] < up)
ctx->max_len = s_max_len[++idx];
/* Find match. */
max_len = up + 3 <= unc_end ? (*match)(up, ctx) : 0;
if (!max_len) {
if (cp >= last)
goto NotCompressed;
not_zero |= *cp++ = *up++;
} else if (cp + 1 >= last) {
goto NotCompressed;
} else {
t16 = make_pair(up - ctx->best_match, max_len, idx);
*cp++ = t16;
*cp++ = t16 >> 8;
ohdr |= 1 << cnt;
up += max_len;
}
cnt = (cnt + 1) & 7;
if (!cnt) {
*cp2 = ohdr;
ohdr = 0;
cp2 = cp;
cp += 1;
}
}
if (cp2 < last)
*cp2 = ohdr;
else
cp -= 1;
*cmpr_chunk_size = cp - cmpr;
t16 = (*cmpr_chunk_size - 3) | 0xB000;
cmpr[0] = t16;
cmpr[1] = t16 >> 8;
return not_zero ? 0 : LZNT_ERROR_ALL_ZEROS;
NotCompressed:
if ((cmpr + LZNT_CHUNK_SIZE + sizeof(short)) > last)
return -2;
/*
* Copy non cmpr data.
* 0x3FFF == ((LZNT_CHUNK_SIZE + 2 - 3) | 0x3000)
*/
cmpr[0] = 0xff;
cmpr[1] = 0x3f;
memcpy(cmpr + sizeof(short), unc, LZNT_CHUNK_SIZE);
*cmpr_chunk_size = LZNT_CHUNK_SIZE + sizeof(short);
return 0;
}
static inline ssize_t decompress_chunk(u8 *unc, u8 *unc_end, const u8 *cmpr,
const u8 *cmpr_end)
{
u8 *up = unc;
u8 ch = *cmpr++;
size_t bit = 0;
size_t index = 0;
u16 pair;
size_t offset, length;
/* Do decompression until pointers are inside range. */
while (up < unc_end && cmpr < cmpr_end) {
/* Correct index */
while (unc + s_max_off[index] < up)
index += 1;
/* Check the current flag for zero. */
if (!(ch & (1 << bit))) {
/* Just copy byte. */
*up++ = *cmpr++;
goto next;
}
/* Check for boundary. */
if (cmpr + 1 >= cmpr_end)
return -EINVAL;
/* Read a short from little endian stream. */
pair = cmpr[1];
pair <<= 8;
pair |= cmpr[0];
cmpr += 2;
/* Translate packed information into offset and length. */
length = parse_pair(pair, &offset, index);
/* Check offset for boundary. */
if (unc + offset > up)
return -EINVAL;
/* Truncate the length if necessary. */
if (up + length >= unc_end)
length = unc_end - up;
/* Now we copy bytes. This is the heart of LZ algorithm. */
for (; length > 0; length--, up++)
*up = *(up - offset);
next:
/* Advance flag bit value. */
bit = (bit + 1) & 7;
if (!bit) {
if (cmpr >= cmpr_end)
break;
ch = *cmpr++;
}
}
/* Return the size of uncompressed data. */
return up - unc;
}
/*
* get_lznt_ctx
* @level: 0 - Standard compression.
* !0 - Best compression, requires a lot of cpu.
*/
struct lznt *get_lznt_ctx(int level)
{
struct lznt *r = kzalloc(level ? offsetof(struct lznt, hash) :
sizeof(struct lznt),
GFP_NOFS);
if (r)
r->std = !level;
return r;
}
/*
* compress_lznt - Compresses @unc into @cmpr
*
* Return:
* * +x - Ok, @cmpr contains 'final_compressed_size' bytes of compressed data.
* * 0 - Input buffer is full zero.
*/
size_t compress_lznt(const void *unc, size_t unc_size, void *cmpr,
size_t cmpr_size, struct lznt *ctx)
{
int err;
size_t (*match)(const u8 *src, struct lznt *ctx);
u8 *p = cmpr;
u8 *end = p + cmpr_size;
const u8 *unc_chunk = unc;
const u8 *unc_end = unc_chunk + unc_size;
bool is_zero = true;
if (ctx->std) {
match = &longest_match_std;
memset(ctx->hash, 0, sizeof(ctx->hash));
} else {
match = &longest_match_best;
}
/* Compression cycle. */
for (; unc_chunk < unc_end; unc_chunk += LZNT_CHUNK_SIZE) {
cmpr_size = 0;
err = compress_chunk(match, unc_chunk, unc_end, p, end,
&cmpr_size, ctx);
if (err < 0)
return unc_size;
if (is_zero && err != LZNT_ERROR_ALL_ZEROS)
is_zero = false;
p += cmpr_size;
}
if (p <= end - 2)
p[0] = p[1] = 0;
return is_zero ? 0 : PtrOffset(cmpr, p);
}
/*
* decompress_lznt - Decompress @cmpr into @unc.
*/
ssize_t decompress_lznt(const void *cmpr, size_t cmpr_size, void *unc,
size_t unc_size)
{
const u8 *cmpr_chunk = cmpr;
const u8 *cmpr_end = cmpr_chunk + cmpr_size;
u8 *unc_chunk = unc;
u8 *unc_end = unc_chunk + unc_size;
u16 chunk_hdr;
if (cmpr_size < sizeof(short))
return -EINVAL;
/* Read chunk header. */
chunk_hdr = cmpr_chunk[1];
chunk_hdr <<= 8;
chunk_hdr |= cmpr_chunk[0];
/* Loop through decompressing chunks. */
for (;;) {
size_t chunk_size_saved;
size_t unc_use;
size_t cmpr_use = 3 + (chunk_hdr & (LZNT_CHUNK_SIZE - 1));
/* Check that the chunk actually fits the supplied buffer. */
if (cmpr_chunk + cmpr_use > cmpr_end)
return -EINVAL;
/* First make sure the chunk contains compressed data. */
if (chunk_hdr & 0x8000) {
/* Decompress a chunk and return if we get an error. */
ssize_t err =
decompress_chunk(unc_chunk, unc_end,
cmpr_chunk + sizeof(chunk_hdr),
cmpr_chunk + cmpr_use);
if (err < 0)
return err;
unc_use = err;
} else {
/* This chunk does not contain compressed data. */
unc_use = unc_chunk + LZNT_CHUNK_SIZE > unc_end ?
unc_end - unc_chunk :
LZNT_CHUNK_SIZE;
if (cmpr_chunk + sizeof(chunk_hdr) + unc_use >
cmpr_end) {
return -EINVAL;
}
memcpy(unc_chunk, cmpr_chunk + sizeof(chunk_hdr),
unc_use);
}
/* Advance pointers. */
cmpr_chunk += cmpr_use;
unc_chunk += unc_use;
/* Check for the end of unc buffer. */
if (unc_chunk >= unc_end)
break;
/* Proceed the next chunk. */
if (cmpr_chunk > cmpr_end - 2)
break;
chunk_size_saved = LZNT_CHUNK_SIZE;
/* Read chunk header. */
chunk_hdr = cmpr_chunk[1];
chunk_hdr <<= 8;
chunk_hdr |= cmpr_chunk[0];
if (!chunk_hdr)
break;
/* Check the size of unc buffer. */
if (unc_use < chunk_size_saved) {
size_t t1 = chunk_size_saved - unc_use;
u8 *t2 = unc_chunk + t1;
/* 'Zero' memory. */
if (t2 >= unc_end)
break;
memset(unc_chunk, 0, t1);
unc_chunk = t2;
}
}
/* Check compression boundary. */
if (cmpr_chunk > cmpr_end)
return -EINVAL;
/*
* The unc size is just a difference between current
* pointer and original one.
*/
return PtrOffset(unc, unc_chunk);
}
| linux-master | fs/ntfs3/lznt.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/types.h>
#include "ntfs_fs.h"
#define BITS_IN_SIZE_T (sizeof(size_t) * 8)
/*
* fill_mask[i] - first i bits are '1' , i = 0,1,2,3,4,5,6,7,8
* fill_mask[i] = 0xFF >> (8-i)
*/
static const u8 fill_mask[] = { 0x00, 0x01, 0x03, 0x07, 0x0F,
0x1F, 0x3F, 0x7F, 0xFF };
/*
* zero_mask[i] - first i bits are '0' , i = 0,1,2,3,4,5,6,7,8
* zero_mask[i] = 0xFF << i
*/
static const u8 zero_mask[] = { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0,
0xE0, 0xC0, 0x80, 0x00 };
/*
* are_bits_clear
*
* Return: True if all bits [bit, bit+nbits) are zeros "0".
*/
bool are_bits_clear(const void *lmap, size_t bit, size_t nbits)
{
size_t pos = bit & 7;
const u8 *map = (u8 *)lmap + (bit >> 3);
if (pos) {
if (8 - pos >= nbits)
return !nbits || !(*map & fill_mask[pos + nbits] &
zero_mask[pos]);
if (*map++ & zero_mask[pos])
return false;
nbits -= 8 - pos;
}
pos = ((size_t)map) & (sizeof(size_t) - 1);
if (pos) {
pos = sizeof(size_t) - pos;
if (nbits >= pos * 8) {
for (nbits -= pos * 8; pos; pos--, map++) {
if (*map)
return false;
}
}
}
for (pos = nbits / BITS_IN_SIZE_T; pos; pos--, map += sizeof(size_t)) {
if (*((size_t *)map))
return false;
}
for (pos = (nbits % BITS_IN_SIZE_T) >> 3; pos; pos--, map++) {
if (*map)
return false;
}
pos = nbits & 7;
if (pos && (*map & fill_mask[pos]))
return false;
return true;
}
/*
* are_bits_set
*
* Return: True if all bits [bit, bit+nbits) are ones "1".
*/
bool are_bits_set(const void *lmap, size_t bit, size_t nbits)
{
u8 mask;
size_t pos = bit & 7;
const u8 *map = (u8 *)lmap + (bit >> 3);
if (pos) {
if (8 - pos >= nbits) {
mask = fill_mask[pos + nbits] & zero_mask[pos];
return !nbits || (*map & mask) == mask;
}
mask = zero_mask[pos];
if ((*map++ & mask) != mask)
return false;
nbits -= 8 - pos;
}
pos = ((size_t)map) & (sizeof(size_t) - 1);
if (pos) {
pos = sizeof(size_t) - pos;
if (nbits >= pos * 8) {
for (nbits -= pos * 8; pos; pos--, map++) {
if (*map != 0xFF)
return false;
}
}
}
for (pos = nbits / BITS_IN_SIZE_T; pos; pos--, map += sizeof(size_t)) {
if (*((size_t *)map) != MINUS_ONE_T)
return false;
}
for (pos = (nbits % BITS_IN_SIZE_T) >> 3; pos; pos--, map++) {
if (*map != 0xFF)
return false;
}
pos = nbits & 7;
if (pos) {
mask = fill_mask[pos];
if ((*map & mask) != mask)
return false;
}
return true;
}
| linux-master | fs/ntfs3/bitfunc.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/fs.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/xattr.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
// clang-format off
#define SYSTEM_DOS_ATTRIB "system.dos_attrib"
#define SYSTEM_NTFS_ATTRIB "system.ntfs_attrib"
#define SYSTEM_NTFS_ATTRIB_BE "system.ntfs_attrib_be"
#define SYSTEM_NTFS_SECURITY "system.ntfs_security"
// clang-format on
static inline size_t unpacked_ea_size(const struct EA_FULL *ea)
{
return ea->size ? le32_to_cpu(ea->size) :
ALIGN(struct_size(ea, name,
1 + ea->name_len +
le16_to_cpu(ea->elength)),
4);
}
static inline size_t packed_ea_size(const struct EA_FULL *ea)
{
return struct_size(ea, name,
1 + ea->name_len + le16_to_cpu(ea->elength)) -
offsetof(struct EA_FULL, flags);
}
/*
* find_ea
*
* Assume there is at least one xattr in the list.
*/
static inline bool find_ea(const struct EA_FULL *ea_all, u32 bytes,
const char *name, u8 name_len, u32 *off, u32 *ea_sz)
{
u32 ea_size;
*off = 0;
if (!ea_all)
return false;
for (; *off < bytes; *off += ea_size) {
const struct EA_FULL *ea = Add2Ptr(ea_all, *off);
ea_size = unpacked_ea_size(ea);
if (ea->name_len == name_len &&
!memcmp(ea->name, name, name_len)) {
if (ea_sz)
*ea_sz = ea_size;
return true;
}
}
return false;
}
/*
* ntfs_read_ea - Read all extended attributes.
* @ea: New allocated memory.
* @info: Pointer into resident data.
*/
static int ntfs_read_ea(struct ntfs_inode *ni, struct EA_FULL **ea,
size_t add_bytes, const struct EA_INFO **info)
{
int err = -EINVAL;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTR_LIST_ENTRY *le = NULL;
struct ATTRIB *attr_info, *attr_ea;
void *ea_p;
u32 size, off, ea_size;
static_assert(le32_to_cpu(ATTR_EA_INFO) < le32_to_cpu(ATTR_EA));
*ea = NULL;
*info = NULL;
attr_info =
ni_find_attr(ni, NULL, &le, ATTR_EA_INFO, NULL, 0, NULL, NULL);
attr_ea =
ni_find_attr(ni, attr_info, &le, ATTR_EA, NULL, 0, NULL, NULL);
if (!attr_ea || !attr_info)
return 0;
*info = resident_data_ex(attr_info, sizeof(struct EA_INFO));
if (!*info)
goto out;
/* Check Ea limit. */
size = le32_to_cpu((*info)->size);
if (size > sbi->ea_max_size) {
err = -EFBIG;
goto out;
}
if (attr_size(attr_ea) > sbi->ea_max_size) {
err = -EFBIG;
goto out;
}
if (!size) {
/* EA info persists, but xattr is empty. Looks like EA problem. */
goto out;
}
/* Allocate memory for packed Ea. */
ea_p = kmalloc(size_add(size, add_bytes), GFP_NOFS);
if (!ea_p)
return -ENOMEM;
if (attr_ea->non_res) {
struct runs_tree run;
run_init(&run);
err = attr_load_runs_range(ni, ATTR_EA, NULL, 0, &run, 0, size);
if (!err)
err = ntfs_read_run_nb(sbi, &run, 0, ea_p, size, NULL);
run_close(&run);
if (err)
goto out1;
} else {
void *p = resident_data_ex(attr_ea, size);
if (!p)
goto out1;
memcpy(ea_p, p, size);
}
memset(Add2Ptr(ea_p, size), 0, add_bytes);
err = -EINVAL;
/* Check all attributes for consistency. */
for (off = 0; off < size; off += ea_size) {
const struct EA_FULL *ef = Add2Ptr(ea_p, off);
u32 bytes = size - off;
/* Check if we can use field ea->size. */
if (bytes < sizeof(ef->size))
goto out1;
if (ef->size) {
ea_size = le32_to_cpu(ef->size);
if (ea_size > bytes)
goto out1;
continue;
}
/* Check if we can use fields ef->name_len and ef->elength. */
if (bytes < offsetof(struct EA_FULL, name))
goto out1;
ea_size = ALIGN(struct_size(ef, name,
1 + ef->name_len +
le16_to_cpu(ef->elength)),
4);
if (ea_size > bytes)
goto out1;
}
*ea = ea_p;
return 0;
out1:
kfree(ea_p);
out:
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
return err;
}
/*
* ntfs_list_ea
*
* Copy a list of xattrs names into the buffer
* provided, or compute the buffer size required.
*
* Return:
* * Number of bytes used / required on
* * -ERRNO - on failure
*/
static ssize_t ntfs_list_ea(struct ntfs_inode *ni, char *buffer,
size_t bytes_per_buffer)
{
const struct EA_INFO *info;
struct EA_FULL *ea_all = NULL;
const struct EA_FULL *ea;
u32 off, size;
int err;
int ea_size;
size_t ret;
err = ntfs_read_ea(ni, &ea_all, 0, &info);
if (err)
return err;
if (!info || !ea_all)
return 0;
size = le32_to_cpu(info->size);
/* Enumerate all xattrs. */
for (ret = 0, off = 0; off < size; off += ea_size) {
ea = Add2Ptr(ea_all, off);
ea_size = unpacked_ea_size(ea);
if (!ea->name_len)
break;
if (buffer) {
if (ret + ea->name_len + 1 > bytes_per_buffer) {
err = -ERANGE;
goto out;
}
memcpy(buffer + ret, ea->name, ea->name_len);
buffer[ret + ea->name_len] = 0;
}
ret += ea->name_len + 1;
}
out:
kfree(ea_all);
return err ? err : ret;
}
static int ntfs_get_ea(struct inode *inode, const char *name, size_t name_len,
void *buffer, size_t size, size_t *required)
{
struct ntfs_inode *ni = ntfs_i(inode);
const struct EA_INFO *info;
struct EA_FULL *ea_all = NULL;
const struct EA_FULL *ea;
u32 off, len;
int err;
if (!(ni->ni_flags & NI_FLAG_EA))
return -ENODATA;
if (!required)
ni_lock(ni);
len = 0;
if (name_len > 255) {
err = -ENAMETOOLONG;
goto out;
}
err = ntfs_read_ea(ni, &ea_all, 0, &info);
if (err)
goto out;
if (!info)
goto out;
/* Enumerate all xattrs. */
if (!find_ea(ea_all, le32_to_cpu(info->size), name, name_len, &off,
NULL)) {
err = -ENODATA;
goto out;
}
ea = Add2Ptr(ea_all, off);
len = le16_to_cpu(ea->elength);
if (!buffer) {
err = 0;
goto out;
}
if (len > size) {
err = -ERANGE;
if (required)
*required = len;
goto out;
}
memcpy(buffer, ea->name + ea->name_len + 1, len);
err = 0;
out:
kfree(ea_all);
if (!required)
ni_unlock(ni);
return err ? err : len;
}
static noinline int ntfs_set_ea(struct inode *inode, const char *name,
size_t name_len, const void *value,
size_t val_size, int flags, bool locked,
__le16 *ea_size)
{
struct ntfs_inode *ni = ntfs_i(inode);
struct ntfs_sb_info *sbi = ni->mi.sbi;
int err;
struct EA_INFO ea_info;
const struct EA_INFO *info;
struct EA_FULL *new_ea;
struct EA_FULL *ea_all = NULL;
size_t add, new_pack;
u32 off, size, ea_sz;
__le16 size_pack;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
struct mft_inode *mi;
struct runs_tree ea_run;
u64 new_sz;
void *p;
if (!locked)
ni_lock(ni);
run_init(&ea_run);
if (name_len > 255) {
err = -ENAMETOOLONG;
goto out;
}
add = ALIGN(struct_size(ea_all, name, 1 + name_len + val_size), 4);
err = ntfs_read_ea(ni, &ea_all, add, &info);
if (err)
goto out;
if (!info) {
memset(&ea_info, 0, sizeof(ea_info));
size = 0;
size_pack = 0;
} else {
memcpy(&ea_info, info, sizeof(ea_info));
size = le32_to_cpu(ea_info.size);
size_pack = ea_info.size_pack;
}
if (info && find_ea(ea_all, size, name, name_len, &off, &ea_sz)) {
struct EA_FULL *ea;
if (flags & XATTR_CREATE) {
err = -EEXIST;
goto out;
}
ea = Add2Ptr(ea_all, off);
/*
* Check simple case when we try to insert xattr with the same value
* e.g. ntfs_save_wsl_perm
*/
if (val_size && le16_to_cpu(ea->elength) == val_size &&
!memcmp(ea->name + ea->name_len + 1, value, val_size)) {
/* xattr already contains the required value. */
goto out;
}
/* Remove current xattr. */
if (ea->flags & FILE_NEED_EA)
le16_add_cpu(&ea_info.count, -1);
le16_add_cpu(&ea_info.size_pack, 0 - packed_ea_size(ea));
memmove(ea, Add2Ptr(ea, ea_sz), size - off - ea_sz);
size -= ea_sz;
memset(Add2Ptr(ea_all, size), 0, ea_sz);
ea_info.size = cpu_to_le32(size);
if ((flags & XATTR_REPLACE) && !val_size) {
/* Remove xattr. */
goto update_ea;
}
} else {
if (flags & XATTR_REPLACE) {
err = -ENODATA;
goto out;
}
if (!ea_all) {
ea_all = kzalloc(add, GFP_NOFS);
if (!ea_all) {
err = -ENOMEM;
goto out;
}
}
}
/* Append new xattr. */
new_ea = Add2Ptr(ea_all, size);
new_ea->size = cpu_to_le32(add);
new_ea->flags = 0;
new_ea->name_len = name_len;
new_ea->elength = cpu_to_le16(val_size);
memcpy(new_ea->name, name, name_len);
new_ea->name[name_len] = 0;
memcpy(new_ea->name + name_len + 1, value, val_size);
new_pack = le16_to_cpu(ea_info.size_pack) + packed_ea_size(new_ea);
ea_info.size_pack = cpu_to_le16(new_pack);
/* New size of ATTR_EA. */
size += add;
ea_info.size = cpu_to_le32(size);
/*
* 1. Check ea_info.size_pack for overflow.
* 2. New attribute size must fit value from $AttrDef
*/
if (new_pack > 0xffff || size > sbi->ea_max_size) {
ntfs_inode_warn(
inode,
"The size of extended attributes must not exceed 64KiB");
err = -EFBIG; // -EINVAL?
goto out;
}
update_ea:
if (!info) {
/* Create xattr. */
if (!size) {
err = 0;
goto out;
}
err = ni_insert_resident(ni, sizeof(struct EA_INFO),
ATTR_EA_INFO, NULL, 0, NULL, NULL,
NULL);
if (err)
goto out;
err = ni_insert_resident(ni, 0, ATTR_EA, NULL, 0, NULL, NULL,
NULL);
if (err)
goto out;
}
new_sz = size;
err = attr_set_size(ni, ATTR_EA, NULL, 0, &ea_run, new_sz, &new_sz,
false, NULL);
if (err)
goto out;
le = NULL;
attr = ni_find_attr(ni, NULL, &le, ATTR_EA_INFO, NULL, 0, NULL, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
if (!size) {
/* Delete xattr, ATTR_EA_INFO */
ni_remove_attr_le(ni, attr, mi, le);
} else {
p = resident_data_ex(attr, sizeof(struct EA_INFO));
if (!p) {
err = -EINVAL;
goto out;
}
memcpy(p, &ea_info, sizeof(struct EA_INFO));
mi->dirty = true;
}
le = NULL;
attr = ni_find_attr(ni, NULL, &le, ATTR_EA, NULL, 0, NULL, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
if (!size) {
/* Delete xattr, ATTR_EA */
ni_remove_attr_le(ni, attr, mi, le);
} else if (attr->non_res) {
err = attr_load_runs_range(ni, ATTR_EA, NULL, 0, &ea_run, 0,
size);
if (err)
goto out;
err = ntfs_sb_write_run(sbi, &ea_run, 0, ea_all, size, 0);
if (err)
goto out;
} else {
p = resident_data_ex(attr, size);
if (!p) {
err = -EINVAL;
goto out;
}
memcpy(p, ea_all, size);
mi->dirty = true;
}
/* Check if we delete the last xattr. */
if (size)
ni->ni_flags |= NI_FLAG_EA;
else
ni->ni_flags &= ~NI_FLAG_EA;
if (ea_info.size_pack != size_pack)
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
if (ea_size)
*ea_size = ea_info.size_pack;
mark_inode_dirty(&ni->vfs_inode);
out:
if (!locked)
ni_unlock(ni);
run_close(&ea_run);
kfree(ea_all);
return err;
}
#ifdef CONFIG_NTFS3_FS_POSIX_ACL
/*
* ntfs_get_acl - inode_operations::get_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;
size_t req;
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;
}
ni_lock(ni);
err = ntfs_get_ea(inode, name, name_len, buf, PATH_MAX, &req);
ni_unlock(ni);
/* 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;
}
err = ntfs_set_ea(inode, name, name_len, value, size, flags, 0, NULL);
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;
}
/*
* ntfs_set_acl - inode_operations::set_acl
*/
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);
}
/*
* ntfs_init_acl - Initialize the ACLs of a new inode.
*
* Called from ntfs_create_inode().
*/
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
/*
* ntfs_acl_chmod - Helper for ntfs3_setattr().
*/
int ntfs_acl_chmod(struct mnt_idmap *idmap, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
struct super_block *sb = inode->i_sb;
if (!(sb->s_flags & SB_POSIXACL))
return 0;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
return posix_acl_chmod(idmap, dentry, inode->i_mode);
}
/*
* ntfs_listxattr - inode_operations::listxattr
*/
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);
ssize_t ret;
if (!(ni->ni_flags & NI_FLAG_EA)) {
/* no xattr in file */
return 0;
}
ni_lock(ni);
ret = ntfs_list_ea(ni, buffer, size);
ni_unlock(ni);
return ret;
}
static int ntfs_getxattr(const struct xattr_handler *handler, struct dentry *de,
struct inode *inode, const char *name, void *buffer,
size_t size)
{
int err;
struct ntfs_inode *ni = ntfs_i(inode);
/* Dispatch request. */
if (!strcmp(name, SYSTEM_DOS_ATTRIB)) {
/* system.dos_attrib */
if (!buffer) {
err = sizeof(u8);
} else if (size < sizeof(u8)) {
err = -ENODATA;
} else {
err = sizeof(u8);
*(u8 *)buffer = le32_to_cpu(ni->std_fa);
}
goto out;
}
if (!strcmp(name, SYSTEM_NTFS_ATTRIB) ||
!strcmp(name, SYSTEM_NTFS_ATTRIB_BE)) {
/* system.ntfs_attrib */
if (!buffer) {
err = sizeof(u32);
} else if (size < sizeof(u32)) {
err = -ENODATA;
} else {
err = sizeof(u32);
*(u32 *)buffer = le32_to_cpu(ni->std_fa);
if (!strcmp(name, SYSTEM_NTFS_ATTRIB_BE))
*(__be32 *)buffer = cpu_to_be32(*(u32 *)buffer);
}
goto out;
}
if (!strcmp(name, SYSTEM_NTFS_SECURITY)) {
/* system.ntfs_security*/
struct SECURITY_DESCRIPTOR_RELATIVE *sd = NULL;
size_t sd_size = 0;
if (!is_ntfs3(ni->mi.sbi)) {
/* We should get nt4 security. */
err = -EINVAL;
goto out;
} else if (le32_to_cpu(ni->std_security_id) <
SECURITY_ID_FIRST) {
err = -ENOENT;
goto out;
}
err = ntfs_get_security_by_id(ni->mi.sbi, ni->std_security_id,
&sd, &sd_size);
if (err)
goto out;
if (!is_sd_valid(sd, sd_size)) {
ntfs_inode_warn(
inode,
"looks like you get incorrect security descriptor id=%u",
ni->std_security_id);
}
if (!buffer) {
err = sd_size;
} else if (size < sd_size) {
err = -ENODATA;
} else {
err = sd_size;
memcpy(buffer, sd, sd_size);
}
kfree(sd);
goto out;
}
/* Deal with NTFS extended attribute. */
err = ntfs_get_ea(inode, name, strlen(name), buffer, size, NULL);
out:
return err;
}
/*
* ntfs_setxattr - inode_operations::setxattr
*/
static noinline int ntfs_setxattr(const struct xattr_handler *handler,
struct mnt_idmap *idmap, struct dentry *de,
struct inode *inode, const char *name,
const void *value, size_t size, int flags)
{
int err = -EINVAL;
struct ntfs_inode *ni = ntfs_i(inode);
enum FILE_ATTRIBUTE new_fa;
/* Dispatch request. */
if (!strcmp(name, SYSTEM_DOS_ATTRIB)) {
if (sizeof(u8) != size)
goto out;
new_fa = cpu_to_le32(*(u8 *)value);
goto set_new_fa;
}
if (!strcmp(name, SYSTEM_NTFS_ATTRIB) ||
!strcmp(name, SYSTEM_NTFS_ATTRIB_BE)) {
if (size != sizeof(u32))
goto out;
if (!strcmp(name, SYSTEM_NTFS_ATTRIB_BE))
new_fa = cpu_to_le32(be32_to_cpu(*(__be32 *)value));
else
new_fa = cpu_to_le32(*(u32 *)value);
if (S_ISREG(inode->i_mode)) {
/* Process compressed/sparsed in special way. */
ni_lock(ni);
err = ni_new_attr_flags(ni, new_fa);
ni_unlock(ni);
if (err)
goto out;
}
set_new_fa:
/*
* Thanks Mark Harmstone:
* Keep directory bit consistency.
*/
if (S_ISDIR(inode->i_mode))
new_fa |= FILE_ATTRIBUTE_DIRECTORY;
else
new_fa &= ~FILE_ATTRIBUTE_DIRECTORY;
if (ni->std_fa != new_fa) {
ni->std_fa = new_fa;
if (new_fa & FILE_ATTRIBUTE_READONLY)
inode->i_mode &= ~0222;
else
inode->i_mode |= 0222;
/* Std attribute always in primary record. */
ni->mi.dirty = true;
mark_inode_dirty(inode);
}
err = 0;
goto out;
}
if (!strcmp(name, SYSTEM_NTFS_SECURITY)) {
/* system.ntfs_security*/
__le32 security_id;
bool inserted;
struct ATTR_STD_INFO5 *std;
if (!is_ntfs3(ni->mi.sbi)) {
/*
* We should replace ATTR_SECURE.
* Skip this way cause it is nt4 feature.
*/
err = -EINVAL;
goto out;
}
if (!is_sd_valid(value, size)) {
err = -EINVAL;
ntfs_inode_warn(
inode,
"you try to set invalid security descriptor");
goto out;
}
err = ntfs_insert_security(ni->mi.sbi, value, size,
&security_id, &inserted);
if (err)
goto out;
ni_lock(ni);
std = ni_std5(ni);
if (!std) {
err = -EINVAL;
} else if (std->security_id != security_id) {
std->security_id = ni->std_security_id = security_id;
/* Std attribute always in primary record. */
ni->mi.dirty = true;
mark_inode_dirty(&ni->vfs_inode);
}
ni_unlock(ni);
goto out;
}
/* Deal with NTFS extended attribute. */
err = ntfs_set_ea(inode, name, strlen(name), value, size, flags, 0,
NULL);
out:
inode_set_ctime_current(inode);
mark_inode_dirty(inode);
return err;
}
/*
* ntfs_save_wsl_perm
*
* save uid/gid/mode in xattr
*/
int ntfs_save_wsl_perm(struct inode *inode, __le16 *ea_size)
{
int err;
__le32 value;
struct ntfs_inode *ni = ntfs_i(inode);
ni_lock(ni);
value = cpu_to_le32(i_uid_read(inode));
err = ntfs_set_ea(inode, "$LXUID", sizeof("$LXUID") - 1, &value,
sizeof(value), 0, true, ea_size);
if (err)
goto out;
value = cpu_to_le32(i_gid_read(inode));
err = ntfs_set_ea(inode, "$LXGID", sizeof("$LXGID") - 1, &value,
sizeof(value), 0, true, ea_size);
if (err)
goto out;
value = cpu_to_le32(inode->i_mode);
err = ntfs_set_ea(inode, "$LXMOD", sizeof("$LXMOD") - 1, &value,
sizeof(value), 0, true, ea_size);
if (err)
goto out;
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
value = cpu_to_le32(inode->i_rdev);
err = ntfs_set_ea(inode, "$LXDEV", sizeof("$LXDEV") - 1, &value,
sizeof(value), 0, true, ea_size);
if (err)
goto out;
}
out:
ni_unlock(ni);
/* In case of error should we delete all WSL xattr? */
return err;
}
/*
* ntfs_get_wsl_perm
*
* get uid/gid/mode from xattr
* it is called from ntfs_iget5->ntfs_read_mft
*/
void ntfs_get_wsl_perm(struct inode *inode)
{
size_t sz;
__le32 value[3];
if (ntfs_get_ea(inode, "$LXUID", sizeof("$LXUID") - 1, &value[0],
sizeof(value[0]), &sz) == sizeof(value[0]) &&
ntfs_get_ea(inode, "$LXGID", sizeof("$LXGID") - 1, &value[1],
sizeof(value[1]), &sz) == sizeof(value[1]) &&
ntfs_get_ea(inode, "$LXMOD", sizeof("$LXMOD") - 1, &value[2],
sizeof(value[2]), &sz) == sizeof(value[2])) {
i_uid_write(inode, (uid_t)le32_to_cpu(value[0]));
i_gid_write(inode, (gid_t)le32_to_cpu(value[1]));
inode->i_mode = le32_to_cpu(value[2]);
if (ntfs_get_ea(inode, "$LXDEV", sizeof("$$LXDEV") - 1,
&value[0], sizeof(value),
&sz) == sizeof(value[0])) {
inode->i_rdev = le32_to_cpu(value[0]);
}
}
}
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 *ntfs_xattr_handlers[] = {
&ntfs_other_xattr_handler,
NULL,
};
// clang-format on
| linux-master | fs/ntfs3/xattr.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
* This code builds two trees of free clusters extents.
* Trees are sorted by start of extent and by length of extent.
* NTFS_MAX_WND_EXTENTS defines the maximum number of elements in trees.
* In extreme case code reads on-disk bitmap to find free clusters.
*
*/
#include <linux/buffer_head.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* Maximum number of extents in tree.
*/
#define NTFS_MAX_WND_EXTENTS (32u * 1024u)
struct rb_node_key {
struct rb_node node;
size_t key;
};
struct e_node {
struct rb_node_key start; /* Tree sorted by start. */
struct rb_node_key count; /* Tree sorted by len. */
};
static int wnd_rescan(struct wnd_bitmap *wnd);
static struct buffer_head *wnd_map(struct wnd_bitmap *wnd, size_t iw);
static bool wnd_is_free_hlp(struct wnd_bitmap *wnd, size_t bit, size_t bits);
static struct kmem_cache *ntfs_enode_cachep;
int __init ntfs3_init_bitmap(void)
{
ntfs_enode_cachep = kmem_cache_create("ntfs3_enode_cache",
sizeof(struct e_node), 0,
SLAB_RECLAIM_ACCOUNT, NULL);
return ntfs_enode_cachep ? 0 : -ENOMEM;
}
void ntfs3_exit_bitmap(void)
{
kmem_cache_destroy(ntfs_enode_cachep);
}
/*
* wnd_scan
*
* b_pos + b_len - biggest fragment.
* Scan range [wpos wbits) window @buf.
*
* Return: -1 if not found.
*/
static size_t wnd_scan(const void *buf, size_t wbit, u32 wpos, u32 wend,
size_t to_alloc, size_t *prev_tail, size_t *b_pos,
size_t *b_len)
{
while (wpos < wend) {
size_t free_len;
u32 free_bits, end;
u32 used = find_next_zero_bit_le(buf, wend, wpos);
if (used >= wend) {
if (*b_len < *prev_tail) {
*b_pos = wbit - *prev_tail;
*b_len = *prev_tail;
}
*prev_tail = 0;
return -1;
}
if (used > wpos) {
wpos = used;
if (*b_len < *prev_tail) {
*b_pos = wbit - *prev_tail;
*b_len = *prev_tail;
}
*prev_tail = 0;
}
/*
* Now we have a fragment [wpos, wend) staring with 0.
*/
end = wpos + to_alloc - *prev_tail;
free_bits = find_next_bit_le(buf, min(end, wend), wpos);
free_len = *prev_tail + free_bits - wpos;
if (*b_len < free_len) {
*b_pos = wbit + wpos - *prev_tail;
*b_len = free_len;
}
if (free_len >= to_alloc)
return wbit + wpos - *prev_tail;
if (free_bits >= wend) {
*prev_tail += free_bits - wpos;
return -1;
}
wpos = free_bits + 1;
*prev_tail = 0;
}
return -1;
}
/*
* wnd_close - Frees all resources.
*/
void wnd_close(struct wnd_bitmap *wnd)
{
struct rb_node *node, *next;
kfree(wnd->free_bits);
run_close(&wnd->run);
node = rb_first(&wnd->start_tree);
while (node) {
next = rb_next(node);
rb_erase(node, &wnd->start_tree);
kmem_cache_free(ntfs_enode_cachep,
rb_entry(node, struct e_node, start.node));
node = next;
}
}
static struct rb_node *rb_lookup(struct rb_root *root, size_t v)
{
struct rb_node **p = &root->rb_node;
struct rb_node *r = NULL;
while (*p) {
struct rb_node_key *k;
k = rb_entry(*p, struct rb_node_key, node);
if (v < k->key) {
p = &(*p)->rb_left;
} else if (v > k->key) {
r = &k->node;
p = &(*p)->rb_right;
} else {
return &k->node;
}
}
return r;
}
/*
* rb_insert_count - Helper function to insert special kind of 'count' tree.
*/
static inline bool rb_insert_count(struct rb_root *root, struct e_node *e)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
size_t e_ckey = e->count.key;
size_t e_skey = e->start.key;
while (*p) {
struct e_node *k =
rb_entry(parent = *p, struct e_node, count.node);
if (e_ckey > k->count.key) {
p = &(*p)->rb_left;
} else if (e_ckey < k->count.key) {
p = &(*p)->rb_right;
} else if (e_skey < k->start.key) {
p = &(*p)->rb_left;
} else if (e_skey > k->start.key) {
p = &(*p)->rb_right;
} else {
WARN_ON(1);
return false;
}
}
rb_link_node(&e->count.node, parent, p);
rb_insert_color(&e->count.node, root);
return true;
}
/*
* rb_insert_start - Helper function to insert special kind of 'count' tree.
*/
static inline bool rb_insert_start(struct rb_root *root, struct e_node *e)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
size_t e_skey = e->start.key;
while (*p) {
struct e_node *k;
parent = *p;
k = rb_entry(parent, struct e_node, start.node);
if (e_skey < k->start.key) {
p = &(*p)->rb_left;
} else if (e_skey > k->start.key) {
p = &(*p)->rb_right;
} else {
WARN_ON(1);
return false;
}
}
rb_link_node(&e->start.node, parent, p);
rb_insert_color(&e->start.node, root);
return true;
}
/*
* wnd_add_free_ext - Adds a new extent of free space.
* @build: 1 when building tree.
*/
static void wnd_add_free_ext(struct wnd_bitmap *wnd, size_t bit, size_t len,
bool build)
{
struct e_node *e, *e0 = NULL;
size_t ib, end_in = bit + len;
struct rb_node *n;
if (build) {
/* Use extent_min to filter too short extents. */
if (wnd->count >= NTFS_MAX_WND_EXTENTS &&
len <= wnd->extent_min) {
wnd->uptodated = -1;
return;
}
} else {
/* Try to find extent before 'bit'. */
n = rb_lookup(&wnd->start_tree, bit);
if (!n) {
n = rb_first(&wnd->start_tree);
} else {
e = rb_entry(n, struct e_node, start.node);
n = rb_next(n);
if (e->start.key + e->count.key == bit) {
/* Remove left. */
bit = e->start.key;
len += e->count.key;
rb_erase(&e->start.node, &wnd->start_tree);
rb_erase(&e->count.node, &wnd->count_tree);
wnd->count -= 1;
e0 = e;
}
}
while (n) {
size_t next_end;
e = rb_entry(n, struct e_node, start.node);
next_end = e->start.key + e->count.key;
if (e->start.key > end_in)
break;
/* Remove right. */
n = rb_next(n);
len += next_end - end_in;
end_in = next_end;
rb_erase(&e->start.node, &wnd->start_tree);
rb_erase(&e->count.node, &wnd->count_tree);
wnd->count -= 1;
if (!e0)
e0 = e;
else
kmem_cache_free(ntfs_enode_cachep, e);
}
if (wnd->uptodated != 1) {
/* Check bits before 'bit'. */
ib = wnd->zone_bit == wnd->zone_end ||
bit < wnd->zone_end ?
0 :
wnd->zone_end;
while (bit > ib && wnd_is_free_hlp(wnd, bit - 1, 1)) {
bit -= 1;
len += 1;
}
/* Check bits after 'end_in'. */
ib = wnd->zone_bit == wnd->zone_end ||
end_in > wnd->zone_bit ?
wnd->nbits :
wnd->zone_bit;
while (end_in < ib && wnd_is_free_hlp(wnd, end_in, 1)) {
end_in += 1;
len += 1;
}
}
}
/* Insert new fragment. */
if (wnd->count >= NTFS_MAX_WND_EXTENTS) {
if (e0)
kmem_cache_free(ntfs_enode_cachep, e0);
wnd->uptodated = -1;
/* Compare with smallest fragment. */
n = rb_last(&wnd->count_tree);
e = rb_entry(n, struct e_node, count.node);
if (len <= e->count.key)
goto out; /* Do not insert small fragments. */
if (build) {
struct e_node *e2;
n = rb_prev(n);
e2 = rb_entry(n, struct e_node, count.node);
/* Smallest fragment will be 'e2->count.key'. */
wnd->extent_min = e2->count.key;
}
/* Replace smallest fragment by new one. */
rb_erase(&e->start.node, &wnd->start_tree);
rb_erase(&e->count.node, &wnd->count_tree);
wnd->count -= 1;
} else {
e = e0 ? e0 : kmem_cache_alloc(ntfs_enode_cachep, GFP_ATOMIC);
if (!e) {
wnd->uptodated = -1;
goto out;
}
if (build && len <= wnd->extent_min)
wnd->extent_min = len;
}
e->start.key = bit;
e->count.key = len;
if (len > wnd->extent_max)
wnd->extent_max = len;
rb_insert_start(&wnd->start_tree, e);
rb_insert_count(&wnd->count_tree, e);
wnd->count += 1;
out:;
}
/*
* wnd_remove_free_ext - Remove a run from the cached free space.
*/
static void wnd_remove_free_ext(struct wnd_bitmap *wnd, size_t bit, size_t len)
{
struct rb_node *n, *n3;
struct e_node *e, *e3;
size_t end_in = bit + len;
size_t end3, end, new_key, new_len, max_new_len;
/* Try to find extent before 'bit'. */
n = rb_lookup(&wnd->start_tree, bit);
if (!n)
return;
e = rb_entry(n, struct e_node, start.node);
end = e->start.key + e->count.key;
new_key = new_len = 0;
len = e->count.key;
/* Range [bit,end_in) must be inside 'e' or outside 'e' and 'n'. */
if (e->start.key > bit)
;
else if (end_in <= end) {
/* Range [bit,end_in) inside 'e'. */
new_key = end_in;
new_len = end - end_in;
len = bit - e->start.key;
} else if (bit > end) {
bool bmax = false;
n3 = rb_next(n);
while (n3) {
e3 = rb_entry(n3, struct e_node, start.node);
if (e3->start.key >= end_in)
break;
if (e3->count.key == wnd->extent_max)
bmax = true;
end3 = e3->start.key + e3->count.key;
if (end3 > end_in) {
e3->start.key = end_in;
rb_erase(&e3->count.node, &wnd->count_tree);
e3->count.key = end3 - end_in;
rb_insert_count(&wnd->count_tree, e3);
break;
}
n3 = rb_next(n3);
rb_erase(&e3->start.node, &wnd->start_tree);
rb_erase(&e3->count.node, &wnd->count_tree);
wnd->count -= 1;
kmem_cache_free(ntfs_enode_cachep, e3);
}
if (!bmax)
return;
n3 = rb_first(&wnd->count_tree);
wnd->extent_max =
n3 ? rb_entry(n3, struct e_node, count.node)->count.key :
0;
return;
}
if (e->count.key != wnd->extent_max) {
;
} else if (rb_prev(&e->count.node)) {
;
} else {
n3 = rb_next(&e->count.node);
max_new_len = max(len, new_len);
if (!n3) {
wnd->extent_max = max_new_len;
} else {
e3 = rb_entry(n3, struct e_node, count.node);
wnd->extent_max = max(e3->count.key, max_new_len);
}
}
if (!len) {
if (new_len) {
e->start.key = new_key;
rb_erase(&e->count.node, &wnd->count_tree);
e->count.key = new_len;
rb_insert_count(&wnd->count_tree, e);
} else {
rb_erase(&e->start.node, &wnd->start_tree);
rb_erase(&e->count.node, &wnd->count_tree);
wnd->count -= 1;
kmem_cache_free(ntfs_enode_cachep, e);
}
goto out;
}
rb_erase(&e->count.node, &wnd->count_tree);
e->count.key = len;
rb_insert_count(&wnd->count_tree, e);
if (!new_len)
goto out;
if (wnd->count >= NTFS_MAX_WND_EXTENTS) {
wnd->uptodated = -1;
/* Get minimal extent. */
e = rb_entry(rb_last(&wnd->count_tree), struct e_node,
count.node);
if (e->count.key > new_len)
goto out;
/* Replace minimum. */
rb_erase(&e->start.node, &wnd->start_tree);
rb_erase(&e->count.node, &wnd->count_tree);
wnd->count -= 1;
} else {
e = kmem_cache_alloc(ntfs_enode_cachep, GFP_ATOMIC);
if (!e)
wnd->uptodated = -1;
}
if (e) {
e->start.key = new_key;
e->count.key = new_len;
rb_insert_start(&wnd->start_tree, e);
rb_insert_count(&wnd->count_tree, e);
wnd->count += 1;
}
out:
if (!wnd->count && 1 != wnd->uptodated)
wnd_rescan(wnd);
}
/*
* wnd_rescan - Scan all bitmap. Used while initialization.
*/
static int wnd_rescan(struct wnd_bitmap *wnd)
{
int err = 0;
size_t prev_tail = 0;
struct super_block *sb = wnd->sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
u64 lbo, len = 0;
u32 blocksize = sb->s_blocksize;
u8 cluster_bits = sbi->cluster_bits;
u32 wbits = 8 * sb->s_blocksize;
u32 used, frb;
size_t wpos, wbit, iw, vbo;
struct buffer_head *bh = NULL;
CLST lcn, clen;
wnd->uptodated = 0;
wnd->extent_max = 0;
wnd->extent_min = MINUS_ONE_T;
wnd->total_zeroes = 0;
vbo = 0;
for (iw = 0; iw < wnd->nwnd; iw++) {
if (iw + 1 == wnd->nwnd)
wbits = wnd->bits_last;
if (wnd->inited) {
if (!wnd->free_bits[iw]) {
/* All ones. */
if (prev_tail) {
wnd_add_free_ext(wnd,
vbo * 8 - prev_tail,
prev_tail, true);
prev_tail = 0;
}
goto next_wnd;
}
if (wbits == wnd->free_bits[iw]) {
/* All zeroes. */
prev_tail += wbits;
wnd->total_zeroes += wbits;
goto next_wnd;
}
}
if (!len) {
u32 off = vbo & sbi->cluster_mask;
if (!run_lookup_entry(&wnd->run, vbo >> cluster_bits,
&lcn, &clen, NULL)) {
err = -ENOENT;
goto out;
}
lbo = ((u64)lcn << cluster_bits) + off;
len = ((u64)clen << cluster_bits) - off;
}
bh = ntfs_bread(sb, lbo >> sb->s_blocksize_bits);
if (!bh) {
err = -EIO;
goto out;
}
used = ntfs_bitmap_weight_le(bh->b_data, wbits);
if (used < wbits) {
frb = wbits - used;
wnd->free_bits[iw] = frb;
wnd->total_zeroes += frb;
}
wpos = 0;
wbit = vbo * 8;
if (wbit + wbits > wnd->nbits)
wbits = wnd->nbits - wbit;
do {
used = find_next_zero_bit_le(bh->b_data, wbits, wpos);
if (used > wpos && prev_tail) {
wnd_add_free_ext(wnd, wbit + wpos - prev_tail,
prev_tail, true);
prev_tail = 0;
}
wpos = used;
if (wpos >= wbits) {
/* No free blocks. */
prev_tail = 0;
break;
}
frb = find_next_bit_le(bh->b_data, wbits, wpos);
if (frb >= wbits) {
/* Keep last free block. */
prev_tail += frb - wpos;
break;
}
wnd_add_free_ext(wnd, wbit + wpos - prev_tail,
frb + prev_tail - wpos, true);
/* Skip free block and first '1'. */
wpos = frb + 1;
/* Reset previous tail. */
prev_tail = 0;
} while (wpos < wbits);
next_wnd:
if (bh)
put_bh(bh);
bh = NULL;
vbo += blocksize;
if (len) {
len -= blocksize;
lbo += blocksize;
}
}
/* Add last block. */
if (prev_tail)
wnd_add_free_ext(wnd, wnd->nbits - prev_tail, prev_tail, true);
/*
* Before init cycle wnd->uptodated was 0.
* If any errors or limits occurs while initialization then
* wnd->uptodated will be -1.
* If 'uptodated' is still 0 then Tree is really updated.
*/
if (!wnd->uptodated)
wnd->uptodated = 1;
if (wnd->zone_bit != wnd->zone_end) {
size_t zlen = wnd->zone_end - wnd->zone_bit;
wnd->zone_end = wnd->zone_bit;
wnd_zone_set(wnd, wnd->zone_bit, zlen);
}
out:
return err;
}
int wnd_init(struct wnd_bitmap *wnd, struct super_block *sb, size_t nbits)
{
int err;
u32 blocksize = sb->s_blocksize;
u32 wbits = blocksize * 8;
init_rwsem(&wnd->rw_lock);
wnd->sb = sb;
wnd->nbits = nbits;
wnd->total_zeroes = nbits;
wnd->extent_max = MINUS_ONE_T;
wnd->zone_bit = wnd->zone_end = 0;
wnd->nwnd = bytes_to_block(sb, bitmap_size(nbits));
wnd->bits_last = nbits & (wbits - 1);
if (!wnd->bits_last)
wnd->bits_last = wbits;
wnd->free_bits =
kcalloc(wnd->nwnd, sizeof(u16), GFP_NOFS | __GFP_NOWARN);
if (!wnd->free_bits)
return -ENOMEM;
err = wnd_rescan(wnd);
if (err)
return err;
wnd->inited = true;
return 0;
}
/*
* wnd_map - Call sb_bread for requested window.
*/
static struct buffer_head *wnd_map(struct wnd_bitmap *wnd, size_t iw)
{
size_t vbo;
CLST lcn, clen;
struct super_block *sb = wnd->sb;
struct ntfs_sb_info *sbi;
struct buffer_head *bh;
u64 lbo;
sbi = sb->s_fs_info;
vbo = (u64)iw << sb->s_blocksize_bits;
if (!run_lookup_entry(&wnd->run, vbo >> sbi->cluster_bits, &lcn, &clen,
NULL)) {
return ERR_PTR(-ENOENT);
}
lbo = ((u64)lcn << sbi->cluster_bits) + (vbo & sbi->cluster_mask);
bh = ntfs_bread(wnd->sb, lbo >> sb->s_blocksize_bits);
if (!bh)
return ERR_PTR(-EIO);
return bh;
}
/*
* wnd_set_free - Mark the bits range from bit to bit + bits as free.
*/
int wnd_set_free(struct wnd_bitmap *wnd, size_t bit, size_t bits)
{
int err = 0;
struct super_block *sb = wnd->sb;
size_t bits0 = bits;
u32 wbits = 8 * sb->s_blocksize;
size_t iw = bit >> (sb->s_blocksize_bits + 3);
u32 wbit = bit & (wbits - 1);
struct buffer_head *bh;
while (iw < wnd->nwnd && bits) {
u32 tail, op;
if (iw + 1 == wnd->nwnd)
wbits = wnd->bits_last;
tail = wbits - wbit;
op = min_t(u32, tail, bits);
bh = wnd_map(wnd, iw);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
break;
}
lock_buffer(bh);
ntfs_bitmap_clear_le(bh->b_data, wbit, op);
wnd->free_bits[iw] += op;
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
put_bh(bh);
wnd->total_zeroes += op;
bits -= op;
wbit = 0;
iw += 1;
}
wnd_add_free_ext(wnd, bit, bits0, false);
return err;
}
/*
* wnd_set_used - Mark the bits range from bit to bit + bits as used.
*/
int wnd_set_used(struct wnd_bitmap *wnd, size_t bit, size_t bits)
{
int err = 0;
struct super_block *sb = wnd->sb;
size_t bits0 = bits;
size_t iw = bit >> (sb->s_blocksize_bits + 3);
u32 wbits = 8 * sb->s_blocksize;
u32 wbit = bit & (wbits - 1);
struct buffer_head *bh;
while (iw < wnd->nwnd && bits) {
u32 tail, op;
if (unlikely(iw + 1 == wnd->nwnd))
wbits = wnd->bits_last;
tail = wbits - wbit;
op = min_t(u32, tail, bits);
bh = wnd_map(wnd, iw);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
break;
}
lock_buffer(bh);
ntfs_bitmap_set_le(bh->b_data, wbit, op);
wnd->free_bits[iw] -= op;
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
put_bh(bh);
wnd->total_zeroes -= op;
bits -= op;
wbit = 0;
iw += 1;
}
if (!RB_EMPTY_ROOT(&wnd->start_tree))
wnd_remove_free_ext(wnd, bit, bits0);
return err;
}
/*
* wnd_set_used_safe - Mark the bits range from bit to bit + bits as used.
*
* Unlikely wnd_set_used/wnd_set_free this function is not full trusted.
* It scans every bit in bitmap and marks free bit as used.
* @done - how many bits were marked as used.
*
* NOTE: normally *done should be 0.
*/
int wnd_set_used_safe(struct wnd_bitmap *wnd, size_t bit, size_t bits,
size_t *done)
{
size_t i, from = 0, len = 0;
int err = 0;
*done = 0;
for (i = 0; i < bits; i++) {
if (wnd_is_free(wnd, bit + i, 1)) {
if (!len)
from = bit + i;
len += 1;
} else if (len) {
err = wnd_set_used(wnd, from, len);
*done += len;
len = 0;
if (err)
break;
}
}
if (len) {
/* last fragment. */
err = wnd_set_used(wnd, from, len);
*done += len;
}
return err;
}
/*
* wnd_is_free_hlp
*
* Return: True if all clusters [bit, bit+bits) are free (bitmap only).
*/
static bool wnd_is_free_hlp(struct wnd_bitmap *wnd, size_t bit, size_t bits)
{
struct super_block *sb = wnd->sb;
size_t iw = bit >> (sb->s_blocksize_bits + 3);
u32 wbits = 8 * sb->s_blocksize;
u32 wbit = bit & (wbits - 1);
while (iw < wnd->nwnd && bits) {
u32 tail, op;
if (unlikely(iw + 1 == wnd->nwnd))
wbits = wnd->bits_last;
tail = wbits - wbit;
op = min_t(u32, tail, bits);
if (wbits != wnd->free_bits[iw]) {
bool ret;
struct buffer_head *bh = wnd_map(wnd, iw);
if (IS_ERR(bh))
return false;
ret = are_bits_clear(bh->b_data, wbit, op);
put_bh(bh);
if (!ret)
return false;
}
bits -= op;
wbit = 0;
iw += 1;
}
return true;
}
/*
* wnd_is_free
*
* Return: True if all clusters [bit, bit+bits) are free.
*/
bool wnd_is_free(struct wnd_bitmap *wnd, size_t bit, size_t bits)
{
bool ret;
struct rb_node *n;
size_t end;
struct e_node *e;
if (RB_EMPTY_ROOT(&wnd->start_tree))
goto use_wnd;
n = rb_lookup(&wnd->start_tree, bit);
if (!n)
goto use_wnd;
e = rb_entry(n, struct e_node, start.node);
end = e->start.key + e->count.key;
if (bit < end && bit + bits <= end)
return true;
use_wnd:
ret = wnd_is_free_hlp(wnd, bit, bits);
return ret;
}
/*
* wnd_is_used
*
* Return: True if all clusters [bit, bit+bits) are used.
*/
bool wnd_is_used(struct wnd_bitmap *wnd, size_t bit, size_t bits)
{
bool ret = false;
struct super_block *sb = wnd->sb;
size_t iw = bit >> (sb->s_blocksize_bits + 3);
u32 wbits = 8 * sb->s_blocksize;
u32 wbit = bit & (wbits - 1);
size_t end;
struct rb_node *n;
struct e_node *e;
if (RB_EMPTY_ROOT(&wnd->start_tree))
goto use_wnd;
end = bit + bits;
n = rb_lookup(&wnd->start_tree, end - 1);
if (!n)
goto use_wnd;
e = rb_entry(n, struct e_node, start.node);
if (e->start.key + e->count.key > bit)
return false;
use_wnd:
while (iw < wnd->nwnd && bits) {
u32 tail, op;
if (unlikely(iw + 1 == wnd->nwnd))
wbits = wnd->bits_last;
tail = wbits - wbit;
op = min_t(u32, tail, bits);
if (wnd->free_bits[iw]) {
bool ret;
struct buffer_head *bh = wnd_map(wnd, iw);
if (IS_ERR(bh))
goto out;
ret = are_bits_set(bh->b_data, wbit, op);
put_bh(bh);
if (!ret)
goto out;
}
bits -= op;
wbit = 0;
iw += 1;
}
ret = true;
out:
return ret;
}
/*
* wnd_find - Look for free space.
*
* - flags - BITMAP_FIND_XXX flags
*
* Return: 0 if not found.
*/
size_t wnd_find(struct wnd_bitmap *wnd, size_t to_alloc, size_t hint,
size_t flags, size_t *allocated)
{
struct super_block *sb;
u32 wbits, wpos, wzbit, wzend;
size_t fnd, max_alloc, b_len, b_pos;
size_t iw, prev_tail, nwnd, wbit, ebit, zbit, zend;
size_t to_alloc0 = to_alloc;
const struct e_node *e;
const struct rb_node *pr, *cr;
u8 log2_bits;
bool fbits_valid;
struct buffer_head *bh;
/* Fast checking for available free space. */
if (flags & BITMAP_FIND_FULL) {
size_t zeroes = wnd_zeroes(wnd);
zeroes -= wnd->zone_end - wnd->zone_bit;
if (zeroes < to_alloc0)
goto no_space;
if (to_alloc0 > wnd->extent_max)
goto no_space;
} else {
if (to_alloc > wnd->extent_max)
to_alloc = wnd->extent_max;
}
if (wnd->zone_bit <= hint && hint < wnd->zone_end)
hint = wnd->zone_end;
max_alloc = wnd->nbits;
b_len = b_pos = 0;
if (hint >= max_alloc)
hint = 0;
if (RB_EMPTY_ROOT(&wnd->start_tree)) {
if (wnd->uptodated == 1) {
/* Extents tree is updated -> No free space. */
goto no_space;
}
goto scan_bitmap;
}
e = NULL;
if (!hint)
goto allocate_biggest;
/* Use hint: Enumerate extents by start >= hint. */
pr = NULL;
cr = wnd->start_tree.rb_node;
for (;;) {
e = rb_entry(cr, struct e_node, start.node);
if (e->start.key == hint)
break;
if (e->start.key < hint) {
pr = cr;
cr = cr->rb_right;
if (!cr)
break;
continue;
}
cr = cr->rb_left;
if (!cr) {
e = pr ? rb_entry(pr, struct e_node, start.node) : NULL;
break;
}
}
if (!e)
goto allocate_biggest;
if (e->start.key + e->count.key > hint) {
/* We have found extension with 'hint' inside. */
size_t len = e->start.key + e->count.key - hint;
if (len >= to_alloc && hint + to_alloc <= max_alloc) {
fnd = hint;
goto found;
}
if (!(flags & BITMAP_FIND_FULL)) {
if (len > to_alloc)
len = to_alloc;
if (hint + len <= max_alloc) {
fnd = hint;
to_alloc = len;
goto found;
}
}
}
allocate_biggest:
/* Allocate from biggest free extent. */
e = rb_entry(rb_first(&wnd->count_tree), struct e_node, count.node);
if (e->count.key != wnd->extent_max)
wnd->extent_max = e->count.key;
if (e->count.key < max_alloc) {
if (e->count.key >= to_alloc) {
;
} else if (flags & BITMAP_FIND_FULL) {
if (e->count.key < to_alloc0) {
/* Biggest free block is less then requested. */
goto no_space;
}
to_alloc = e->count.key;
} else if (-1 != wnd->uptodated) {
to_alloc = e->count.key;
} else {
/* Check if we can use more bits. */
size_t op, max_check;
struct rb_root start_tree;
memcpy(&start_tree, &wnd->start_tree,
sizeof(struct rb_root));
memset(&wnd->start_tree, 0, sizeof(struct rb_root));
max_check = e->start.key + to_alloc;
if (max_check > max_alloc)
max_check = max_alloc;
for (op = e->start.key + e->count.key; op < max_check;
op++) {
if (!wnd_is_free(wnd, op, 1))
break;
}
memcpy(&wnd->start_tree, &start_tree,
sizeof(struct rb_root));
to_alloc = op - e->start.key;
}
/* Prepare to return. */
fnd = e->start.key;
if (e->start.key + to_alloc > max_alloc)
to_alloc = max_alloc - e->start.key;
goto found;
}
if (wnd->uptodated == 1) {
/* Extents tree is updated -> no free space. */
goto no_space;
}
b_len = e->count.key;
b_pos = e->start.key;
scan_bitmap:
sb = wnd->sb;
log2_bits = sb->s_blocksize_bits + 3;
/* At most two ranges [hint, max_alloc) + [0, hint). */
Again:
/* TODO: Optimize request for case nbits > wbits. */
iw = hint >> log2_bits;
wbits = sb->s_blocksize * 8;
wpos = hint & (wbits - 1);
prev_tail = 0;
fbits_valid = true;
if (max_alloc == wnd->nbits) {
nwnd = wnd->nwnd;
} else {
size_t t = max_alloc + wbits - 1;
nwnd = likely(t > max_alloc) ? (t >> log2_bits) : wnd->nwnd;
}
/* Enumerate all windows. */
for (; iw < nwnd; iw++) {
wbit = iw << log2_bits;
if (!wnd->free_bits[iw]) {
if (prev_tail > b_len) {
b_pos = wbit - prev_tail;
b_len = prev_tail;
}
/* Skip full used window. */
prev_tail = 0;
wpos = 0;
continue;
}
if (unlikely(iw + 1 == nwnd)) {
if (max_alloc == wnd->nbits) {
wbits = wnd->bits_last;
} else {
size_t t = max_alloc & (wbits - 1);
if (t) {
wbits = t;
fbits_valid = false;
}
}
}
if (wnd->zone_end > wnd->zone_bit) {
ebit = wbit + wbits;
zbit = max(wnd->zone_bit, wbit);
zend = min(wnd->zone_end, ebit);
/* Here we have a window [wbit, ebit) and zone [zbit, zend). */
if (zend <= zbit) {
/* Zone does not overlap window. */
} else {
wzbit = zbit - wbit;
wzend = zend - wbit;
/* Zone overlaps window. */
if (wnd->free_bits[iw] == wzend - wzbit) {
prev_tail = 0;
wpos = 0;
continue;
}
/* Scan two ranges window: [wbit, zbit) and [zend, ebit). */
bh = wnd_map(wnd, iw);
if (IS_ERR(bh)) {
/* TODO: Error */
prev_tail = 0;
wpos = 0;
continue;
}
/* Scan range [wbit, zbit). */
if (wpos < wzbit) {
/* Scan range [wpos, zbit). */
fnd = wnd_scan(bh->b_data, wbit, wpos,
wzbit, to_alloc,
&prev_tail, &b_pos,
&b_len);
if (fnd != MINUS_ONE_T) {
put_bh(bh);
goto found;
}
}
prev_tail = 0;
/* Scan range [zend, ebit). */
if (wzend < wbits) {
fnd = wnd_scan(bh->b_data, wbit,
max(wzend, wpos), wbits,
to_alloc, &prev_tail,
&b_pos, &b_len);
if (fnd != MINUS_ONE_T) {
put_bh(bh);
goto found;
}
}
wpos = 0;
put_bh(bh);
continue;
}
}
/* Current window does not overlap zone. */
if (!wpos && fbits_valid && wnd->free_bits[iw] == wbits) {
/* Window is empty. */
if (prev_tail + wbits >= to_alloc) {
fnd = wbit + wpos - prev_tail;
goto found;
}
/* Increase 'prev_tail' and process next window. */
prev_tail += wbits;
wpos = 0;
continue;
}
/* Read window. */
bh = wnd_map(wnd, iw);
if (IS_ERR(bh)) {
// TODO: Error.
prev_tail = 0;
wpos = 0;
continue;
}
/* Scan range [wpos, eBits). */
fnd = wnd_scan(bh->b_data, wbit, wpos, wbits, to_alloc,
&prev_tail, &b_pos, &b_len);
put_bh(bh);
if (fnd != MINUS_ONE_T)
goto found;
}
if (b_len < prev_tail) {
/* The last fragment. */
b_len = prev_tail;
b_pos = max_alloc - prev_tail;
}
if (hint) {
/*
* We have scanned range [hint max_alloc).
* Prepare to scan range [0 hint + to_alloc).
*/
size_t nextmax = hint + to_alloc;
if (likely(nextmax >= hint) && nextmax < max_alloc)
max_alloc = nextmax;
hint = 0;
goto Again;
}
if (!b_len)
goto no_space;
wnd->extent_max = b_len;
if (flags & BITMAP_FIND_FULL)
goto no_space;
fnd = b_pos;
to_alloc = b_len;
found:
if (flags & BITMAP_FIND_MARK_AS_USED) {
/* TODO: Optimize remove extent (pass 'e'?). */
if (wnd_set_used(wnd, fnd, to_alloc))
goto no_space;
} else if (wnd->extent_max != MINUS_ONE_T &&
to_alloc > wnd->extent_max) {
wnd->extent_max = to_alloc;
}
*allocated = fnd;
return to_alloc;
no_space:
return 0;
}
/*
* wnd_extend - Extend bitmap ($MFT bitmap).
*/
int wnd_extend(struct wnd_bitmap *wnd, size_t new_bits)
{
int err;
struct super_block *sb = wnd->sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
u32 blocksize = sb->s_blocksize;
u32 wbits = blocksize * 8;
u32 b0, new_last;
size_t bits, iw, new_wnd;
size_t old_bits = wnd->nbits;
u16 *new_free;
if (new_bits <= old_bits)
return -EINVAL;
/* Align to 8 byte boundary. */
new_wnd = bytes_to_block(sb, bitmap_size(new_bits));
new_last = new_bits & (wbits - 1);
if (!new_last)
new_last = wbits;
if (new_wnd != wnd->nwnd) {
new_free = kmalloc_array(new_wnd, sizeof(u16), GFP_NOFS);
if (!new_free)
return -ENOMEM;
memcpy(new_free, wnd->free_bits, wnd->nwnd * sizeof(short));
memset(new_free + wnd->nwnd, 0,
(new_wnd - wnd->nwnd) * sizeof(short));
kfree(wnd->free_bits);
wnd->free_bits = new_free;
}
/* Zero bits [old_bits,new_bits). */
bits = new_bits - old_bits;
b0 = old_bits & (wbits - 1);
for (iw = old_bits >> (sb->s_blocksize_bits + 3); bits; iw += 1) {
u32 op;
size_t frb;
u64 vbo, lbo, bytes;
struct buffer_head *bh;
if (iw + 1 == new_wnd)
wbits = new_last;
op = b0 + bits > wbits ? wbits - b0 : bits;
vbo = (u64)iw * blocksize;
err = ntfs_vbo_to_lbo(sbi, &wnd->run, vbo, &lbo, &bytes);
if (err)
break;
bh = ntfs_bread(sb, lbo >> sb->s_blocksize_bits);
if (!bh)
return -EIO;
lock_buffer(bh);
ntfs_bitmap_clear_le(bh->b_data, b0, blocksize * 8 - b0);
frb = wbits - ntfs_bitmap_weight_le(bh->b_data, wbits);
wnd->total_zeroes += frb - wnd->free_bits[iw];
wnd->free_bits[iw] = frb;
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
/* err = sync_dirty_buffer(bh); */
b0 = 0;
bits -= op;
}
wnd->nbits = new_bits;
wnd->nwnd = new_wnd;
wnd->bits_last = new_last;
wnd_add_free_ext(wnd, old_bits, new_bits - old_bits, false);
return 0;
}
void wnd_zone_set(struct wnd_bitmap *wnd, size_t lcn, size_t len)
{
size_t zlen = wnd->zone_end - wnd->zone_bit;
if (zlen)
wnd_add_free_ext(wnd, wnd->zone_bit, zlen, false);
if (!RB_EMPTY_ROOT(&wnd->start_tree) && len)
wnd_remove_free_ext(wnd, lcn, len);
wnd->zone_bit = lcn;
wnd->zone_end = lcn + len;
}
int ntfs_trim_fs(struct ntfs_sb_info *sbi, struct fstrim_range *range)
{
int err = 0;
struct super_block *sb = sbi->sb;
struct wnd_bitmap *wnd = &sbi->used.bitmap;
u32 wbits = 8 * sb->s_blocksize;
CLST len = 0, lcn = 0, done = 0;
CLST minlen = bytes_to_cluster(sbi, range->minlen);
CLST lcn_from = bytes_to_cluster(sbi, range->start);
size_t iw = lcn_from >> (sb->s_blocksize_bits + 3);
u32 wbit = lcn_from & (wbits - 1);
CLST lcn_to;
if (!minlen)
minlen = 1;
if (range->len == (u64)-1)
lcn_to = wnd->nbits;
else
lcn_to = bytes_to_cluster(sbi, range->start + range->len);
down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
for (; iw < wnd->nwnd; iw++, wbit = 0) {
CLST lcn_wnd = iw * wbits;
struct buffer_head *bh;
if (lcn_wnd > lcn_to)
break;
if (!wnd->free_bits[iw])
continue;
if (iw + 1 == wnd->nwnd)
wbits = wnd->bits_last;
if (lcn_wnd + wbits > lcn_to)
wbits = lcn_to - lcn_wnd;
bh = wnd_map(wnd, iw);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
break;
}
for (; wbit < wbits; wbit++) {
if (!test_bit_le(wbit, bh->b_data)) {
if (!len)
lcn = lcn_wnd + wbit;
len += 1;
continue;
}
if (len >= minlen) {
err = ntfs_discard(sbi, lcn, len);
if (err)
goto out;
done += len;
}
len = 0;
}
put_bh(bh);
}
/* Process the last fragment. */
if (len >= minlen) {
err = ntfs_discard(sbi, lcn, len);
if (err)
goto out;
done += len;
}
out:
range->len = (u64)done << sbi->cluster_bits;
up_read(&wnd->rw_lock);
return err;
}
#if BITS_PER_LONG == 64
typedef __le64 bitmap_ulong;
#define cpu_to_ul(x) cpu_to_le64(x)
#define ul_to_cpu(x) le64_to_cpu(x)
#else
typedef __le32 bitmap_ulong;
#define cpu_to_ul(x) cpu_to_le32(x)
#define ul_to_cpu(x) le32_to_cpu(x)
#endif
void ntfs_bitmap_set_le(void *map, unsigned int start, int len)
{
bitmap_ulong *p = (bitmap_ulong *)map + BIT_WORD(start);
const unsigned int size = start + len;
int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
bitmap_ulong mask_to_set = cpu_to_ul(BITMAP_FIRST_WORD_MASK(start));
while (len - bits_to_set >= 0) {
*p |= mask_to_set;
len -= bits_to_set;
bits_to_set = BITS_PER_LONG;
mask_to_set = cpu_to_ul(~0UL);
p++;
}
if (len) {
mask_to_set &= cpu_to_ul(BITMAP_LAST_WORD_MASK(size));
*p |= mask_to_set;
}
}
void ntfs_bitmap_clear_le(void *map, unsigned int start, int len)
{
bitmap_ulong *p = (bitmap_ulong *)map + BIT_WORD(start);
const unsigned int size = start + len;
int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
bitmap_ulong mask_to_clear = cpu_to_ul(BITMAP_FIRST_WORD_MASK(start));
while (len - bits_to_clear >= 0) {
*p &= ~mask_to_clear;
len -= bits_to_clear;
bits_to_clear = BITS_PER_LONG;
mask_to_clear = cpu_to_ul(~0UL);
p++;
}
if (len) {
mask_to_clear &= cpu_to_ul(BITMAP_LAST_WORD_MASK(size));
*p &= ~mask_to_clear;
}
}
unsigned int ntfs_bitmap_weight_le(const void *bitmap, int bits)
{
const ulong *bmp = bitmap;
unsigned int k, lim = bits / BITS_PER_LONG;
unsigned int w = 0;
for (k = 0; k < lim; k++)
w += hweight_long(bmp[k]);
if (bits % BITS_PER_LONG) {
w += hweight_long(ul_to_cpu(((bitmap_ulong *)bitmap)[k]) &
BITMAP_LAST_WORD_MASK(bits));
}
return w;
}
| linux-master | fs/ntfs3/bitmap.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/blkdev.h>
#include <linux/fs.h>
#include <linux/random.h>
#include <linux/slab.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* LOG FILE structs
*/
// clang-format off
#define MaxLogFileSize 0x100000000ull
#define DefaultLogPageSize 4096
#define MinLogRecordPages 0x30
struct RESTART_HDR {
struct NTFS_RECORD_HEADER rhdr; // 'RSTR'
__le32 sys_page_size; // 0x10: Page size of the system which initialized the log.
__le32 page_size; // 0x14: Log page size used for this log file.
__le16 ra_off; // 0x18:
__le16 minor_ver; // 0x1A:
__le16 major_ver; // 0x1C:
__le16 fixups[];
};
#define LFS_NO_CLIENT 0xffff
#define LFS_NO_CLIENT_LE cpu_to_le16(0xffff)
struct CLIENT_REC {
__le64 oldest_lsn;
__le64 restart_lsn; // 0x08:
__le16 prev_client; // 0x10:
__le16 next_client; // 0x12:
__le16 seq_num; // 0x14:
u8 align[6]; // 0x16:
__le32 name_bytes; // 0x1C: In bytes.
__le16 name[32]; // 0x20: Name of client.
};
static_assert(sizeof(struct CLIENT_REC) == 0x60);
/* Two copies of these will exist at the beginning of the log file */
struct RESTART_AREA {
__le64 current_lsn; // 0x00: Current logical end of log file.
__le16 log_clients; // 0x08: Maximum number of clients.
__le16 client_idx[2]; // 0x0A: Free/use index into the client record arrays.
__le16 flags; // 0x0E: See RESTART_SINGLE_PAGE_IO.
__le32 seq_num_bits; // 0x10: The number of bits in sequence number.
__le16 ra_len; // 0x14:
__le16 client_off; // 0x16:
__le64 l_size; // 0x18: Usable log file size.
__le32 last_lsn_data_len; // 0x20:
__le16 rec_hdr_len; // 0x24: Log page data offset.
__le16 data_off; // 0x26: Log page data length.
__le32 open_log_count; // 0x28:
__le32 align[5]; // 0x2C:
struct CLIENT_REC clients[]; // 0x40:
};
struct LOG_REC_HDR {
__le16 redo_op; // 0x00: NTFS_LOG_OPERATION
__le16 undo_op; // 0x02: NTFS_LOG_OPERATION
__le16 redo_off; // 0x04: Offset to Redo record.
__le16 redo_len; // 0x06: Redo length.
__le16 undo_off; // 0x08: Offset to Undo record.
__le16 undo_len; // 0x0A: Undo length.
__le16 target_attr; // 0x0C:
__le16 lcns_follow; // 0x0E:
__le16 record_off; // 0x10:
__le16 attr_off; // 0x12:
__le16 cluster_off; // 0x14:
__le16 reserved; // 0x16:
__le64 target_vcn; // 0x18:
__le64 page_lcns[]; // 0x20:
};
static_assert(sizeof(struct LOG_REC_HDR) == 0x20);
#define RESTART_ENTRY_ALLOCATED 0xFFFFFFFF
#define RESTART_ENTRY_ALLOCATED_LE cpu_to_le32(0xFFFFFFFF)
struct RESTART_TABLE {
__le16 size; // 0x00: In bytes
__le16 used; // 0x02: Entries
__le16 total; // 0x04: Entries
__le16 res[3]; // 0x06:
__le32 free_goal; // 0x0C:
__le32 first_free; // 0x10:
__le32 last_free; // 0x14:
};
static_assert(sizeof(struct RESTART_TABLE) == 0x18);
struct ATTR_NAME_ENTRY {
__le16 off; // Offset in the Open attribute Table.
__le16 name_bytes;
__le16 name[];
};
struct OPEN_ATTR_ENRTY {
__le32 next; // 0x00: RESTART_ENTRY_ALLOCATED if allocated
__le32 bytes_per_index; // 0x04:
enum ATTR_TYPE type; // 0x08:
u8 is_dirty_pages; // 0x0C:
u8 is_attr_name; // 0x0B: Faked field to manage 'ptr'
u8 name_len; // 0x0C: Faked field to manage 'ptr'
u8 res;
struct MFT_REF ref; // 0x10: File Reference of file containing attribute
__le64 open_record_lsn; // 0x18:
void *ptr; // 0x20:
};
/* 32 bit version of 'struct OPEN_ATTR_ENRTY' */
struct OPEN_ATTR_ENRTY_32 {
__le32 next; // 0x00: RESTART_ENTRY_ALLOCATED if allocated
__le32 ptr; // 0x04:
struct MFT_REF ref; // 0x08:
__le64 open_record_lsn; // 0x10:
u8 is_dirty_pages; // 0x18:
u8 is_attr_name; // 0x19:
u8 res1[2];
enum ATTR_TYPE type; // 0x1C:
u8 name_len; // 0x20: In wchar
u8 res2[3];
__le32 AttributeName; // 0x24:
__le32 bytes_per_index; // 0x28:
};
#define SIZEOF_OPENATTRIBUTEENTRY0 0x2c
// static_assert( 0x2C == sizeof(struct OPEN_ATTR_ENRTY_32) );
static_assert(sizeof(struct OPEN_ATTR_ENRTY) < SIZEOF_OPENATTRIBUTEENTRY0);
/*
* One entry exists in the Dirty Pages Table for each page which is dirty at
* the time the Restart Area is written.
*/
struct DIR_PAGE_ENTRY {
__le32 next; // 0x00: RESTART_ENTRY_ALLOCATED if allocated
__le32 target_attr; // 0x04: Index into the Open attribute Table
__le32 transfer_len; // 0x08:
__le32 lcns_follow; // 0x0C:
__le64 vcn; // 0x10: Vcn of dirty page
__le64 oldest_lsn; // 0x18:
__le64 page_lcns[]; // 0x20:
};
static_assert(sizeof(struct DIR_PAGE_ENTRY) == 0x20);
/* 32 bit version of 'struct DIR_PAGE_ENTRY' */
struct DIR_PAGE_ENTRY_32 {
__le32 next; // 0x00: RESTART_ENTRY_ALLOCATED if allocated
__le32 target_attr; // 0x04: Index into the Open attribute Table
__le32 transfer_len; // 0x08:
__le32 lcns_follow; // 0x0C:
__le32 reserved; // 0x10:
__le32 vcn_low; // 0x14: Vcn of dirty page
__le32 vcn_hi; // 0x18: Vcn of dirty page
__le32 oldest_lsn_low; // 0x1C:
__le32 oldest_lsn_hi; // 0x1C:
__le32 page_lcns_low; // 0x24:
__le32 page_lcns_hi; // 0x24:
};
static_assert(offsetof(struct DIR_PAGE_ENTRY_32, vcn_low) == 0x14);
static_assert(sizeof(struct DIR_PAGE_ENTRY_32) == 0x2c);
enum transact_state {
TransactionUninitialized = 0,
TransactionActive,
TransactionPrepared,
TransactionCommitted
};
struct TRANSACTION_ENTRY {
__le32 next; // 0x00: RESTART_ENTRY_ALLOCATED if allocated
u8 transact_state; // 0x04:
u8 reserved[3]; // 0x05:
__le64 first_lsn; // 0x08:
__le64 prev_lsn; // 0x10:
__le64 undo_next_lsn; // 0x18:
__le32 undo_records; // 0x20: Number of undo log records pending abort
__le32 undo_len; // 0x24: Total undo size
};
static_assert(sizeof(struct TRANSACTION_ENTRY) == 0x28);
struct NTFS_RESTART {
__le32 major_ver; // 0x00:
__le32 minor_ver; // 0x04:
__le64 check_point_start; // 0x08:
__le64 open_attr_table_lsn; // 0x10:
__le64 attr_names_lsn; // 0x18:
__le64 dirty_pages_table_lsn; // 0x20:
__le64 transact_table_lsn; // 0x28:
__le32 open_attr_len; // 0x30: In bytes
__le32 attr_names_len; // 0x34: In bytes
__le32 dirty_pages_len; // 0x38: In bytes
__le32 transact_table_len; // 0x3C: In bytes
};
static_assert(sizeof(struct NTFS_RESTART) == 0x40);
struct NEW_ATTRIBUTE_SIZES {
__le64 alloc_size;
__le64 valid_size;
__le64 data_size;
__le64 total_size;
};
struct BITMAP_RANGE {
__le32 bitmap_off;
__le32 bits;
};
struct LCN_RANGE {
__le64 lcn;
__le64 len;
};
/* The following type defines the different log record types. */
#define LfsClientRecord cpu_to_le32(1)
#define LfsClientRestart cpu_to_le32(2)
/* This is used to uniquely identify a client for a particular log file. */
struct CLIENT_ID {
__le16 seq_num;
__le16 client_idx;
};
/* This is the header that begins every Log Record in the log file. */
struct LFS_RECORD_HDR {
__le64 this_lsn; // 0x00:
__le64 client_prev_lsn; // 0x08:
__le64 client_undo_next_lsn; // 0x10:
__le32 client_data_len; // 0x18:
struct CLIENT_ID client; // 0x1C: Owner of this log record.
__le32 record_type; // 0x20: LfsClientRecord or LfsClientRestart.
__le32 transact_id; // 0x24:
__le16 flags; // 0x28: LOG_RECORD_MULTI_PAGE
u8 align[6]; // 0x2A:
};
#define LOG_RECORD_MULTI_PAGE cpu_to_le16(1)
static_assert(sizeof(struct LFS_RECORD_HDR) == 0x30);
struct LFS_RECORD {
__le16 next_record_off; // 0x00: Offset of the free space in the page,
u8 align[6]; // 0x02:
__le64 last_end_lsn; // 0x08: lsn for the last log record which ends on the page,
};
static_assert(sizeof(struct LFS_RECORD) == 0x10);
struct RECORD_PAGE_HDR {
struct NTFS_RECORD_HEADER rhdr; // 'RCRD'
__le32 rflags; // 0x10: See LOG_PAGE_LOG_RECORD_END
__le16 page_count; // 0x14:
__le16 page_pos; // 0x16:
struct LFS_RECORD record_hdr; // 0x18:
__le16 fixups[10]; // 0x28:
__le32 file_off; // 0x3c: Used when major version >= 2
};
// clang-format on
// Page contains the end of a log record.
#define LOG_PAGE_LOG_RECORD_END cpu_to_le32(0x00000001)
static inline bool is_log_record_end(const struct RECORD_PAGE_HDR *hdr)
{
return hdr->rflags & LOG_PAGE_LOG_RECORD_END;
}
static_assert(offsetof(struct RECORD_PAGE_HDR, file_off) == 0x3c);
/*
* END of NTFS LOG structures
*/
/* Define some tuning parameters to keep the restart tables a reasonable size. */
#define INITIAL_NUMBER_TRANSACTIONS 5
enum NTFS_LOG_OPERATION {
Noop = 0x00,
CompensationLogRecord = 0x01,
InitializeFileRecordSegment = 0x02,
DeallocateFileRecordSegment = 0x03,
WriteEndOfFileRecordSegment = 0x04,
CreateAttribute = 0x05,
DeleteAttribute = 0x06,
UpdateResidentValue = 0x07,
UpdateNonresidentValue = 0x08,
UpdateMappingPairs = 0x09,
DeleteDirtyClusters = 0x0A,
SetNewAttributeSizes = 0x0B,
AddIndexEntryRoot = 0x0C,
DeleteIndexEntryRoot = 0x0D,
AddIndexEntryAllocation = 0x0E,
DeleteIndexEntryAllocation = 0x0F,
WriteEndOfIndexBuffer = 0x10,
SetIndexEntryVcnRoot = 0x11,
SetIndexEntryVcnAllocation = 0x12,
UpdateFileNameRoot = 0x13,
UpdateFileNameAllocation = 0x14,
SetBitsInNonresidentBitMap = 0x15,
ClearBitsInNonresidentBitMap = 0x16,
HotFix = 0x17,
EndTopLevelAction = 0x18,
PrepareTransaction = 0x19,
CommitTransaction = 0x1A,
ForgetTransaction = 0x1B,
OpenNonresidentAttribute = 0x1C,
OpenAttributeTableDump = 0x1D,
AttributeNamesDump = 0x1E,
DirtyPageTableDump = 0x1F,
TransactionTableDump = 0x20,
UpdateRecordDataRoot = 0x21,
UpdateRecordDataAllocation = 0x22,
UpdateRelativeDataInIndex =
0x23, // NtOfsRestartUpdateRelativeDataInIndex
UpdateRelativeDataInIndex2 = 0x24,
ZeroEndOfFileRecord = 0x25,
};
/*
* Array for log records which require a target attribute.
* A true indicates that the corresponding restart operation
* requires a target attribute.
*/
static const u8 AttributeRequired[] = {
0xFC, 0xFB, 0xFF, 0x10, 0x06,
};
static inline bool is_target_required(u16 op)
{
bool ret = op <= UpdateRecordDataAllocation &&
(AttributeRequired[op >> 3] >> (op & 7) & 1);
return ret;
}
static inline bool can_skip_action(enum NTFS_LOG_OPERATION op)
{
switch (op) {
case Noop:
case DeleteDirtyClusters:
case HotFix:
case EndTopLevelAction:
case PrepareTransaction:
case CommitTransaction:
case ForgetTransaction:
case CompensationLogRecord:
case OpenNonresidentAttribute:
case OpenAttributeTableDump:
case AttributeNamesDump:
case DirtyPageTableDump:
case TransactionTableDump:
return true;
default:
return false;
}
}
enum { lcb_ctx_undo_next, lcb_ctx_prev, lcb_ctx_next };
/* Bytes per restart table. */
static inline u32 bytes_per_rt(const struct RESTART_TABLE *rt)
{
return le16_to_cpu(rt->used) * le16_to_cpu(rt->size) +
sizeof(struct RESTART_TABLE);
}
/* Log record length. */
static inline u32 lrh_length(const struct LOG_REC_HDR *lr)
{
u16 t16 = le16_to_cpu(lr->lcns_follow);
return struct_size(lr, page_lcns, max_t(u16, 1, t16));
}
struct lcb {
struct LFS_RECORD_HDR *lrh; // Log record header of the current lsn.
struct LOG_REC_HDR *log_rec;
u32 ctx_mode; // lcb_ctx_undo_next/lcb_ctx_prev/lcb_ctx_next
struct CLIENT_ID client;
bool alloc; // If true the we should deallocate 'log_rec'.
};
static void lcb_put(struct lcb *lcb)
{
if (lcb->alloc)
kfree(lcb->log_rec);
kfree(lcb->lrh);
kfree(lcb);
}
/* Find the oldest lsn from active clients. */
static inline void oldest_client_lsn(const struct CLIENT_REC *ca,
__le16 next_client, u64 *oldest_lsn)
{
while (next_client != LFS_NO_CLIENT_LE) {
const struct CLIENT_REC *cr = ca + le16_to_cpu(next_client);
u64 lsn = le64_to_cpu(cr->oldest_lsn);
/* Ignore this block if it's oldest lsn is 0. */
if (lsn && lsn < *oldest_lsn)
*oldest_lsn = lsn;
next_client = cr->next_client;
}
}
static inline bool is_rst_page_hdr_valid(u32 file_off,
const struct RESTART_HDR *rhdr)
{
u32 sys_page = le32_to_cpu(rhdr->sys_page_size);
u32 page_size = le32_to_cpu(rhdr->page_size);
u32 end_usa;
u16 ro;
if (sys_page < SECTOR_SIZE || page_size < SECTOR_SIZE ||
sys_page & (sys_page - 1) || page_size & (page_size - 1)) {
return false;
}
/* Check that if the file offset isn't 0, it is the system page size. */
if (file_off && file_off != sys_page)
return false;
/* Check support version 1.1+. */
if (le16_to_cpu(rhdr->major_ver) <= 1 && !rhdr->minor_ver)
return false;
if (le16_to_cpu(rhdr->major_ver) > 2)
return false;
ro = le16_to_cpu(rhdr->ra_off);
if (!IS_ALIGNED(ro, 8) || ro > sys_page)
return false;
end_usa = ((sys_page >> SECTOR_SHIFT) + 1) * sizeof(short);
end_usa += le16_to_cpu(rhdr->rhdr.fix_off);
if (ro < end_usa)
return false;
return true;
}
static inline bool is_rst_area_valid(const struct RESTART_HDR *rhdr)
{
const struct RESTART_AREA *ra;
u16 cl, fl, ul;
u32 off, l_size, file_dat_bits, file_size_round;
u16 ro = le16_to_cpu(rhdr->ra_off);
u32 sys_page = le32_to_cpu(rhdr->sys_page_size);
if (ro + offsetof(struct RESTART_AREA, l_size) >
SECTOR_SIZE - sizeof(short))
return false;
ra = Add2Ptr(rhdr, ro);
cl = le16_to_cpu(ra->log_clients);
if (cl > 1)
return false;
off = le16_to_cpu(ra->client_off);
if (!IS_ALIGNED(off, 8) || ro + off > SECTOR_SIZE - sizeof(short))
return false;
off += cl * sizeof(struct CLIENT_REC);
if (off > sys_page)
return false;
/*
* Check the restart length field and whether the entire
* restart area is contained that length.
*/
if (le16_to_cpu(rhdr->ra_off) + le16_to_cpu(ra->ra_len) > sys_page ||
off > le16_to_cpu(ra->ra_len)) {
return false;
}
/*
* As a final check make sure that the use list and the free list
* are either empty or point to a valid client.
*/
fl = le16_to_cpu(ra->client_idx[0]);
ul = le16_to_cpu(ra->client_idx[1]);
if ((fl != LFS_NO_CLIENT && fl >= cl) ||
(ul != LFS_NO_CLIENT && ul >= cl))
return false;
/* Make sure the sequence number bits match the log file size. */
l_size = le64_to_cpu(ra->l_size);
file_dat_bits = sizeof(u64) * 8 - le32_to_cpu(ra->seq_num_bits);
file_size_round = 1u << (file_dat_bits + 3);
if (file_size_round != l_size &&
(file_size_round < l_size || (file_size_round / 2) > l_size)) {
return false;
}
/* The log page data offset and record header length must be quad-aligned. */
if (!IS_ALIGNED(le16_to_cpu(ra->data_off), 8) ||
!IS_ALIGNED(le16_to_cpu(ra->rec_hdr_len), 8))
return false;
return true;
}
static inline bool is_client_area_valid(const struct RESTART_HDR *rhdr,
bool usa_error)
{
u16 ro = le16_to_cpu(rhdr->ra_off);
const struct RESTART_AREA *ra = Add2Ptr(rhdr, ro);
u16 ra_len = le16_to_cpu(ra->ra_len);
const struct CLIENT_REC *ca;
u32 i;
if (usa_error && ra_len + ro > SECTOR_SIZE - sizeof(short))
return false;
/* Find the start of the client array. */
ca = Add2Ptr(ra, le16_to_cpu(ra->client_off));
/*
* Start with the free list.
* Check that all the clients are valid and that there isn't a cycle.
* Do the in-use list on the second pass.
*/
for (i = 0; i < 2; i++) {
u16 client_idx = le16_to_cpu(ra->client_idx[i]);
bool first_client = true;
u16 clients = le16_to_cpu(ra->log_clients);
while (client_idx != LFS_NO_CLIENT) {
const struct CLIENT_REC *cr;
if (!clients ||
client_idx >= le16_to_cpu(ra->log_clients))
return false;
clients -= 1;
cr = ca + client_idx;
client_idx = le16_to_cpu(cr->next_client);
if (first_client) {
first_client = false;
if (cr->prev_client != LFS_NO_CLIENT_LE)
return false;
}
}
}
return true;
}
/*
* remove_client
*
* Remove a client record from a client record list an restart area.
*/
static inline void remove_client(struct CLIENT_REC *ca,
const struct CLIENT_REC *cr, __le16 *head)
{
if (cr->prev_client == LFS_NO_CLIENT_LE)
*head = cr->next_client;
else
ca[le16_to_cpu(cr->prev_client)].next_client = cr->next_client;
if (cr->next_client != LFS_NO_CLIENT_LE)
ca[le16_to_cpu(cr->next_client)].prev_client = cr->prev_client;
}
/*
* add_client - Add a client record to the start of a list.
*/
static inline void add_client(struct CLIENT_REC *ca, u16 index, __le16 *head)
{
struct CLIENT_REC *cr = ca + index;
cr->prev_client = LFS_NO_CLIENT_LE;
cr->next_client = *head;
if (*head != LFS_NO_CLIENT_LE)
ca[le16_to_cpu(*head)].prev_client = cpu_to_le16(index);
*head = cpu_to_le16(index);
}
static inline void *enum_rstbl(struct RESTART_TABLE *t, void *c)
{
__le32 *e;
u32 bprt;
u16 rsize = t ? le16_to_cpu(t->size) : 0;
if (!c) {
if (!t || !t->total)
return NULL;
e = Add2Ptr(t, sizeof(struct RESTART_TABLE));
} else {
e = Add2Ptr(c, rsize);
}
/* Loop until we hit the first one allocated, or the end of the list. */
for (bprt = bytes_per_rt(t); PtrOffset(t, e) < bprt;
e = Add2Ptr(e, rsize)) {
if (*e == RESTART_ENTRY_ALLOCATED_LE)
return e;
}
return NULL;
}
/*
* find_dp - Search for a @vcn in Dirty Page Table.
*/
static inline struct DIR_PAGE_ENTRY *find_dp(struct RESTART_TABLE *dptbl,
u32 target_attr, u64 vcn)
{
__le32 ta = cpu_to_le32(target_attr);
struct DIR_PAGE_ENTRY *dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
u64 dp_vcn = le64_to_cpu(dp->vcn);
if (dp->target_attr == ta && vcn >= dp_vcn &&
vcn < dp_vcn + le32_to_cpu(dp->lcns_follow)) {
return dp;
}
}
return NULL;
}
static inline u32 norm_file_page(u32 page_size, u32 *l_size, bool use_default)
{
if (use_default)
page_size = DefaultLogPageSize;
/* Round the file size down to a system page boundary. */
*l_size &= ~(page_size - 1);
/* File should contain at least 2 restart pages and MinLogRecordPages pages. */
if (*l_size < (MinLogRecordPages + 2) * page_size)
return 0;
return page_size;
}
static bool check_log_rec(const struct LOG_REC_HDR *lr, u32 bytes, u32 tr,
u32 bytes_per_attr_entry)
{
u16 t16;
if (bytes < sizeof(struct LOG_REC_HDR))
return false;
if (!tr)
return false;
if ((tr - sizeof(struct RESTART_TABLE)) %
sizeof(struct TRANSACTION_ENTRY))
return false;
if (le16_to_cpu(lr->redo_off) & 7)
return false;
if (le16_to_cpu(lr->undo_off) & 7)
return false;
if (lr->target_attr)
goto check_lcns;
if (is_target_required(le16_to_cpu(lr->redo_op)))
return false;
if (is_target_required(le16_to_cpu(lr->undo_op)))
return false;
check_lcns:
if (!lr->lcns_follow)
goto check_length;
t16 = le16_to_cpu(lr->target_attr);
if ((t16 - sizeof(struct RESTART_TABLE)) % bytes_per_attr_entry)
return false;
check_length:
if (bytes < lrh_length(lr))
return false;
return true;
}
static bool check_rstbl(const struct RESTART_TABLE *rt, size_t bytes)
{
u32 ts;
u32 i, off;
u16 rsize = le16_to_cpu(rt->size);
u16 ne = le16_to_cpu(rt->used);
u32 ff = le32_to_cpu(rt->first_free);
u32 lf = le32_to_cpu(rt->last_free);
ts = rsize * ne + sizeof(struct RESTART_TABLE);
if (!rsize || rsize > bytes ||
rsize + sizeof(struct RESTART_TABLE) > bytes || bytes < ts ||
le16_to_cpu(rt->total) > ne || ff > ts || lf > ts ||
(ff && ff < sizeof(struct RESTART_TABLE)) ||
(lf && lf < sizeof(struct RESTART_TABLE))) {
return false;
}
/*
* Verify each entry is either allocated or points
* to a valid offset the table.
*/
for (i = 0; i < ne; i++) {
off = le32_to_cpu(*(__le32 *)Add2Ptr(
rt, i * rsize + sizeof(struct RESTART_TABLE)));
if (off != RESTART_ENTRY_ALLOCATED && off &&
(off < sizeof(struct RESTART_TABLE) ||
((off - sizeof(struct RESTART_TABLE)) % rsize))) {
return false;
}
}
/*
* Walk through the list headed by the first entry to make
* sure none of the entries are currently being used.
*/
for (off = ff; off;) {
if (off == RESTART_ENTRY_ALLOCATED)
return false;
off = le32_to_cpu(*(__le32 *)Add2Ptr(rt, off));
}
return true;
}
/*
* free_rsttbl_idx - Free a previously allocated index a Restart Table.
*/
static inline void free_rsttbl_idx(struct RESTART_TABLE *rt, u32 off)
{
__le32 *e;
u32 lf = le32_to_cpu(rt->last_free);
__le32 off_le = cpu_to_le32(off);
e = Add2Ptr(rt, off);
if (off < le32_to_cpu(rt->free_goal)) {
*e = rt->first_free;
rt->first_free = off_le;
if (!lf)
rt->last_free = off_le;
} else {
if (lf)
*(__le32 *)Add2Ptr(rt, lf) = off_le;
else
rt->first_free = off_le;
rt->last_free = off_le;
*e = 0;
}
le16_sub_cpu(&rt->total, 1);
}
static inline struct RESTART_TABLE *init_rsttbl(u16 esize, u16 used)
{
__le32 *e, *last_free;
u32 off;
u32 bytes = esize * used + sizeof(struct RESTART_TABLE);
u32 lf = sizeof(struct RESTART_TABLE) + (used - 1) * esize;
struct RESTART_TABLE *t = kzalloc(bytes, GFP_NOFS);
if (!t)
return NULL;
t->size = cpu_to_le16(esize);
t->used = cpu_to_le16(used);
t->free_goal = cpu_to_le32(~0u);
t->first_free = cpu_to_le32(sizeof(struct RESTART_TABLE));
t->last_free = cpu_to_le32(lf);
e = (__le32 *)(t + 1);
last_free = Add2Ptr(t, lf);
for (off = sizeof(struct RESTART_TABLE) + esize; e < last_free;
e = Add2Ptr(e, esize), off += esize) {
*e = cpu_to_le32(off);
}
return t;
}
static inline struct RESTART_TABLE *extend_rsttbl(struct RESTART_TABLE *tbl,
u32 add, u32 free_goal)
{
u16 esize = le16_to_cpu(tbl->size);
__le32 osize = cpu_to_le32(bytes_per_rt(tbl));
u32 used = le16_to_cpu(tbl->used);
struct RESTART_TABLE *rt;
rt = init_rsttbl(esize, used + add);
if (!rt)
return NULL;
memcpy(rt + 1, tbl + 1, esize * used);
rt->free_goal = free_goal == ~0u ?
cpu_to_le32(~0u) :
cpu_to_le32(sizeof(struct RESTART_TABLE) +
free_goal * esize);
if (tbl->first_free) {
rt->first_free = tbl->first_free;
*(__le32 *)Add2Ptr(rt, le32_to_cpu(tbl->last_free)) = osize;
} else {
rt->first_free = osize;
}
rt->total = tbl->total;
kfree(tbl);
return rt;
}
/*
* alloc_rsttbl_idx
*
* Allocate an index from within a previously initialized Restart Table.
*/
static inline void *alloc_rsttbl_idx(struct RESTART_TABLE **tbl)
{
u32 off;
__le32 *e;
struct RESTART_TABLE *t = *tbl;
if (!t->first_free) {
*tbl = t = extend_rsttbl(t, 16, ~0u);
if (!t)
return NULL;
}
off = le32_to_cpu(t->first_free);
/* Dequeue this entry and zero it. */
e = Add2Ptr(t, off);
t->first_free = *e;
memset(e, 0, le16_to_cpu(t->size));
*e = RESTART_ENTRY_ALLOCATED_LE;
/* If list is going empty, then we fix the last_free as well. */
if (!t->first_free)
t->last_free = 0;
le16_add_cpu(&t->total, 1);
return Add2Ptr(t, off);
}
/*
* alloc_rsttbl_from_idx
*
* Allocate a specific index from within a previously initialized Restart Table.
*/
static inline void *alloc_rsttbl_from_idx(struct RESTART_TABLE **tbl, u32 vbo)
{
u32 off;
__le32 *e;
struct RESTART_TABLE *rt = *tbl;
u32 bytes = bytes_per_rt(rt);
u16 esize = le16_to_cpu(rt->size);
/* If the entry is not the table, we will have to extend the table. */
if (vbo >= bytes) {
/*
* Extend the size by computing the number of entries between
* the existing size and the desired index and adding 1 to that.
*/
u32 bytes2idx = vbo - bytes;
/*
* There should always be an integral number of entries
* being added. Now extend the table.
*/
*tbl = rt = extend_rsttbl(rt, bytes2idx / esize + 1, bytes);
if (!rt)
return NULL;
}
/* See if the entry is already allocated, and just return if it is. */
e = Add2Ptr(rt, vbo);
if (*e == RESTART_ENTRY_ALLOCATED_LE)
return e;
/*
* Walk through the table, looking for the entry we're
* interested and the previous entry.
*/
off = le32_to_cpu(rt->first_free);
e = Add2Ptr(rt, off);
if (off == vbo) {
/* this is a match */
rt->first_free = *e;
goto skip_looking;
}
/*
* Need to walk through the list looking for the predecessor
* of our entry.
*/
for (;;) {
/* Remember the entry just found */
u32 last_off = off;
__le32 *last_e = e;
/* Should never run of entries. */
/* Lookup up the next entry the list. */
off = le32_to_cpu(*last_e);
e = Add2Ptr(rt, off);
/* If this is our match we are done. */
if (off == vbo) {
*last_e = *e;
/*
* If this was the last entry, we update that
* table as well.
*/
if (le32_to_cpu(rt->last_free) == off)
rt->last_free = cpu_to_le32(last_off);
break;
}
}
skip_looking:
/* If the list is now empty, we fix the last_free as well. */
if (!rt->first_free)
rt->last_free = 0;
/* Zero this entry. */
memset(e, 0, esize);
*e = RESTART_ENTRY_ALLOCATED_LE;
le16_add_cpu(&rt->total, 1);
return e;
}
#define RESTART_SINGLE_PAGE_IO cpu_to_le16(0x0001)
#define NTFSLOG_WRAPPED 0x00000001
#define NTFSLOG_MULTIPLE_PAGE_IO 0x00000002
#define NTFSLOG_NO_LAST_LSN 0x00000004
#define NTFSLOG_REUSE_TAIL 0x00000010
#define NTFSLOG_NO_OLDEST_LSN 0x00000020
/* Helper struct to work with NTFS $LogFile. */
struct ntfs_log {
struct ntfs_inode *ni;
u32 l_size;
u32 sys_page_size;
u32 sys_page_mask;
u32 page_size;
u32 page_mask; // page_size - 1
u8 page_bits;
struct RECORD_PAGE_HDR *one_page_buf;
struct RESTART_TABLE *open_attr_tbl;
u32 transaction_id;
u32 clst_per_page;
u32 first_page;
u32 next_page;
u32 ra_off;
u32 data_off;
u32 restart_size;
u32 data_size;
u16 record_header_len;
u64 seq_num;
u32 seq_num_bits;
u32 file_data_bits;
u32 seq_num_mask; /* (1 << file_data_bits) - 1 */
struct RESTART_AREA *ra; /* In-memory image of the next restart area. */
u32 ra_size; /* The usable size of the restart area. */
/*
* If true, then the in-memory restart area is to be written
* to the first position on the disk.
*/
bool init_ra;
bool set_dirty; /* True if we need to set dirty flag. */
u64 oldest_lsn;
u32 oldest_lsn_off;
u64 last_lsn;
u32 total_avail;
u32 total_avail_pages;
u32 total_undo_commit;
u32 max_current_avail;
u32 current_avail;
u32 reserved;
short major_ver;
short minor_ver;
u32 l_flags; /* See NTFSLOG_XXX */
u32 current_openlog_count; /* On-disk value for open_log_count. */
struct CLIENT_ID client_id;
u32 client_undo_commit;
};
static inline u32 lsn_to_vbo(struct ntfs_log *log, const u64 lsn)
{
u32 vbo = (lsn << log->seq_num_bits) >> (log->seq_num_bits - 3);
return vbo;
}
/* Compute the offset in the log file of the next log page. */
static inline u32 next_page_off(struct ntfs_log *log, u32 off)
{
off = (off & ~log->sys_page_mask) + log->page_size;
return off >= log->l_size ? log->first_page : off;
}
static inline u32 lsn_to_page_off(struct ntfs_log *log, u64 lsn)
{
return (((u32)lsn) << 3) & log->page_mask;
}
static inline u64 vbo_to_lsn(struct ntfs_log *log, u32 off, u64 Seq)
{
return (off >> 3) + (Seq << log->file_data_bits);
}
static inline bool is_lsn_in_file(struct ntfs_log *log, u64 lsn)
{
return lsn >= log->oldest_lsn &&
lsn <= le64_to_cpu(log->ra->current_lsn);
}
static inline u32 hdr_file_off(struct ntfs_log *log,
struct RECORD_PAGE_HDR *hdr)
{
if (log->major_ver < 2)
return le64_to_cpu(hdr->rhdr.lsn);
return le32_to_cpu(hdr->file_off);
}
static inline u64 base_lsn(struct ntfs_log *log,
const struct RECORD_PAGE_HDR *hdr, u64 lsn)
{
u64 h_lsn = le64_to_cpu(hdr->rhdr.lsn);
u64 ret = (((h_lsn >> log->file_data_bits) +
(lsn < (lsn_to_vbo(log, h_lsn) & ~log->page_mask) ? 1 : 0))
<< log->file_data_bits) +
((((is_log_record_end(hdr) &&
h_lsn <= le64_to_cpu(hdr->record_hdr.last_end_lsn)) ?
le16_to_cpu(hdr->record_hdr.next_record_off) :
log->page_size) +
lsn) >>
3);
return ret;
}
static inline bool verify_client_lsn(struct ntfs_log *log,
const struct CLIENT_REC *client, u64 lsn)
{
return lsn >= le64_to_cpu(client->oldest_lsn) &&
lsn <= le64_to_cpu(log->ra->current_lsn) && lsn;
}
struct restart_info {
u64 last_lsn;
struct RESTART_HDR *r_page;
u32 vbo;
bool chkdsk_was_run;
bool valid_page;
bool initialized;
bool restart;
};
static int read_log_page(struct ntfs_log *log, u32 vbo,
struct RECORD_PAGE_HDR **buffer, bool *usa_error)
{
int err = 0;
u32 page_idx = vbo >> log->page_bits;
u32 page_off = vbo & log->page_mask;
u32 bytes = log->page_size - page_off;
void *to_free = NULL;
u32 page_vbo = page_idx << log->page_bits;
struct RECORD_PAGE_HDR *page_buf;
struct ntfs_inode *ni = log->ni;
bool bBAAD;
if (vbo >= log->l_size)
return -EINVAL;
if (!*buffer) {
to_free = kmalloc(log->page_size, GFP_NOFS);
if (!to_free)
return -ENOMEM;
*buffer = to_free;
}
page_buf = page_off ? log->one_page_buf : *buffer;
err = ntfs_read_run_nb(ni->mi.sbi, &ni->file.run, page_vbo, page_buf,
log->page_size, NULL);
if (err)
goto out;
if (page_buf->rhdr.sign != NTFS_FFFF_SIGNATURE)
ntfs_fix_post_read(&page_buf->rhdr, PAGE_SIZE, false);
if (page_buf != *buffer)
memcpy(*buffer, Add2Ptr(page_buf, page_off), bytes);
bBAAD = page_buf->rhdr.sign == NTFS_BAAD_SIGNATURE;
if (usa_error)
*usa_error = bBAAD;
/* Check that the update sequence array for this page is valid */
/* If we don't allow errors, raise an error status */
else if (bBAAD)
err = -EINVAL;
out:
if (err && to_free) {
kfree(to_free);
*buffer = NULL;
}
return err;
}
/*
* log_read_rst
*
* It walks through 512 blocks of the file looking for a valid
* restart page header. It will stop the first time we find a
* valid page header.
*/
static int log_read_rst(struct ntfs_log *log, u32 l_size, bool first,
struct restart_info *info)
{
u32 skip, vbo;
struct RESTART_HDR *r_page = NULL;
/* Determine which restart area we are looking for. */
if (first) {
vbo = 0;
skip = 512;
} else {
vbo = 512;
skip = 0;
}
/* Loop continuously until we succeed. */
for (; vbo < l_size; vbo = 2 * vbo + skip, skip = 0) {
bool usa_error;
bool brst, bchk;
struct RESTART_AREA *ra;
/* Read a page header at the current offset. */
if (read_log_page(log, vbo, (struct RECORD_PAGE_HDR **)&r_page,
&usa_error)) {
/* Ignore any errors. */
continue;
}
/* Exit if the signature is a log record page. */
if (r_page->rhdr.sign == NTFS_RCRD_SIGNATURE) {
info->initialized = true;
break;
}
brst = r_page->rhdr.sign == NTFS_RSTR_SIGNATURE;
bchk = r_page->rhdr.sign == NTFS_CHKD_SIGNATURE;
if (!bchk && !brst) {
if (r_page->rhdr.sign != NTFS_FFFF_SIGNATURE) {
/*
* Remember if the signature does not
* indicate uninitialized file.
*/
info->initialized = true;
}
continue;
}
ra = NULL;
info->valid_page = false;
info->initialized = true;
info->vbo = vbo;
/* Let's check the restart area if this is a valid page. */
if (!is_rst_page_hdr_valid(vbo, r_page))
goto check_result;
ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));
if (!is_rst_area_valid(r_page))
goto check_result;
/*
* We have a valid restart page header and restart area.
* If chkdsk was run or we have no clients then we have
* no more checking to do.
*/
if (bchk || ra->client_idx[1] == LFS_NO_CLIENT_LE) {
info->valid_page = true;
goto check_result;
}
if (is_client_area_valid(r_page, usa_error)) {
info->valid_page = true;
ra = Add2Ptr(r_page, le16_to_cpu(r_page->ra_off));
}
check_result:
/*
* If chkdsk was run then update the caller's
* values and return.
*/
if (r_page->rhdr.sign == NTFS_CHKD_SIGNATURE) {
info->chkdsk_was_run = true;
info->last_lsn = le64_to_cpu(r_page->rhdr.lsn);
info->restart = true;
info->r_page = r_page;
return 0;
}
/*
* If we have a valid page then copy the values
* we need from it.
*/
if (info->valid_page) {
info->last_lsn = le64_to_cpu(ra->current_lsn);
info->restart = true;
info->r_page = r_page;
return 0;
}
}
kfree(r_page);
return 0;
}
/*
* Ilog_init_pg_hdr - Init @log from restart page header.
*/
static void log_init_pg_hdr(struct ntfs_log *log, u32 sys_page_size,
u32 page_size, u16 major_ver, u16 minor_ver)
{
log->sys_page_size = sys_page_size;
log->sys_page_mask = sys_page_size - 1;
log->page_size = page_size;
log->page_mask = page_size - 1;
log->page_bits = blksize_bits(page_size);
log->clst_per_page = log->page_size >> log->ni->mi.sbi->cluster_bits;
if (!log->clst_per_page)
log->clst_per_page = 1;
log->first_page = major_ver >= 2 ?
0x22 * page_size :
((sys_page_size << 1) + (page_size << 1));
log->major_ver = major_ver;
log->minor_ver = minor_ver;
}
/*
* log_create - Init @log in cases when we don't have a restart area to use.
*/
static void log_create(struct ntfs_log *log, u32 l_size, const u64 last_lsn,
u32 open_log_count, bool wrapped, bool use_multi_page)
{
log->l_size = l_size;
/* All file offsets must be quadword aligned. */
log->file_data_bits = blksize_bits(l_size) - 3;
log->seq_num_mask = (8 << log->file_data_bits) - 1;
log->seq_num_bits = sizeof(u64) * 8 - log->file_data_bits;
log->seq_num = (last_lsn >> log->file_data_bits) + 2;
log->next_page = log->first_page;
log->oldest_lsn = log->seq_num << log->file_data_bits;
log->oldest_lsn_off = 0;
log->last_lsn = log->oldest_lsn;
log->l_flags |= NTFSLOG_NO_LAST_LSN | NTFSLOG_NO_OLDEST_LSN;
/* Set the correct flags for the I/O and indicate if we have wrapped. */
if (wrapped)
log->l_flags |= NTFSLOG_WRAPPED;
if (use_multi_page)
log->l_flags |= NTFSLOG_MULTIPLE_PAGE_IO;
/* Compute the log page values. */
log->data_off = ALIGN(
offsetof(struct RECORD_PAGE_HDR, fixups) +
sizeof(short) * ((log->page_size >> SECTOR_SHIFT) + 1),
8);
log->data_size = log->page_size - log->data_off;
log->record_header_len = sizeof(struct LFS_RECORD_HDR);
/* Remember the different page sizes for reservation. */
log->reserved = log->data_size - log->record_header_len;
/* Compute the restart page values. */
log->ra_off = ALIGN(
offsetof(struct RESTART_HDR, fixups) +
sizeof(short) *
((log->sys_page_size >> SECTOR_SHIFT) + 1),
8);
log->restart_size = log->sys_page_size - log->ra_off;
log->ra_size = struct_size(log->ra, clients, 1);
log->current_openlog_count = open_log_count;
/*
* The total available log file space is the number of
* log file pages times the space available on each page.
*/
log->total_avail_pages = log->l_size - log->first_page;
log->total_avail = log->total_avail_pages >> log->page_bits;
/*
* We assume that we can't use the end of the page less than
* the file record size.
* Then we won't need to reserve more than the caller asks for.
*/
log->max_current_avail = log->total_avail * log->reserved;
log->total_avail = log->total_avail * log->data_size;
log->current_avail = log->max_current_avail;
}
/*
* log_create_ra - Fill a restart area from the values stored in @log.
*/
static struct RESTART_AREA *log_create_ra(struct ntfs_log *log)
{
struct CLIENT_REC *cr;
struct RESTART_AREA *ra = kzalloc(log->restart_size, GFP_NOFS);
if (!ra)
return NULL;
ra->current_lsn = cpu_to_le64(log->last_lsn);
ra->log_clients = cpu_to_le16(1);
ra->client_idx[1] = LFS_NO_CLIENT_LE;
if (log->l_flags & NTFSLOG_MULTIPLE_PAGE_IO)
ra->flags = RESTART_SINGLE_PAGE_IO;
ra->seq_num_bits = cpu_to_le32(log->seq_num_bits);
ra->ra_len = cpu_to_le16(log->ra_size);
ra->client_off = cpu_to_le16(offsetof(struct RESTART_AREA, clients));
ra->l_size = cpu_to_le64(log->l_size);
ra->rec_hdr_len = cpu_to_le16(log->record_header_len);
ra->data_off = cpu_to_le16(log->data_off);
ra->open_log_count = cpu_to_le32(log->current_openlog_count + 1);
cr = ra->clients;
cr->prev_client = LFS_NO_CLIENT_LE;
cr->next_client = LFS_NO_CLIENT_LE;
return ra;
}
static u32 final_log_off(struct ntfs_log *log, u64 lsn, u32 data_len)
{
u32 base_vbo = lsn << 3;
u32 final_log_off = (base_vbo & log->seq_num_mask) & ~log->page_mask;
u32 page_off = base_vbo & log->page_mask;
u32 tail = log->page_size - page_off;
page_off -= 1;
/* Add the length of the header. */
data_len += log->record_header_len;
/*
* If this lsn is contained this log page we are done.
* Otherwise we need to walk through several log pages.
*/
if (data_len > tail) {
data_len -= tail;
tail = log->data_size;
page_off = log->data_off - 1;
for (;;) {
final_log_off = next_page_off(log, final_log_off);
/*
* We are done if the remaining bytes
* fit on this page.
*/
if (data_len <= tail)
break;
data_len -= tail;
}
}
/*
* We add the remaining bytes to our starting position on this page
* and then add that value to the file offset of this log page.
*/
return final_log_off + data_len + page_off;
}
static int next_log_lsn(struct ntfs_log *log, const struct LFS_RECORD_HDR *rh,
u64 *lsn)
{
int err;
u64 this_lsn = le64_to_cpu(rh->this_lsn);
u32 vbo = lsn_to_vbo(log, this_lsn);
u32 end =
final_log_off(log, this_lsn, le32_to_cpu(rh->client_data_len));
u32 hdr_off = end & ~log->sys_page_mask;
u64 seq = this_lsn >> log->file_data_bits;
struct RECORD_PAGE_HDR *page = NULL;
/* Remember if we wrapped. */
if (end <= vbo)
seq += 1;
/* Log page header for this page. */
err = read_log_page(log, hdr_off, &page, NULL);
if (err)
return err;
/*
* If the lsn we were given was not the last lsn on this page,
* then the starting offset for the next lsn is on a quad word
* boundary following the last file offset for the current lsn.
* Otherwise the file offset is the start of the data on the next page.
*/
if (this_lsn == le64_to_cpu(page->rhdr.lsn)) {
/* If we wrapped, we need to increment the sequence number. */
hdr_off = next_page_off(log, hdr_off);
if (hdr_off == log->first_page)
seq += 1;
vbo = hdr_off + log->data_off;
} else {
vbo = ALIGN(end, 8);
}
/* Compute the lsn based on the file offset and the sequence count. */
*lsn = vbo_to_lsn(log, vbo, seq);
/*
* If this lsn is within the legal range for the file, we return true.
* Otherwise false indicates that there are no more lsn's.
*/
if (!is_lsn_in_file(log, *lsn))
*lsn = 0;
kfree(page);
return 0;
}
/*
* current_log_avail - Calculate the number of bytes available for log records.
*/
static u32 current_log_avail(struct ntfs_log *log)
{
u32 oldest_off, next_free_off, free_bytes;
if (log->l_flags & NTFSLOG_NO_LAST_LSN) {
/* The entire file is available. */
return log->max_current_avail;
}
/*
* If there is a last lsn the restart area then we know that we will
* have to compute the free range.
* If there is no oldest lsn then start at the first page of the file.
*/
oldest_off = (log->l_flags & NTFSLOG_NO_OLDEST_LSN) ?
log->first_page :
(log->oldest_lsn_off & ~log->sys_page_mask);
/*
* We will use the next log page offset to compute the next free page.
* If we are going to reuse this page go to the next page.
* If we are at the first page then use the end of the file.
*/
next_free_off = (log->l_flags & NTFSLOG_REUSE_TAIL) ?
log->next_page + log->page_size :
log->next_page == log->first_page ? log->l_size :
log->next_page;
/* If the two offsets are the same then there is no available space. */
if (oldest_off == next_free_off)
return 0;
/*
* If the free offset follows the oldest offset then subtract
* this range from the total available pages.
*/
free_bytes =
oldest_off < next_free_off ?
log->total_avail_pages - (next_free_off - oldest_off) :
oldest_off - next_free_off;
free_bytes >>= log->page_bits;
return free_bytes * log->reserved;
}
static bool check_subseq_log_page(struct ntfs_log *log,
const struct RECORD_PAGE_HDR *rp, u32 vbo,
u64 seq)
{
u64 lsn_seq;
const struct NTFS_RECORD_HEADER *rhdr = &rp->rhdr;
u64 lsn = le64_to_cpu(rhdr->lsn);
if (rhdr->sign == NTFS_FFFF_SIGNATURE || !rhdr->sign)
return false;
/*
* If the last lsn on the page occurs was written after the page
* that caused the original error then we have a fatal error.
*/
lsn_seq = lsn >> log->file_data_bits;
/*
* If the sequence number for the lsn the page is equal or greater
* than lsn we expect, then this is a subsequent write.
*/
return lsn_seq >= seq ||
(lsn_seq == seq - 1 && log->first_page == vbo &&
vbo != (lsn_to_vbo(log, lsn) & ~log->page_mask));
}
/*
* last_log_lsn
*
* Walks through the log pages for a file, searching for the
* last log page written to the file.
*/
static int last_log_lsn(struct ntfs_log *log)
{
int err;
bool usa_error = false;
bool replace_page = false;
bool reuse_page = log->l_flags & NTFSLOG_REUSE_TAIL;
bool wrapped_file, wrapped;
u32 page_cnt = 1, page_pos = 1;
u32 page_off = 0, page_off1 = 0, saved_off = 0;
u32 final_off, second_off, final_off_prev = 0, second_off_prev = 0;
u32 first_file_off = 0, second_file_off = 0;
u32 part_io_count = 0;
u32 tails = 0;
u32 this_off, curpage_off, nextpage_off, remain_pages;
u64 expected_seq, seq_base = 0, lsn_base = 0;
u64 best_lsn, best_lsn1, best_lsn2;
u64 lsn_cur, lsn1, lsn2;
u64 last_ok_lsn = reuse_page ? log->last_lsn : 0;
u16 cur_pos, best_page_pos;
struct RECORD_PAGE_HDR *page = NULL;
struct RECORD_PAGE_HDR *tst_page = NULL;
struct RECORD_PAGE_HDR *first_tail = NULL;
struct RECORD_PAGE_HDR *second_tail = NULL;
struct RECORD_PAGE_HDR *tail_page = NULL;
struct RECORD_PAGE_HDR *second_tail_prev = NULL;
struct RECORD_PAGE_HDR *first_tail_prev = NULL;
struct RECORD_PAGE_HDR *page_bufs = NULL;
struct RECORD_PAGE_HDR *best_page;
if (log->major_ver >= 2) {
final_off = 0x02 * log->page_size;
second_off = 0x12 * log->page_size;
// 0x10 == 0x12 - 0x2
page_bufs = kmalloc(log->page_size * 0x10, GFP_NOFS);
if (!page_bufs)
return -ENOMEM;
} else {
second_off = log->first_page - log->page_size;
final_off = second_off - log->page_size;
}
next_tail:
/* Read second tail page (at pos 3/0x12000). */
if (read_log_page(log, second_off, &second_tail, &usa_error) ||
usa_error || second_tail->rhdr.sign != NTFS_RCRD_SIGNATURE) {
kfree(second_tail);
second_tail = NULL;
second_file_off = 0;
lsn2 = 0;
} else {
second_file_off = hdr_file_off(log, second_tail);
lsn2 = le64_to_cpu(second_tail->record_hdr.last_end_lsn);
}
/* Read first tail page (at pos 2/0x2000). */
if (read_log_page(log, final_off, &first_tail, &usa_error) ||
usa_error || first_tail->rhdr.sign != NTFS_RCRD_SIGNATURE) {
kfree(first_tail);
first_tail = NULL;
first_file_off = 0;
lsn1 = 0;
} else {
first_file_off = hdr_file_off(log, first_tail);
lsn1 = le64_to_cpu(first_tail->record_hdr.last_end_lsn);
}
if (log->major_ver < 2) {
int best_page;
first_tail_prev = first_tail;
final_off_prev = first_file_off;
second_tail_prev = second_tail;
second_off_prev = second_file_off;
tails = 1;
if (!first_tail && !second_tail)
goto tail_read;
if (first_tail && second_tail)
best_page = lsn1 < lsn2 ? 1 : 0;
else if (first_tail)
best_page = 0;
else
best_page = 1;
page_off = best_page ? second_file_off : first_file_off;
seq_base = (best_page ? lsn2 : lsn1) >> log->file_data_bits;
goto tail_read;
}
best_lsn1 = first_tail ? base_lsn(log, first_tail, first_file_off) : 0;
best_lsn2 = second_tail ? base_lsn(log, second_tail, second_file_off) :
0;
if (first_tail && second_tail) {
if (best_lsn1 > best_lsn2) {
best_lsn = best_lsn1;
best_page = first_tail;
this_off = first_file_off;
} else {
best_lsn = best_lsn2;
best_page = second_tail;
this_off = second_file_off;
}
} else if (first_tail) {
best_lsn = best_lsn1;
best_page = first_tail;
this_off = first_file_off;
} else if (second_tail) {
best_lsn = best_lsn2;
best_page = second_tail;
this_off = second_file_off;
} else {
goto tail_read;
}
best_page_pos = le16_to_cpu(best_page->page_pos);
if (!tails) {
if (best_page_pos == page_pos) {
seq_base = best_lsn >> log->file_data_bits;
saved_off = page_off = le32_to_cpu(best_page->file_off);
lsn_base = best_lsn;
memmove(page_bufs, best_page, log->page_size);
page_cnt = le16_to_cpu(best_page->page_count);
if (page_cnt > 1)
page_pos += 1;
tails = 1;
}
} else if (seq_base == (best_lsn >> log->file_data_bits) &&
saved_off + log->page_size == this_off &&
lsn_base < best_lsn &&
(page_pos != page_cnt || best_page_pos == page_pos ||
best_page_pos == 1) &&
(page_pos >= page_cnt || best_page_pos == page_pos)) {
u16 bppc = le16_to_cpu(best_page->page_count);
saved_off += log->page_size;
lsn_base = best_lsn;
memmove(Add2Ptr(page_bufs, tails * log->page_size), best_page,
log->page_size);
tails += 1;
if (best_page_pos != bppc) {
page_cnt = bppc;
page_pos = best_page_pos;
if (page_cnt > 1)
page_pos += 1;
} else {
page_pos = page_cnt = 1;
}
} else {
kfree(first_tail);
kfree(second_tail);
goto tail_read;
}
kfree(first_tail_prev);
first_tail_prev = first_tail;
final_off_prev = first_file_off;
first_tail = NULL;
kfree(second_tail_prev);
second_tail_prev = second_tail;
second_off_prev = second_file_off;
second_tail = NULL;
final_off += log->page_size;
second_off += log->page_size;
if (tails < 0x10)
goto next_tail;
tail_read:
first_tail = first_tail_prev;
final_off = final_off_prev;
second_tail = second_tail_prev;
second_off = second_off_prev;
page_cnt = page_pos = 1;
curpage_off = seq_base == log->seq_num ? min(log->next_page, page_off) :
log->next_page;
wrapped_file =
curpage_off == log->first_page &&
!(log->l_flags & (NTFSLOG_NO_LAST_LSN | NTFSLOG_REUSE_TAIL));
expected_seq = wrapped_file ? (log->seq_num + 1) : log->seq_num;
nextpage_off = curpage_off;
next_page:
tail_page = NULL;
/* Read the next log page. */
err = read_log_page(log, curpage_off, &page, &usa_error);
/* Compute the next log page offset the file. */
nextpage_off = next_page_off(log, curpage_off);
wrapped = nextpage_off == log->first_page;
if (tails > 1) {
struct RECORD_PAGE_HDR *cur_page =
Add2Ptr(page_bufs, curpage_off - page_off);
if (curpage_off == saved_off) {
tail_page = cur_page;
goto use_tail_page;
}
if (page_off > curpage_off || curpage_off >= saved_off)
goto use_tail_page;
if (page_off1)
goto use_cur_page;
if (!err && !usa_error &&
page->rhdr.sign == NTFS_RCRD_SIGNATURE &&
cur_page->rhdr.lsn == page->rhdr.lsn &&
cur_page->record_hdr.next_record_off ==
page->record_hdr.next_record_off &&
((page_pos == page_cnt &&
le16_to_cpu(page->page_pos) == 1) ||
(page_pos != page_cnt &&
le16_to_cpu(page->page_pos) == page_pos + 1 &&
le16_to_cpu(page->page_count) == page_cnt))) {
cur_page = NULL;
goto use_tail_page;
}
page_off1 = page_off;
use_cur_page:
lsn_cur = le64_to_cpu(cur_page->rhdr.lsn);
if (last_ok_lsn !=
le64_to_cpu(cur_page->record_hdr.last_end_lsn) &&
((lsn_cur >> log->file_data_bits) +
((curpage_off <
(lsn_to_vbo(log, lsn_cur) & ~log->page_mask)) ?
1 :
0)) != expected_seq) {
goto check_tail;
}
if (!is_log_record_end(cur_page)) {
tail_page = NULL;
last_ok_lsn = lsn_cur;
goto next_page_1;
}
log->seq_num = expected_seq;
log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
log->last_lsn = le64_to_cpu(cur_page->record_hdr.last_end_lsn);
log->ra->current_lsn = cur_page->record_hdr.last_end_lsn;
if (log->record_header_len <=
log->page_size -
le16_to_cpu(cur_page->record_hdr.next_record_off)) {
log->l_flags |= NTFSLOG_REUSE_TAIL;
log->next_page = curpage_off;
} else {
log->l_flags &= ~NTFSLOG_REUSE_TAIL;
log->next_page = nextpage_off;
}
if (wrapped_file)
log->l_flags |= NTFSLOG_WRAPPED;
last_ok_lsn = le64_to_cpu(cur_page->record_hdr.last_end_lsn);
goto next_page_1;
}
/*
* If we are at the expected first page of a transfer check to see
* if either tail copy is at this offset.
* If this page is the last page of a transfer, check if we wrote
* a subsequent tail copy.
*/
if (page_cnt == page_pos || page_cnt == page_pos + 1) {
/*
* Check if the offset matches either the first or second
* tail copy. It is possible it will match both.
*/
if (curpage_off == final_off)
tail_page = first_tail;
/*
* If we already matched on the first page then
* check the ending lsn's.
*/
if (curpage_off == second_off) {
if (!tail_page ||
(second_tail &&
le64_to_cpu(second_tail->record_hdr.last_end_lsn) >
le64_to_cpu(first_tail->record_hdr
.last_end_lsn))) {
tail_page = second_tail;
}
}
}
use_tail_page:
if (tail_page) {
/* We have a candidate for a tail copy. */
lsn_cur = le64_to_cpu(tail_page->record_hdr.last_end_lsn);
if (last_ok_lsn < lsn_cur) {
/*
* If the sequence number is not expected,
* then don't use the tail copy.
*/
if (expected_seq != (lsn_cur >> log->file_data_bits))
tail_page = NULL;
} else if (last_ok_lsn > lsn_cur) {
/*
* If the last lsn is greater than the one on
* this page then forget this tail.
*/
tail_page = NULL;
}
}
/*
*If we have an error on the current page,
* we will break of this loop.
*/
if (err || usa_error)
goto check_tail;
/*
* Done if the last lsn on this page doesn't match the previous known
* last lsn or the sequence number is not expected.
*/
lsn_cur = le64_to_cpu(page->rhdr.lsn);
if (last_ok_lsn != lsn_cur &&
expected_seq != (lsn_cur >> log->file_data_bits)) {
goto check_tail;
}
/*
* Check that the page position and page count values are correct.
* If this is the first page of a transfer the position must be 1
* and the count will be unknown.
*/
if (page_cnt == page_pos) {
if (page->page_pos != cpu_to_le16(1) &&
(!reuse_page || page->page_pos != page->page_count)) {
/*
* If the current page is the first page we are
* looking at and we are reusing this page then
* it can be either the first or last page of a
* transfer. Otherwise it can only be the first.
*/
goto check_tail;
}
} else if (le16_to_cpu(page->page_count) != page_cnt ||
le16_to_cpu(page->page_pos) != page_pos + 1) {
/*
* The page position better be 1 more than the last page
* position and the page count better match.
*/
goto check_tail;
}
/*
* We have a valid page the file and may have a valid page
* the tail copy area.
* If the tail page was written after the page the file then
* break of the loop.
*/
if (tail_page &&
le64_to_cpu(tail_page->record_hdr.last_end_lsn) > lsn_cur) {
/* Remember if we will replace the page. */
replace_page = true;
goto check_tail;
}
tail_page = NULL;
if (is_log_record_end(page)) {
/*
* Since we have read this page we know the sequence number
* is the same as our expected value.
*/
log->seq_num = expected_seq;
log->last_lsn = le64_to_cpu(page->record_hdr.last_end_lsn);
log->ra->current_lsn = page->record_hdr.last_end_lsn;
log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
/*
* If there is room on this page for another header then
* remember we want to reuse the page.
*/
if (log->record_header_len <=
log->page_size -
le16_to_cpu(page->record_hdr.next_record_off)) {
log->l_flags |= NTFSLOG_REUSE_TAIL;
log->next_page = curpage_off;
} else {
log->l_flags &= ~NTFSLOG_REUSE_TAIL;
log->next_page = nextpage_off;
}
/* Remember if we wrapped the log file. */
if (wrapped_file)
log->l_flags |= NTFSLOG_WRAPPED;
}
/*
* Remember the last page count and position.
* Also remember the last known lsn.
*/
page_cnt = le16_to_cpu(page->page_count);
page_pos = le16_to_cpu(page->page_pos);
last_ok_lsn = le64_to_cpu(page->rhdr.lsn);
next_page_1:
if (wrapped) {
expected_seq += 1;
wrapped_file = 1;
}
curpage_off = nextpage_off;
kfree(page);
page = NULL;
reuse_page = 0;
goto next_page;
check_tail:
if (tail_page) {
log->seq_num = expected_seq;
log->last_lsn = le64_to_cpu(tail_page->record_hdr.last_end_lsn);
log->ra->current_lsn = tail_page->record_hdr.last_end_lsn;
log->l_flags &= ~NTFSLOG_NO_LAST_LSN;
if (log->page_size -
le16_to_cpu(
tail_page->record_hdr.next_record_off) >=
log->record_header_len) {
log->l_flags |= NTFSLOG_REUSE_TAIL;
log->next_page = curpage_off;
} else {
log->l_flags &= ~NTFSLOG_REUSE_TAIL;
log->next_page = nextpage_off;
}
if (wrapped)
log->l_flags |= NTFSLOG_WRAPPED;
}
/* Remember that the partial IO will start at the next page. */
second_off = nextpage_off;
/*
* If the next page is the first page of the file then update
* the sequence number for log records which begon the next page.
*/
if (wrapped)
expected_seq += 1;
/*
* If we have a tail copy or are performing single page I/O we can
* immediately look at the next page.
*/
if (replace_page || (log->ra->flags & RESTART_SINGLE_PAGE_IO)) {
page_cnt = 2;
page_pos = 1;
goto check_valid;
}
if (page_pos != page_cnt)
goto check_valid;
/*
* If the next page causes us to wrap to the beginning of the log
* file then we know which page to check next.
*/
if (wrapped) {
page_cnt = 2;
page_pos = 1;
goto check_valid;
}
cur_pos = 2;
next_test_page:
kfree(tst_page);
tst_page = NULL;
/* Walk through the file, reading log pages. */
err = read_log_page(log, nextpage_off, &tst_page, &usa_error);
/*
* If we get a USA error then assume that we correctly found
* the end of the original transfer.
*/
if (usa_error)
goto file_is_valid;
/*
* If we were able to read the page, we examine it to see if it
* is the same or different Io block.
*/
if (err)
goto next_test_page_1;
if (le16_to_cpu(tst_page->page_pos) == cur_pos &&
check_subseq_log_page(log, tst_page, nextpage_off, expected_seq)) {
page_cnt = le16_to_cpu(tst_page->page_count) + 1;
page_pos = le16_to_cpu(tst_page->page_pos);
goto check_valid;
} else {
goto file_is_valid;
}
next_test_page_1:
nextpage_off = next_page_off(log, curpage_off);
wrapped = nextpage_off == log->first_page;
if (wrapped) {
expected_seq += 1;
page_cnt = 2;
page_pos = 1;
}
cur_pos += 1;
part_io_count += 1;
if (!wrapped)
goto next_test_page;
check_valid:
/* Skip over the remaining pages this transfer. */
remain_pages = page_cnt - page_pos - 1;
part_io_count += remain_pages;
while (remain_pages--) {
nextpage_off = next_page_off(log, curpage_off);
wrapped = nextpage_off == log->first_page;
if (wrapped)
expected_seq += 1;
}
/* Call our routine to check this log page. */
kfree(tst_page);
tst_page = NULL;
err = read_log_page(log, nextpage_off, &tst_page, &usa_error);
if (!err && !usa_error &&
check_subseq_log_page(log, tst_page, nextpage_off, expected_seq)) {
err = -EINVAL;
goto out;
}
file_is_valid:
/* We have a valid file. */
if (page_off1 || tail_page) {
struct RECORD_PAGE_HDR *tmp_page;
if (sb_rdonly(log->ni->mi.sbi->sb)) {
err = -EROFS;
goto out;
}
if (page_off1) {
tmp_page = Add2Ptr(page_bufs, page_off1 - page_off);
tails -= (page_off1 - page_off) / log->page_size;
if (!tail_page)
tails -= 1;
} else {
tmp_page = tail_page;
tails = 1;
}
while (tails--) {
u64 off = hdr_file_off(log, tmp_page);
if (!page) {
page = kmalloc(log->page_size, GFP_NOFS);
if (!page)
return -ENOMEM;
}
/*
* Correct page and copy the data from this page
* into it and flush it to disk.
*/
memcpy(page, tmp_page, log->page_size);
/* Fill last flushed lsn value flush the page. */
if (log->major_ver < 2)
page->rhdr.lsn = page->record_hdr.last_end_lsn;
else
page->file_off = 0;
page->page_pos = page->page_count = cpu_to_le16(1);
ntfs_fix_pre_write(&page->rhdr, log->page_size);
err = ntfs_sb_write_run(log->ni->mi.sbi,
&log->ni->file.run, off, page,
log->page_size, 0);
if (err)
goto out;
if (part_io_count && second_off == off) {
second_off += log->page_size;
part_io_count -= 1;
}
tmp_page = Add2Ptr(tmp_page, log->page_size);
}
}
if (part_io_count) {
if (sb_rdonly(log->ni->mi.sbi->sb)) {
err = -EROFS;
goto out;
}
}
out:
kfree(second_tail);
kfree(first_tail);
kfree(page);
kfree(tst_page);
kfree(page_bufs);
return err;
}
/*
* read_log_rec_buf - Copy a log record from the file to a buffer.
*
* The log record may span several log pages and may even wrap the file.
*/
static int read_log_rec_buf(struct ntfs_log *log,
const struct LFS_RECORD_HDR *rh, void *buffer)
{
int err;
struct RECORD_PAGE_HDR *ph = NULL;
u64 lsn = le64_to_cpu(rh->this_lsn);
u32 vbo = lsn_to_vbo(log, lsn) & ~log->page_mask;
u32 off = lsn_to_page_off(log, lsn) + log->record_header_len;
u32 data_len = le32_to_cpu(rh->client_data_len);
/*
* While there are more bytes to transfer,
* we continue to attempt to perform the read.
*/
for (;;) {
bool usa_error;
u32 tail = log->page_size - off;
if (tail >= data_len)
tail = data_len;
data_len -= tail;
err = read_log_page(log, vbo, &ph, &usa_error);
if (err)
goto out;
/*
* The last lsn on this page better be greater or equal
* to the lsn we are copying.
*/
if (lsn > le64_to_cpu(ph->rhdr.lsn)) {
err = -EINVAL;
goto out;
}
memcpy(buffer, Add2Ptr(ph, off), tail);
/* If there are no more bytes to transfer, we exit the loop. */
if (!data_len) {
if (!is_log_record_end(ph) ||
lsn > le64_to_cpu(ph->record_hdr.last_end_lsn)) {
err = -EINVAL;
goto out;
}
break;
}
if (ph->rhdr.lsn == ph->record_hdr.last_end_lsn ||
lsn > le64_to_cpu(ph->rhdr.lsn)) {
err = -EINVAL;
goto out;
}
vbo = next_page_off(log, vbo);
off = log->data_off;
/*
* Adjust our pointer the user's buffer to transfer
* the next block to.
*/
buffer = Add2Ptr(buffer, tail);
}
out:
kfree(ph);
return err;
}
static int read_rst_area(struct ntfs_log *log, struct NTFS_RESTART **rst_,
u64 *lsn)
{
int err;
struct LFS_RECORD_HDR *rh = NULL;
const struct CLIENT_REC *cr =
Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off));
u64 lsnr, lsnc = le64_to_cpu(cr->restart_lsn);
u32 len;
struct NTFS_RESTART *rst;
*lsn = 0;
*rst_ = NULL;
/* If the client doesn't have a restart area, go ahead and exit now. */
if (!lsnc)
return 0;
err = read_log_page(log, lsn_to_vbo(log, lsnc),
(struct RECORD_PAGE_HDR **)&rh, NULL);
if (err)
return err;
rst = NULL;
lsnr = le64_to_cpu(rh->this_lsn);
if (lsnc != lsnr) {
/* If the lsn values don't match, then the disk is corrupt. */
err = -EINVAL;
goto out;
}
*lsn = lsnr;
len = le32_to_cpu(rh->client_data_len);
if (!len) {
err = 0;
goto out;
}
if (len < sizeof(struct NTFS_RESTART)) {
err = -EINVAL;
goto out;
}
rst = kmalloc(len, GFP_NOFS);
if (!rst) {
err = -ENOMEM;
goto out;
}
/* Copy the data into the 'rst' buffer. */
err = read_log_rec_buf(log, rh, rst);
if (err)
goto out;
*rst_ = rst;
rst = NULL;
out:
kfree(rh);
kfree(rst);
return err;
}
static int find_log_rec(struct ntfs_log *log, u64 lsn, struct lcb *lcb)
{
int err;
struct LFS_RECORD_HDR *rh = lcb->lrh;
u32 rec_len, len;
/* Read the record header for this lsn. */
if (!rh) {
err = read_log_page(log, lsn_to_vbo(log, lsn),
(struct RECORD_PAGE_HDR **)&rh, NULL);
lcb->lrh = rh;
if (err)
return err;
}
/*
* If the lsn the log record doesn't match the desired
* lsn then the disk is corrupt.
*/
if (lsn != le64_to_cpu(rh->this_lsn))
return -EINVAL;
len = le32_to_cpu(rh->client_data_len);
/*
* Check that the length field isn't greater than the total
* available space the log file.
*/
rec_len = len + log->record_header_len;
if (rec_len >= log->total_avail)
return -EINVAL;
/*
* If the entire log record is on this log page,
* put a pointer to the log record the context block.
*/
if (rh->flags & LOG_RECORD_MULTI_PAGE) {
void *lr = kmalloc(len, GFP_NOFS);
if (!lr)
return -ENOMEM;
lcb->log_rec = lr;
lcb->alloc = true;
/* Copy the data into the buffer returned. */
err = read_log_rec_buf(log, rh, lr);
if (err)
return err;
} else {
/* If beyond the end of the current page -> an error. */
u32 page_off = lsn_to_page_off(log, lsn);
if (page_off + len + log->record_header_len > log->page_size)
return -EINVAL;
lcb->log_rec = Add2Ptr(rh, sizeof(struct LFS_RECORD_HDR));
lcb->alloc = false;
}
return 0;
}
/*
* read_log_rec_lcb - Init the query operation.
*/
static int read_log_rec_lcb(struct ntfs_log *log, u64 lsn, u32 ctx_mode,
struct lcb **lcb_)
{
int err;
const struct CLIENT_REC *cr;
struct lcb *lcb;
switch (ctx_mode) {
case lcb_ctx_undo_next:
case lcb_ctx_prev:
case lcb_ctx_next:
break;
default:
return -EINVAL;
}
/* Check that the given lsn is the legal range for this client. */
cr = Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off));
if (!verify_client_lsn(log, cr, lsn))
return -EINVAL;
lcb = kzalloc(sizeof(struct lcb), GFP_NOFS);
if (!lcb)
return -ENOMEM;
lcb->client = log->client_id;
lcb->ctx_mode = ctx_mode;
/* Find the log record indicated by the given lsn. */
err = find_log_rec(log, lsn, lcb);
if (err)
goto out;
*lcb_ = lcb;
return 0;
out:
lcb_put(lcb);
*lcb_ = NULL;
return err;
}
/*
* find_client_next_lsn
*
* Attempt to find the next lsn to return to a client based on the context mode.
*/
static int find_client_next_lsn(struct ntfs_log *log, struct lcb *lcb, u64 *lsn)
{
int err;
u64 next_lsn;
struct LFS_RECORD_HDR *hdr;
hdr = lcb->lrh;
*lsn = 0;
if (lcb_ctx_next != lcb->ctx_mode)
goto check_undo_next;
/* Loop as long as another lsn can be found. */
for (;;) {
u64 current_lsn;
err = next_log_lsn(log, hdr, ¤t_lsn);
if (err)
goto out;
if (!current_lsn)
break;
if (hdr != lcb->lrh)
kfree(hdr);
hdr = NULL;
err = read_log_page(log, lsn_to_vbo(log, current_lsn),
(struct RECORD_PAGE_HDR **)&hdr, NULL);
if (err)
goto out;
if (memcmp(&hdr->client, &lcb->client,
sizeof(struct CLIENT_ID))) {
/*err = -EINVAL; */
} else if (LfsClientRecord == hdr->record_type) {
kfree(lcb->lrh);
lcb->lrh = hdr;
*lsn = current_lsn;
return 0;
}
}
out:
if (hdr != lcb->lrh)
kfree(hdr);
return err;
check_undo_next:
if (lcb_ctx_undo_next == lcb->ctx_mode)
next_lsn = le64_to_cpu(hdr->client_undo_next_lsn);
else if (lcb_ctx_prev == lcb->ctx_mode)
next_lsn = le64_to_cpu(hdr->client_prev_lsn);
else
return 0;
if (!next_lsn)
return 0;
if (!verify_client_lsn(
log, Add2Ptr(log->ra, le16_to_cpu(log->ra->client_off)),
next_lsn))
return 0;
hdr = NULL;
err = read_log_page(log, lsn_to_vbo(log, next_lsn),
(struct RECORD_PAGE_HDR **)&hdr, NULL);
if (err)
return err;
kfree(lcb->lrh);
lcb->lrh = hdr;
*lsn = next_lsn;
return 0;
}
static int read_next_log_rec(struct ntfs_log *log, struct lcb *lcb, u64 *lsn)
{
int err;
err = find_client_next_lsn(log, lcb, lsn);
if (err)
return err;
if (!*lsn)
return 0;
if (lcb->alloc)
kfree(lcb->log_rec);
lcb->log_rec = NULL;
lcb->alloc = false;
kfree(lcb->lrh);
lcb->lrh = NULL;
return find_log_rec(log, *lsn, lcb);
}
bool check_index_header(const struct INDEX_HDR *hdr, size_t bytes)
{
__le16 mask;
u32 min_de, de_off, used, total;
const struct NTFS_DE *e;
if (hdr_has_subnode(hdr)) {
min_de = sizeof(struct NTFS_DE) + sizeof(u64);
mask = NTFS_IE_HAS_SUBNODES;
} else {
min_de = sizeof(struct NTFS_DE);
mask = 0;
}
de_off = le32_to_cpu(hdr->de_off);
used = le32_to_cpu(hdr->used);
total = le32_to_cpu(hdr->total);
if (de_off > bytes - min_de || used > bytes || total > bytes ||
de_off + min_de > used || used > total) {
return false;
}
e = Add2Ptr(hdr, de_off);
for (;;) {
u16 esize = le16_to_cpu(e->size);
struct NTFS_DE *next = Add2Ptr(e, esize);
if (esize < min_de || PtrOffset(hdr, next) > used ||
(e->flags & NTFS_IE_HAS_SUBNODES) != mask) {
return false;
}
if (de_is_last(e))
break;
e = next;
}
return true;
}
static inline bool check_index_buffer(const struct INDEX_BUFFER *ib, u32 bytes)
{
u16 fo;
const struct NTFS_RECORD_HEADER *r = &ib->rhdr;
if (r->sign != NTFS_INDX_SIGNATURE)
return false;
fo = (SECTOR_SIZE - ((bytes >> SECTOR_SHIFT) + 1) * sizeof(short));
if (le16_to_cpu(r->fix_off) > fo)
return false;
if ((le16_to_cpu(r->fix_num) - 1) * SECTOR_SIZE != bytes)
return false;
return check_index_header(&ib->ihdr,
bytes - offsetof(struct INDEX_BUFFER, ihdr));
}
static inline bool check_index_root(const struct ATTRIB *attr,
struct ntfs_sb_info *sbi)
{
bool ret;
const struct INDEX_ROOT *root = resident_data(attr);
u8 index_bits = le32_to_cpu(root->index_block_size) >=
sbi->cluster_size ?
sbi->cluster_bits :
SECTOR_SHIFT;
u8 block_clst = root->index_block_clst;
if (le32_to_cpu(attr->res.data_size) < sizeof(struct INDEX_ROOT) ||
(root->type != ATTR_NAME && root->type != ATTR_ZERO) ||
(root->type == ATTR_NAME &&
root->rule != NTFS_COLLATION_TYPE_FILENAME) ||
(le32_to_cpu(root->index_block_size) !=
(block_clst << index_bits)) ||
(block_clst != 1 && block_clst != 2 && block_clst != 4 &&
block_clst != 8 && block_clst != 0x10 && block_clst != 0x20 &&
block_clst != 0x40 && block_clst != 0x80)) {
return false;
}
ret = check_index_header(&root->ihdr,
le32_to_cpu(attr->res.data_size) -
offsetof(struct INDEX_ROOT, ihdr));
return ret;
}
static inline bool check_attr(const struct MFT_REC *rec,
const struct ATTRIB *attr,
struct ntfs_sb_info *sbi)
{
u32 asize = le32_to_cpu(attr->size);
u32 rsize = 0;
u64 dsize, svcn, evcn;
u16 run_off;
/* Check the fixed part of the attribute record header. */
if (asize >= sbi->record_size ||
asize + PtrOffset(rec, attr) >= sbi->record_size ||
(attr->name_len &&
le16_to_cpu(attr->name_off) + attr->name_len * sizeof(short) >
asize)) {
return false;
}
/* Check the attribute fields. */
switch (attr->non_res) {
case 0:
rsize = le32_to_cpu(attr->res.data_size);
if (rsize >= asize ||
le16_to_cpu(attr->res.data_off) + rsize > asize) {
return false;
}
break;
case 1:
dsize = le64_to_cpu(attr->nres.data_size);
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
run_off = le16_to_cpu(attr->nres.run_off);
if (svcn > evcn + 1 || run_off >= asize ||
le64_to_cpu(attr->nres.valid_size) > dsize ||
dsize > le64_to_cpu(attr->nres.alloc_size)) {
return false;
}
if (run_off > asize)
return false;
if (run_unpack(NULL, sbi, 0, svcn, evcn, svcn,
Add2Ptr(attr, run_off), asize - run_off) < 0) {
return false;
}
return true;
default:
return false;
}
switch (attr->type) {
case ATTR_NAME:
if (fname_full_size(Add2Ptr(
attr, le16_to_cpu(attr->res.data_off))) > asize) {
return false;
}
break;
case ATTR_ROOT:
return check_index_root(attr, sbi);
case ATTR_STD:
if (rsize < sizeof(struct ATTR_STD_INFO5) &&
rsize != sizeof(struct ATTR_STD_INFO)) {
return false;
}
break;
case ATTR_LIST:
case ATTR_ID:
case ATTR_SECURE:
case ATTR_LABEL:
case ATTR_VOL_INFO:
case ATTR_DATA:
case ATTR_ALLOC:
case ATTR_BITMAP:
case ATTR_REPARSE:
case ATTR_EA_INFO:
case ATTR_EA:
case ATTR_PROPERTYSET:
case ATTR_LOGGED_UTILITY_STREAM:
break;
default:
return false;
}
return true;
}
static inline bool check_file_record(const struct MFT_REC *rec,
const struct MFT_REC *rec2,
struct ntfs_sb_info *sbi)
{
const struct ATTRIB *attr;
u16 fo = le16_to_cpu(rec->rhdr.fix_off);
u16 fn = le16_to_cpu(rec->rhdr.fix_num);
u16 ao = le16_to_cpu(rec->attr_off);
u32 rs = sbi->record_size;
/* Check the file record header for consistency. */
if (rec->rhdr.sign != NTFS_FILE_SIGNATURE ||
fo > (SECTOR_SIZE - ((rs >> SECTOR_SHIFT) + 1) * sizeof(short)) ||
(fn - 1) * SECTOR_SIZE != rs || ao < MFTRECORD_FIXUP_OFFSET_1 ||
ao > sbi->record_size - SIZEOF_RESIDENT || !is_rec_inuse(rec) ||
le32_to_cpu(rec->total) != rs) {
return false;
}
/* Loop to check all of the attributes. */
for (attr = Add2Ptr(rec, ao); attr->type != ATTR_END;
attr = Add2Ptr(attr, le32_to_cpu(attr->size))) {
if (check_attr(rec, attr, sbi))
continue;
return false;
}
return true;
}
static inline int check_lsn(const struct NTFS_RECORD_HEADER *hdr,
const u64 *rlsn)
{
u64 lsn;
if (!rlsn)
return true;
lsn = le64_to_cpu(hdr->lsn);
if (hdr->sign == NTFS_HOLE_SIGNATURE)
return false;
if (*rlsn > lsn)
return true;
return false;
}
static inline bool check_if_attr(const struct MFT_REC *rec,
const struct LOG_REC_HDR *lrh)
{
u16 ro = le16_to_cpu(lrh->record_off);
u16 o = le16_to_cpu(rec->attr_off);
const struct ATTRIB *attr = Add2Ptr(rec, o);
while (o < ro) {
u32 asize;
if (attr->type == ATTR_END)
break;
asize = le32_to_cpu(attr->size);
if (!asize)
break;
o += asize;
attr = Add2Ptr(attr, asize);
}
return o == ro;
}
static inline bool check_if_index_root(const struct MFT_REC *rec,
const struct LOG_REC_HDR *lrh)
{
u16 ro = le16_to_cpu(lrh->record_off);
u16 o = le16_to_cpu(rec->attr_off);
const struct ATTRIB *attr = Add2Ptr(rec, o);
while (o < ro) {
u32 asize;
if (attr->type == ATTR_END)
break;
asize = le32_to_cpu(attr->size);
if (!asize)
break;
o += asize;
attr = Add2Ptr(attr, asize);
}
return o == ro && attr->type == ATTR_ROOT;
}
static inline bool check_if_root_index(const struct ATTRIB *attr,
const struct INDEX_HDR *hdr,
const struct LOG_REC_HDR *lrh)
{
u16 ao = le16_to_cpu(lrh->attr_off);
u32 de_off = le32_to_cpu(hdr->de_off);
u32 o = PtrOffset(attr, hdr) + de_off;
const struct NTFS_DE *e = Add2Ptr(hdr, de_off);
u32 asize = le32_to_cpu(attr->size);
while (o < ao) {
u16 esize;
if (o >= asize)
break;
esize = le16_to_cpu(e->size);
if (!esize)
break;
o += esize;
e = Add2Ptr(e, esize);
}
return o == ao;
}
static inline bool check_if_alloc_index(const struct INDEX_HDR *hdr,
u32 attr_off)
{
u32 de_off = le32_to_cpu(hdr->de_off);
u32 o = offsetof(struct INDEX_BUFFER, ihdr) + de_off;
const struct NTFS_DE *e = Add2Ptr(hdr, de_off);
u32 used = le32_to_cpu(hdr->used);
while (o < attr_off) {
u16 esize;
if (de_off >= used)
break;
esize = le16_to_cpu(e->size);
if (!esize)
break;
o += esize;
de_off += esize;
e = Add2Ptr(e, esize);
}
return o == attr_off;
}
static inline void change_attr_size(struct MFT_REC *rec, struct ATTRIB *attr,
u32 nsize)
{
u32 asize = le32_to_cpu(attr->size);
int dsize = nsize - asize;
u8 *next = Add2Ptr(attr, asize);
u32 used = le32_to_cpu(rec->used);
memmove(Add2Ptr(attr, nsize), next, used - PtrOffset(rec, next));
rec->used = cpu_to_le32(used + dsize);
attr->size = cpu_to_le32(nsize);
}
struct OpenAttr {
struct ATTRIB *attr;
struct runs_tree *run1;
struct runs_tree run0;
struct ntfs_inode *ni;
// CLST rno;
};
/*
* cmp_type_and_name
*
* Return: 0 if 'attr' has the same type and name.
*/
static inline int cmp_type_and_name(const struct ATTRIB *a1,
const struct ATTRIB *a2)
{
return a1->type != a2->type || a1->name_len != a2->name_len ||
(a1->name_len && memcmp(attr_name(a1), attr_name(a2),
a1->name_len * sizeof(short)));
}
static struct OpenAttr *find_loaded_attr(struct ntfs_log *log,
const struct ATTRIB *attr, CLST rno)
{
struct OPEN_ATTR_ENRTY *oe = NULL;
while ((oe = enum_rstbl(log->open_attr_tbl, oe))) {
struct OpenAttr *op_attr;
if (ino_get(&oe->ref) != rno)
continue;
op_attr = (struct OpenAttr *)oe->ptr;
if (!cmp_type_and_name(op_attr->attr, attr))
return op_attr;
}
return NULL;
}
static struct ATTRIB *attr_create_nonres_log(struct ntfs_sb_info *sbi,
enum ATTR_TYPE type, u64 size,
const u16 *name, size_t name_len,
__le16 flags)
{
struct ATTRIB *attr;
u32 name_size = ALIGN(name_len * sizeof(short), 8);
bool is_ext = flags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED);
u32 asize = name_size +
(is_ext ? SIZEOF_NONRESIDENT_EX : SIZEOF_NONRESIDENT);
attr = kzalloc(asize, GFP_NOFS);
if (!attr)
return NULL;
attr->type = type;
attr->size = cpu_to_le32(asize);
attr->flags = flags;
attr->non_res = 1;
attr->name_len = name_len;
attr->nres.evcn = cpu_to_le64((u64)bytes_to_cluster(sbi, size) - 1);
attr->nres.alloc_size = cpu_to_le64(ntfs_up_cluster(sbi, size));
attr->nres.data_size = cpu_to_le64(size);
attr->nres.valid_size = attr->nres.data_size;
if (is_ext) {
attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
if (is_attr_compressed(attr))
attr->nres.c_unit = COMPRESSION_UNIT;
attr->nres.run_off =
cpu_to_le16(SIZEOF_NONRESIDENT_EX + name_size);
memcpy(Add2Ptr(attr, SIZEOF_NONRESIDENT_EX), name,
name_len * sizeof(short));
} else {
attr->name_off = SIZEOF_NONRESIDENT_LE;
attr->nres.run_off =
cpu_to_le16(SIZEOF_NONRESIDENT + name_size);
memcpy(Add2Ptr(attr, SIZEOF_NONRESIDENT), name,
name_len * sizeof(short));
}
return attr;
}
/*
* do_action - Common routine for the Redo and Undo Passes.
* @rlsn: If it is NULL then undo.
*/
static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,
const struct LOG_REC_HDR *lrh, u32 op, void *data,
u32 dlen, u32 rec_len, const u64 *rlsn)
{
int err = 0;
struct ntfs_sb_info *sbi = log->ni->mi.sbi;
struct inode *inode = NULL, *inode_parent;
struct mft_inode *mi = NULL, *mi2_child = NULL;
CLST rno = 0, rno_base = 0;
struct INDEX_BUFFER *ib = NULL;
struct MFT_REC *rec = NULL;
struct ATTRIB *attr = NULL, *attr2;
struct INDEX_HDR *hdr;
struct INDEX_ROOT *root;
struct NTFS_DE *e, *e1, *e2;
struct NEW_ATTRIBUTE_SIZES *new_sz;
struct ATTR_FILE_NAME *fname;
struct OpenAttr *oa, *oa2;
u32 nsize, t32, asize, used, esize, off, bits;
u16 id, id2;
u32 record_size = sbi->record_size;
u64 t64;
u16 roff = le16_to_cpu(lrh->record_off);
u16 aoff = le16_to_cpu(lrh->attr_off);
u64 lco = 0;
u64 cbo = (u64)le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;
u64 tvo = le64_to_cpu(lrh->target_vcn) << sbi->cluster_bits;
u64 vbo = cbo + tvo;
void *buffer_le = NULL;
u32 bytes = 0;
bool a_dirty = false;
u16 data_off;
oa = oe->ptr;
/* Big switch to prepare. */
switch (op) {
/* ============================================================
* Process MFT records, as described by the current log record.
* ============================================================
*/
case InitializeFileRecordSegment:
case DeallocateFileRecordSegment:
case WriteEndOfFileRecordSegment:
case CreateAttribute:
case DeleteAttribute:
case UpdateResidentValue:
case UpdateMappingPairs:
case SetNewAttributeSizes:
case AddIndexEntryRoot:
case DeleteIndexEntryRoot:
case SetIndexEntryVcnRoot:
case UpdateFileNameRoot:
case UpdateRecordDataRoot:
case ZeroEndOfFileRecord:
rno = vbo >> sbi->record_bits;
inode = ilookup(sbi->sb, rno);
if (inode) {
mi = &ntfs_i(inode)->mi;
} else if (op == InitializeFileRecordSegment) {
mi = kzalloc(sizeof(struct mft_inode), GFP_NOFS);
if (!mi)
return -ENOMEM;
err = mi_format_new(mi, sbi, rno, 0, false);
if (err)
goto out;
} else {
/* Read from disk. */
err = mi_get(sbi, rno, &mi);
if (err)
return err;
}
rec = mi->mrec;
if (op == DeallocateFileRecordSegment)
goto skip_load_parent;
if (InitializeFileRecordSegment != op) {
if (rec->rhdr.sign == NTFS_BAAD_SIGNATURE)
goto dirty_vol;
if (!check_lsn(&rec->rhdr, rlsn))
goto out;
if (!check_file_record(rec, NULL, sbi))
goto dirty_vol;
attr = Add2Ptr(rec, roff);
}
if (is_rec_base(rec) || InitializeFileRecordSegment == op) {
rno_base = rno;
goto skip_load_parent;
}
rno_base = ino_get(&rec->parent_ref);
inode_parent = ntfs_iget5(sbi->sb, &rec->parent_ref, NULL);
if (IS_ERR(inode_parent))
goto skip_load_parent;
if (is_bad_inode(inode_parent)) {
iput(inode_parent);
goto skip_load_parent;
}
if (ni_load_mi_ex(ntfs_i(inode_parent), rno, &mi2_child)) {
iput(inode_parent);
} else {
if (mi2_child->mrec != mi->mrec)
memcpy(mi2_child->mrec, mi->mrec,
sbi->record_size);
if (inode)
iput(inode);
else if (mi)
mi_put(mi);
inode = inode_parent;
mi = mi2_child;
rec = mi2_child->mrec;
attr = Add2Ptr(rec, roff);
}
skip_load_parent:
inode_parent = NULL;
break;
/*
* Process attributes, as described by the current log record.
*/
case UpdateNonresidentValue:
case AddIndexEntryAllocation:
case DeleteIndexEntryAllocation:
case WriteEndOfIndexBuffer:
case SetIndexEntryVcnAllocation:
case UpdateFileNameAllocation:
case SetBitsInNonresidentBitMap:
case ClearBitsInNonresidentBitMap:
case UpdateRecordDataAllocation:
attr = oa->attr;
bytes = UpdateNonresidentValue == op ? dlen : 0;
lco = (u64)le16_to_cpu(lrh->lcns_follow) << sbi->cluster_bits;
if (attr->type == ATTR_ALLOC) {
t32 = le32_to_cpu(oe->bytes_per_index);
if (bytes < t32)
bytes = t32;
}
if (!bytes)
bytes = lco - cbo;
bytes += roff;
if (attr->type == ATTR_ALLOC)
bytes = (bytes + 511) & ~511; // align
buffer_le = kmalloc(bytes, GFP_NOFS);
if (!buffer_le)
return -ENOMEM;
err = ntfs_read_run_nb(sbi, oa->run1, vbo, buffer_le, bytes,
NULL);
if (err)
goto out;
if (attr->type == ATTR_ALLOC && *(int *)buffer_le)
ntfs_fix_post_read(buffer_le, bytes, false);
break;
default:
WARN_ON(1);
}
/* Big switch to do operation. */
switch (op) {
case InitializeFileRecordSegment:
if (roff + dlen > record_size)
goto dirty_vol;
memcpy(Add2Ptr(rec, roff), data, dlen);
mi->dirty = true;
break;
case DeallocateFileRecordSegment:
clear_rec_inuse(rec);
le16_add_cpu(&rec->seq, 1);
mi->dirty = true;
break;
case WriteEndOfFileRecordSegment:
attr2 = (struct ATTRIB *)data;
if (!check_if_attr(rec, lrh) || roff + dlen > record_size)
goto dirty_vol;
memmove(attr, attr2, dlen);
rec->used = cpu_to_le32(ALIGN(roff + dlen, 8));
mi->dirty = true;
break;
case CreateAttribute:
attr2 = (struct ATTRIB *)data;
asize = le32_to_cpu(attr2->size);
used = le32_to_cpu(rec->used);
if (!check_if_attr(rec, lrh) || dlen < SIZEOF_RESIDENT ||
!IS_ALIGNED(asize, 8) ||
Add2Ptr(attr2, asize) > Add2Ptr(lrh, rec_len) ||
dlen > record_size - used) {
goto dirty_vol;
}
memmove(Add2Ptr(attr, asize), attr, used - roff);
memcpy(attr, attr2, asize);
rec->used = cpu_to_le32(used + asize);
id = le16_to_cpu(rec->next_attr_id);
id2 = le16_to_cpu(attr2->id);
if (id <= id2)
rec->next_attr_id = cpu_to_le16(id2 + 1);
if (is_attr_indexed(attr))
le16_add_cpu(&rec->hard_links, 1);
oa2 = find_loaded_attr(log, attr, rno_base);
if (oa2) {
void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
GFP_NOFS);
if (p2) {
// run_close(oa2->run1);
kfree(oa2->attr);
oa2->attr = p2;
}
}
mi->dirty = true;
break;
case DeleteAttribute:
asize = le32_to_cpu(attr->size);
used = le32_to_cpu(rec->used);
if (!check_if_attr(rec, lrh))
goto dirty_vol;
rec->used = cpu_to_le32(used - asize);
if (is_attr_indexed(attr))
le16_add_cpu(&rec->hard_links, -1);
memmove(attr, Add2Ptr(attr, asize), used - asize - roff);
mi->dirty = true;
break;
case UpdateResidentValue:
nsize = aoff + dlen;
if (!check_if_attr(rec, lrh))
goto dirty_vol;
asize = le32_to_cpu(attr->size);
used = le32_to_cpu(rec->used);
if (lrh->redo_len == lrh->undo_len) {
if (nsize > asize)
goto dirty_vol;
goto move_data;
}
if (nsize > asize && nsize - asize > record_size - used)
goto dirty_vol;
nsize = ALIGN(nsize, 8);
data_off = le16_to_cpu(attr->res.data_off);
if (nsize < asize) {
memmove(Add2Ptr(attr, aoff), data, dlen);
data = NULL; // To skip below memmove().
}
memmove(Add2Ptr(attr, nsize), Add2Ptr(attr, asize),
used - le16_to_cpu(lrh->record_off) - asize);
rec->used = cpu_to_le32(used + nsize - asize);
attr->size = cpu_to_le32(nsize);
attr->res.data_size = cpu_to_le32(aoff + dlen - data_off);
move_data:
if (data)
memmove(Add2Ptr(attr, aoff), data, dlen);
oa2 = find_loaded_attr(log, attr, rno_base);
if (oa2) {
void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
GFP_NOFS);
if (p2) {
// run_close(&oa2->run0);
oa2->run1 = &oa2->run0;
kfree(oa2->attr);
oa2->attr = p2;
}
}
mi->dirty = true;
break;
case UpdateMappingPairs:
nsize = aoff + dlen;
asize = le32_to_cpu(attr->size);
used = le32_to_cpu(rec->used);
if (!check_if_attr(rec, lrh) || !attr->non_res ||
aoff < le16_to_cpu(attr->nres.run_off) || aoff > asize ||
(nsize > asize && nsize - asize > record_size - used)) {
goto dirty_vol;
}
nsize = ALIGN(nsize, 8);
memmove(Add2Ptr(attr, nsize), Add2Ptr(attr, asize),
used - le16_to_cpu(lrh->record_off) - asize);
rec->used = cpu_to_le32(used + nsize - asize);
attr->size = cpu_to_le32(nsize);
memmove(Add2Ptr(attr, aoff), data, dlen);
if (run_get_highest_vcn(le64_to_cpu(attr->nres.svcn),
attr_run(attr), &t64)) {
goto dirty_vol;
}
attr->nres.evcn = cpu_to_le64(t64);
oa2 = find_loaded_attr(log, attr, rno_base);
if (oa2 && oa2->attr->non_res)
oa2->attr->nres.evcn = attr->nres.evcn;
mi->dirty = true;
break;
case SetNewAttributeSizes:
new_sz = data;
if (!check_if_attr(rec, lrh) || !attr->non_res)
goto dirty_vol;
attr->nres.alloc_size = new_sz->alloc_size;
attr->nres.data_size = new_sz->data_size;
attr->nres.valid_size = new_sz->valid_size;
if (dlen >= sizeof(struct NEW_ATTRIBUTE_SIZES))
attr->nres.total_size = new_sz->total_size;
oa2 = find_loaded_attr(log, attr, rno_base);
if (oa2) {
void *p2 = kmemdup(attr, le32_to_cpu(attr->size),
GFP_NOFS);
if (p2) {
kfree(oa2->attr);
oa2->attr = p2;
}
}
mi->dirty = true;
break;
case AddIndexEntryRoot:
e = (struct NTFS_DE *)data;
esize = le16_to_cpu(e->size);
root = resident_data(attr);
hdr = &root->ihdr;
used = le32_to_cpu(hdr->used);
if (!check_if_index_root(rec, lrh) ||
!check_if_root_index(attr, hdr, lrh) ||
Add2Ptr(data, esize) > Add2Ptr(lrh, rec_len) ||
esize > le32_to_cpu(rec->total) - le32_to_cpu(rec->used)) {
goto dirty_vol;
}
e1 = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
change_attr_size(rec, attr, le32_to_cpu(attr->size) + esize);
memmove(Add2Ptr(e1, esize), e1,
PtrOffset(e1, Add2Ptr(hdr, used)));
memmove(e1, e, esize);
le32_add_cpu(&attr->res.data_size, esize);
hdr->used = cpu_to_le32(used + esize);
le32_add_cpu(&hdr->total, esize);
mi->dirty = true;
break;
case DeleteIndexEntryRoot:
root = resident_data(attr);
hdr = &root->ihdr;
used = le32_to_cpu(hdr->used);
if (!check_if_index_root(rec, lrh) ||
!check_if_root_index(attr, hdr, lrh)) {
goto dirty_vol;
}
e1 = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
esize = le16_to_cpu(e1->size);
e2 = Add2Ptr(e1, esize);
memmove(e1, e2, PtrOffset(e2, Add2Ptr(hdr, used)));
le32_sub_cpu(&attr->res.data_size, esize);
hdr->used = cpu_to_le32(used - esize);
le32_sub_cpu(&hdr->total, esize);
change_attr_size(rec, attr, le32_to_cpu(attr->size) - esize);
mi->dirty = true;
break;
case SetIndexEntryVcnRoot:
root = resident_data(attr);
hdr = &root->ihdr;
if (!check_if_index_root(rec, lrh) ||
!check_if_root_index(attr, hdr, lrh)) {
goto dirty_vol;
}
e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
de_set_vbn_le(e, *(__le64 *)data);
mi->dirty = true;
break;
case UpdateFileNameRoot:
root = resident_data(attr);
hdr = &root->ihdr;
if (!check_if_index_root(rec, lrh) ||
!check_if_root_index(attr, hdr, lrh)) {
goto dirty_vol;
}
e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
fname = (struct ATTR_FILE_NAME *)(e + 1);
memmove(&fname->dup, data, sizeof(fname->dup)); //
mi->dirty = true;
break;
case UpdateRecordDataRoot:
root = resident_data(attr);
hdr = &root->ihdr;
if (!check_if_index_root(rec, lrh) ||
!check_if_root_index(attr, hdr, lrh)) {
goto dirty_vol;
}
e = Add2Ptr(attr, le16_to_cpu(lrh->attr_off));
memmove(Add2Ptr(e, le16_to_cpu(e->view.data_off)), data, dlen);
mi->dirty = true;
break;
case ZeroEndOfFileRecord:
if (roff + dlen > record_size)
goto dirty_vol;
memset(attr, 0, dlen);
mi->dirty = true;
break;
case UpdateNonresidentValue:
if (lco < cbo + roff + dlen)
goto dirty_vol;
memcpy(Add2Ptr(buffer_le, roff), data, dlen);
a_dirty = true;
if (attr->type == ATTR_ALLOC)
ntfs_fix_pre_write(buffer_le, bytes);
break;
case AddIndexEntryAllocation:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = data;
esize = le16_to_cpu(e->size);
e1 = Add2Ptr(ib, aoff);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
used = le32_to_cpu(hdr->used);
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff) ||
Add2Ptr(e, esize) > Add2Ptr(lrh, rec_len) ||
used + esize > le32_to_cpu(hdr->total)) {
goto dirty_vol;
}
memmove(Add2Ptr(e1, esize), e1,
PtrOffset(e1, Add2Ptr(hdr, used)));
memcpy(e1, e, esize);
hdr->used = cpu_to_le32(used + esize);
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
case DeleteIndexEntryAllocation:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = Add2Ptr(ib, aoff);
esize = le16_to_cpu(e->size);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff)) {
goto dirty_vol;
}
e1 = Add2Ptr(e, esize);
nsize = esize;
used = le32_to_cpu(hdr->used);
memmove(e, e1, PtrOffset(e1, Add2Ptr(hdr, used)));
hdr->used = cpu_to_le32(used - nsize);
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
case WriteEndOfIndexBuffer:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = Add2Ptr(ib, aoff);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff) ||
aoff + dlen > offsetof(struct INDEX_BUFFER, ihdr) +
le32_to_cpu(hdr->total)) {
goto dirty_vol;
}
hdr->used = cpu_to_le32(dlen + PtrOffset(hdr, e));
memmove(e, data, dlen);
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
case SetIndexEntryVcnAllocation:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = Add2Ptr(ib, aoff);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff)) {
goto dirty_vol;
}
de_set_vbn_le(e, *(__le64 *)data);
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
case UpdateFileNameAllocation:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = Add2Ptr(ib, aoff);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff)) {
goto dirty_vol;
}
fname = (struct ATTR_FILE_NAME *)(e + 1);
memmove(&fname->dup, data, sizeof(fname->dup));
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
case SetBitsInNonresidentBitMap:
off = le32_to_cpu(((struct BITMAP_RANGE *)data)->bitmap_off);
bits = le32_to_cpu(((struct BITMAP_RANGE *)data)->bits);
if (cbo + (off + 7) / 8 > lco ||
cbo + ((off + bits + 7) / 8) > lco) {
goto dirty_vol;
}
ntfs_bitmap_set_le(Add2Ptr(buffer_le, roff), off, bits);
a_dirty = true;
break;
case ClearBitsInNonresidentBitMap:
off = le32_to_cpu(((struct BITMAP_RANGE *)data)->bitmap_off);
bits = le32_to_cpu(((struct BITMAP_RANGE *)data)->bits);
if (cbo + (off + 7) / 8 > lco ||
cbo + ((off + bits + 7) / 8) > lco) {
goto dirty_vol;
}
ntfs_bitmap_clear_le(Add2Ptr(buffer_le, roff), off, bits);
a_dirty = true;
break;
case UpdateRecordDataAllocation:
ib = Add2Ptr(buffer_le, roff);
hdr = &ib->ihdr;
e = Add2Ptr(ib, aoff);
if (is_baad(&ib->rhdr))
goto dirty_vol;
if (!check_lsn(&ib->rhdr, rlsn))
goto out;
if (!check_index_buffer(ib, bytes) ||
!check_if_alloc_index(hdr, aoff)) {
goto dirty_vol;
}
memmove(Add2Ptr(e, le16_to_cpu(e->view.data_off)), data, dlen);
a_dirty = true;
ntfs_fix_pre_write(&ib->rhdr, bytes);
break;
default:
WARN_ON(1);
}
if (rlsn) {
__le64 t64 = cpu_to_le64(*rlsn);
if (rec)
rec->rhdr.lsn = t64;
if (ib)
ib->rhdr.lsn = t64;
}
if (mi && mi->dirty) {
err = mi_write(mi, 0);
if (err)
goto out;
}
if (a_dirty) {
attr = oa->attr;
err = ntfs_sb_write_run(sbi, oa->run1, vbo, buffer_le, bytes,
0);
if (err)
goto out;
}
out:
if (inode)
iput(inode);
else if (mi != mi2_child)
mi_put(mi);
kfree(buffer_le);
return err;
dirty_vol:
log->set_dirty = true;
goto out;
}
/*
* log_replay - Replays log and empties it.
*
* This function is called during mount operation.
* It replays log and empties it.
* Initialized is set false if logfile contains '-1'.
*/
int log_replay(struct ntfs_inode *ni, bool *initialized)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ntfs_log *log;
struct restart_info rst_info, rst_info2;
u64 rec_lsn, ra_lsn, checkpt_lsn = 0, rlsn = 0;
struct ATTR_NAME_ENTRY *attr_names = NULL;
struct ATTR_NAME_ENTRY *ane;
struct RESTART_TABLE *dptbl = NULL;
struct RESTART_TABLE *trtbl = NULL;
const struct RESTART_TABLE *rt;
struct RESTART_TABLE *oatbl = NULL;
struct inode *inode;
struct OpenAttr *oa;
struct ntfs_inode *ni_oe;
struct ATTRIB *attr = NULL;
u64 size, vcn, undo_next_lsn;
CLST rno, lcn, lcn0, len0, clen;
void *data;
struct NTFS_RESTART *rst = NULL;
struct lcb *lcb = NULL;
struct OPEN_ATTR_ENRTY *oe;
struct TRANSACTION_ENTRY *tr;
struct DIR_PAGE_ENTRY *dp;
u32 i, bytes_per_attr_entry;
u32 l_size = ni->vfs_inode.i_size;
u32 orig_file_size = l_size;
u32 page_size, vbo, tail, off, dlen;
u32 saved_len, rec_len, transact_id;
bool use_second_page;
struct RESTART_AREA *ra2, *ra = NULL;
struct CLIENT_REC *ca, *cr;
__le16 client;
struct RESTART_HDR *rh;
const struct LFS_RECORD_HDR *frh;
const struct LOG_REC_HDR *lrh;
bool is_mapped;
bool is_ro = sb_rdonly(sbi->sb);
u64 t64;
u16 t16;
u32 t32;
/* Get the size of page. NOTE: To replay we can use default page. */
#if PAGE_SIZE >= DefaultLogPageSize && PAGE_SIZE <= DefaultLogPageSize * 2
page_size = norm_file_page(PAGE_SIZE, &l_size, true);
#else
page_size = norm_file_page(PAGE_SIZE, &l_size, false);
#endif
if (!page_size)
return -EINVAL;
log = kzalloc(sizeof(struct ntfs_log), GFP_NOFS);
if (!log)
return -ENOMEM;
log->ni = ni;
log->l_size = l_size;
log->one_page_buf = kmalloc(page_size, GFP_NOFS);
if (!log->one_page_buf) {
err = -ENOMEM;
goto out;
}
log->page_size = page_size;
log->page_mask = page_size - 1;
log->page_bits = blksize_bits(page_size);
/* Look for a restart area on the disk. */
memset(&rst_info, 0, sizeof(struct restart_info));
err = log_read_rst(log, l_size, true, &rst_info);
if (err)
goto out;
/* remember 'initialized' */
*initialized = rst_info.initialized;
if (!rst_info.restart) {
if (rst_info.initialized) {
/* No restart area but the file is not initialized. */
err = -EINVAL;
goto out;
}
log_init_pg_hdr(log, page_size, page_size, 1, 1);
log_create(log, l_size, 0, get_random_u32(), false, false);
log->ra = ra;
ra = log_create_ra(log);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
log->init_ra = true;
goto process_log;
}
/*
* If the restart offset above wasn't zero then we won't
* look for a second restart.
*/
if (rst_info.vbo)
goto check_restart_area;
memset(&rst_info2, 0, sizeof(struct restart_info));
err = log_read_rst(log, l_size, false, &rst_info2);
if (err)
goto out;
/* Determine which restart area to use. */
if (!rst_info2.restart || rst_info2.last_lsn <= rst_info.last_lsn)
goto use_first_page;
use_second_page = true;
if (rst_info.chkdsk_was_run && page_size != rst_info.vbo) {
struct RECORD_PAGE_HDR *sp = NULL;
bool usa_error;
if (!read_log_page(log, page_size, &sp, &usa_error) &&
sp->rhdr.sign == NTFS_CHKD_SIGNATURE) {
use_second_page = false;
}
kfree(sp);
}
if (use_second_page) {
kfree(rst_info.r_page);
memcpy(&rst_info, &rst_info2, sizeof(struct restart_info));
rst_info2.r_page = NULL;
}
use_first_page:
kfree(rst_info2.r_page);
check_restart_area:
/*
* If the restart area is at offset 0, we want
* to write the second restart area first.
*/
log->init_ra = !!rst_info.vbo;
/* If we have a valid page then grab a pointer to the restart area. */
ra2 = rst_info.valid_page ?
Add2Ptr(rst_info.r_page,
le16_to_cpu(rst_info.r_page->ra_off)) :
NULL;
if (rst_info.chkdsk_was_run ||
(ra2 && ra2->client_idx[1] == LFS_NO_CLIENT_LE)) {
bool wrapped = false;
bool use_multi_page = false;
u32 open_log_count;
/* Do some checks based on whether we have a valid log page. */
if (!rst_info.valid_page) {
open_log_count = get_random_u32();
goto init_log_instance;
}
open_log_count = le32_to_cpu(ra2->open_log_count);
/*
* If the restart page size isn't changing then we want to
* check how much work we need to do.
*/
if (page_size != le32_to_cpu(rst_info.r_page->sys_page_size))
goto init_log_instance;
init_log_instance:
log_init_pg_hdr(log, page_size, page_size, 1, 1);
log_create(log, l_size, rst_info.last_lsn, open_log_count,
wrapped, use_multi_page);
ra = log_create_ra(log);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
/* Put the restart areas and initialize
* the log file as required.
*/
goto process_log;
}
if (!ra2) {
err = -EINVAL;
goto out;
}
/*
* If the log page or the system page sizes have changed, we can't
* use the log file. We must use the system page size instead of the
* default size if there is not a clean shutdown.
*/
t32 = le32_to_cpu(rst_info.r_page->sys_page_size);
if (page_size != t32) {
l_size = orig_file_size;
page_size =
norm_file_page(t32, &l_size, t32 == DefaultLogPageSize);
}
if (page_size != t32 ||
page_size != le32_to_cpu(rst_info.r_page->page_size)) {
err = -EINVAL;
goto out;
}
/* If the file size has shrunk then we won't mount it. */
if (l_size < le64_to_cpu(ra2->l_size)) {
err = -EINVAL;
goto out;
}
log_init_pg_hdr(log, page_size, page_size,
le16_to_cpu(rst_info.r_page->major_ver),
le16_to_cpu(rst_info.r_page->minor_ver));
log->l_size = le64_to_cpu(ra2->l_size);
log->seq_num_bits = le32_to_cpu(ra2->seq_num_bits);
log->file_data_bits = sizeof(u64) * 8 - log->seq_num_bits;
log->seq_num_mask = (8 << log->file_data_bits) - 1;
log->last_lsn = le64_to_cpu(ra2->current_lsn);
log->seq_num = log->last_lsn >> log->file_data_bits;
log->ra_off = le16_to_cpu(rst_info.r_page->ra_off);
log->restart_size = log->sys_page_size - log->ra_off;
log->record_header_len = le16_to_cpu(ra2->rec_hdr_len);
log->ra_size = le16_to_cpu(ra2->ra_len);
log->data_off = le16_to_cpu(ra2->data_off);
log->data_size = log->page_size - log->data_off;
log->reserved = log->data_size - log->record_header_len;
vbo = lsn_to_vbo(log, log->last_lsn);
if (vbo < log->first_page) {
/* This is a pseudo lsn. */
log->l_flags |= NTFSLOG_NO_LAST_LSN;
log->next_page = log->first_page;
goto find_oldest;
}
/* Find the end of this log record. */
off = final_log_off(log, log->last_lsn,
le32_to_cpu(ra2->last_lsn_data_len));
/* If we wrapped the file then increment the sequence number. */
if (off <= vbo) {
log->seq_num += 1;
log->l_flags |= NTFSLOG_WRAPPED;
}
/* Now compute the next log page to use. */
vbo &= ~log->sys_page_mask;
tail = log->page_size - (off & log->page_mask) - 1;
/*
*If we can fit another log record on the page,
* move back a page the log file.
*/
if (tail >= log->record_header_len) {
log->l_flags |= NTFSLOG_REUSE_TAIL;
log->next_page = vbo;
} else {
log->next_page = next_page_off(log, vbo);
}
find_oldest:
/*
* Find the oldest client lsn. Use the last
* flushed lsn as a starting point.
*/
log->oldest_lsn = log->last_lsn;
oldest_client_lsn(Add2Ptr(ra2, le16_to_cpu(ra2->client_off)),
ra2->client_idx[1], &log->oldest_lsn);
log->oldest_lsn_off = lsn_to_vbo(log, log->oldest_lsn);
if (log->oldest_lsn_off < log->first_page)
log->l_flags |= NTFSLOG_NO_OLDEST_LSN;
if (!(ra2->flags & RESTART_SINGLE_PAGE_IO))
log->l_flags |= NTFSLOG_WRAPPED | NTFSLOG_MULTIPLE_PAGE_IO;
log->current_openlog_count = le32_to_cpu(ra2->open_log_count);
log->total_avail_pages = log->l_size - log->first_page;
log->total_avail = log->total_avail_pages >> log->page_bits;
log->max_current_avail = log->total_avail * log->reserved;
log->total_avail = log->total_avail * log->data_size;
log->current_avail = current_log_avail(log);
ra = kzalloc(log->restart_size, GFP_NOFS);
if (!ra) {
err = -ENOMEM;
goto out;
}
log->ra = ra;
t16 = le16_to_cpu(ra2->client_off);
if (t16 == offsetof(struct RESTART_AREA, clients)) {
memcpy(ra, ra2, log->ra_size);
} else {
memcpy(ra, ra2, offsetof(struct RESTART_AREA, clients));
memcpy(ra->clients, Add2Ptr(ra2, t16),
le16_to_cpu(ra2->ra_len) - t16);
log->current_openlog_count = get_random_u32();
ra->open_log_count = cpu_to_le32(log->current_openlog_count);
log->ra_size = offsetof(struct RESTART_AREA, clients) +
sizeof(struct CLIENT_REC);
ra->client_off =
cpu_to_le16(offsetof(struct RESTART_AREA, clients));
ra->ra_len = cpu_to_le16(log->ra_size);
}
le32_add_cpu(&ra->open_log_count, 1);
/* Now we need to walk through looking for the last lsn. */
err = last_log_lsn(log);
if (err)
goto out;
log->current_avail = current_log_avail(log);
/* Remember which restart area to write first. */
log->init_ra = rst_info.vbo;
process_log:
/* 1.0, 1.1, 2.0 log->major_ver/minor_ver - short values. */
switch ((log->major_ver << 16) + log->minor_ver) {
case 0x10000:
case 0x10001:
case 0x20000:
break;
default:
ntfs_warn(sbi->sb, "\x24LogFile version %d.%d is not supported",
log->major_ver, log->minor_ver);
err = -EOPNOTSUPP;
log->set_dirty = true;
goto out;
}
/* One client "NTFS" per logfile. */
ca = Add2Ptr(ra, le16_to_cpu(ra->client_off));
for (client = ra->client_idx[1];; client = cr->next_client) {
if (client == LFS_NO_CLIENT_LE) {
/* Insert "NTFS" client LogFile. */
client = ra->client_idx[0];
if (client == LFS_NO_CLIENT_LE) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(client);
cr = ca + t16;
remove_client(ca, cr, &ra->client_idx[0]);
cr->restart_lsn = 0;
cr->oldest_lsn = cpu_to_le64(log->oldest_lsn);
cr->name_bytes = cpu_to_le32(8);
cr->name[0] = cpu_to_le16('N');
cr->name[1] = cpu_to_le16('T');
cr->name[2] = cpu_to_le16('F');
cr->name[3] = cpu_to_le16('S');
add_client(ca, t16, &ra->client_idx[1]);
break;
}
cr = ca + le16_to_cpu(client);
if (cpu_to_le32(8) == cr->name_bytes &&
cpu_to_le16('N') == cr->name[0] &&
cpu_to_le16('T') == cr->name[1] &&
cpu_to_le16('F') == cr->name[2] &&
cpu_to_le16('S') == cr->name[3])
break;
}
/* Update the client handle with the client block information. */
log->client_id.seq_num = cr->seq_num;
log->client_id.client_idx = client;
err = read_rst_area(log, &rst, &ra_lsn);
if (err)
goto out;
if (!rst)
goto out;
bytes_per_attr_entry = !rst->major_ver ? 0x2C : 0x28;
checkpt_lsn = le64_to_cpu(rst->check_point_start);
if (!checkpt_lsn)
checkpt_lsn = ra_lsn;
/* Allocate and Read the Transaction Table. */
if (!rst->transact_table_len)
goto check_dirty_page_table;
t64 = le64_to_cpu(rst->transact_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
/* Now check that this is a valid restart table. */
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
trtbl = kmemdup(rt, t32, GFP_NOFS);
if (!trtbl) {
err = -ENOMEM;
goto out;
}
lcb_put(lcb);
lcb = NULL;
check_dirty_page_table:
/* The next record back should be the Dirty Pages Table. */
if (!rst->dirty_pages_len)
goto check_attribute_names;
t64 = le64_to_cpu(rst->dirty_pages_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
/* Now check that this is a valid restart table. */
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
dptbl = kmemdup(rt, t32, GFP_NOFS);
if (!dptbl) {
err = -ENOMEM;
goto out;
}
/* Convert Ra version '0' into version '1'. */
if (rst->major_ver)
goto end_conv_1;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
struct DIR_PAGE_ENTRY_32 *dp0 = (struct DIR_PAGE_ENTRY_32 *)dp;
// NOTE: Danger. Check for of boundary.
memmove(&dp->vcn, &dp0->vcn_low,
2 * sizeof(u64) +
le32_to_cpu(dp->lcns_follow) * sizeof(u64));
}
end_conv_1:
lcb_put(lcb);
lcb = NULL;
/*
* Go through the table and remove the duplicates,
* remembering the oldest lsn values.
*/
if (sbi->cluster_size <= log->page_size)
goto trace_dp_table;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
struct DIR_PAGE_ENTRY *next = dp;
while ((next = enum_rstbl(dptbl, next))) {
if (next->target_attr == dp->target_attr &&
next->vcn == dp->vcn) {
if (le64_to_cpu(next->oldest_lsn) <
le64_to_cpu(dp->oldest_lsn)) {
dp->oldest_lsn = next->oldest_lsn;
}
free_rsttbl_idx(dptbl, PtrOffset(dptbl, next));
}
}
}
trace_dp_table:
check_attribute_names:
/* The next record should be the Attribute Names. */
if (!rst->attr_names_len)
goto check_attr_table;
t64 = le64_to_cpu(rst->attr_names_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t32 = lrh_length(lrh);
rec_len -= t32;
attr_names = kmemdup(Add2Ptr(lrh, t32), rec_len, GFP_NOFS);
if (!attr_names) {
err = -ENOMEM;
goto out;
}
lcb_put(lcb);
lcb = NULL;
check_attr_table:
/* The next record should be the attribute Table. */
if (!rst->open_attr_len)
goto check_attribute_names2;
t64 = le64_to_cpu(rst->open_attr_table_lsn);
err = read_log_rec_lcb(log, t64, lcb_ctx_prev, &lcb);
if (err)
goto out;
lrh = lcb->log_rec;
frh = lcb->lrh;
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, le32_to_cpu(frh->transact_id),
bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
t16 = le16_to_cpu(lrh->redo_off);
rt = Add2Ptr(lrh, t16);
t32 = rec_len - t16;
if (!check_rstbl(rt, t32)) {
err = -EINVAL;
goto out;
}
oatbl = kmemdup(rt, t32, GFP_NOFS);
if (!oatbl) {
err = -ENOMEM;
goto out;
}
log->open_attr_tbl = oatbl;
/* Clear all of the Attr pointers. */
oe = NULL;
while ((oe = enum_rstbl(oatbl, oe))) {
if (!rst->major_ver) {
struct OPEN_ATTR_ENRTY_32 oe0;
/* Really 'oe' points to OPEN_ATTR_ENRTY_32. */
memcpy(&oe0, oe, SIZEOF_OPENATTRIBUTEENTRY0);
oe->bytes_per_index = oe0.bytes_per_index;
oe->type = oe0.type;
oe->is_dirty_pages = oe0.is_dirty_pages;
oe->name_len = 0;
oe->ref = oe0.ref;
oe->open_record_lsn = oe0.open_record_lsn;
}
oe->is_attr_name = 0;
oe->ptr = NULL;
}
lcb_put(lcb);
lcb = NULL;
check_attribute_names2:
if (!rst->attr_names_len)
goto trace_attribute_table;
ane = attr_names;
if (!oatbl)
goto trace_attribute_table;
while (ane->off) {
/* TODO: Clear table on exit! */
oe = Add2Ptr(oatbl, le16_to_cpu(ane->off));
t16 = le16_to_cpu(ane->name_bytes);
oe->name_len = t16 / sizeof(short);
oe->ptr = ane->name;
oe->is_attr_name = 2;
ane = Add2Ptr(ane, sizeof(struct ATTR_NAME_ENTRY) + t16);
}
trace_attribute_table:
/*
* If the checkpt_lsn is zero, then this is a freshly
* formatted disk and we have no work to do.
*/
if (!checkpt_lsn) {
err = 0;
goto out;
}
if (!oatbl) {
oatbl = init_rsttbl(bytes_per_attr_entry, 8);
if (!oatbl) {
err = -ENOMEM;
goto out;
}
}
log->open_attr_tbl = oatbl;
/* Start the analysis pass from the Checkpoint lsn. */
rec_lsn = checkpt_lsn;
/* Read the first lsn. */
err = read_log_rec_lcb(log, checkpt_lsn, lcb_ctx_next, &lcb);
if (err)
goto out;
/* Loop to read all subsequent records to the end of the log file. */
next_log_record_analyze:
err = read_next_log_rec(log, lcb, &rec_lsn);
if (err)
goto out;
if (!rec_lsn)
goto end_log_records_enumerate;
frh = lcb->lrh;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
lrh = lcb->log_rec;
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
/*
* The first lsn after the previous lsn remembered
* the checkpoint is the first candidate for the rlsn.
*/
if (!rlsn)
rlsn = rec_lsn;
if (LfsClientRecord != frh->record_type)
goto next_log_record_analyze;
/*
* Now update the Transaction Table for this transaction. If there
* is no entry present or it is unallocated we allocate the entry.
*/
if (!trtbl) {
trtbl = init_rsttbl(sizeof(struct TRANSACTION_ENTRY),
INITIAL_NUMBER_TRANSACTIONS);
if (!trtbl) {
err = -ENOMEM;
goto out;
}
}
tr = Add2Ptr(trtbl, transact_id);
if (transact_id >= bytes_per_rt(trtbl) ||
tr->next != RESTART_ENTRY_ALLOCATED_LE) {
tr = alloc_rsttbl_from_idx(&trtbl, transact_id);
if (!tr) {
err = -ENOMEM;
goto out;
}
tr->transact_state = TransactionActive;
tr->first_lsn = cpu_to_le64(rec_lsn);
}
tr->prev_lsn = tr->undo_next_lsn = cpu_to_le64(rec_lsn);
/*
* If this is a compensation log record, then change
* the undo_next_lsn to be the undo_next_lsn of this record.
*/
if (lrh->undo_op == cpu_to_le16(CompensationLogRecord))
tr->undo_next_lsn = frh->client_undo_next_lsn;
/* Dispatch to handle log record depending on type. */
switch (le16_to_cpu(lrh->redo_op)) {
case InitializeFileRecordSegment:
case DeallocateFileRecordSegment:
case WriteEndOfFileRecordSegment:
case CreateAttribute:
case DeleteAttribute:
case UpdateResidentValue:
case UpdateNonresidentValue:
case UpdateMappingPairs:
case SetNewAttributeSizes:
case AddIndexEntryRoot:
case DeleteIndexEntryRoot:
case AddIndexEntryAllocation:
case DeleteIndexEntryAllocation:
case WriteEndOfIndexBuffer:
case SetIndexEntryVcnRoot:
case SetIndexEntryVcnAllocation:
case UpdateFileNameRoot:
case UpdateFileNameAllocation:
case SetBitsInNonresidentBitMap:
case ClearBitsInNonresidentBitMap:
case UpdateRecordDataRoot:
case UpdateRecordDataAllocation:
case ZeroEndOfFileRecord:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (dp)
goto copy_lcns;
/*
* Calculate the number of clusters per page the system
* which wrote the checkpoint, possibly creating the table.
*/
if (dptbl) {
t32 = (le16_to_cpu(dptbl->size) -
sizeof(struct DIR_PAGE_ENTRY)) /
sizeof(u64);
} else {
t32 = log->clst_per_page;
kfree(dptbl);
dptbl = init_rsttbl(struct_size(dp, page_lcns, t32),
32);
if (!dptbl) {
err = -ENOMEM;
goto out;
}
}
dp = alloc_rsttbl_idx(&dptbl);
if (!dp) {
err = -ENOMEM;
goto out;
}
dp->target_attr = cpu_to_le32(t16);
dp->transfer_len = cpu_to_le32(t32 << sbi->cluster_bits);
dp->lcns_follow = cpu_to_le32(t32);
dp->vcn = cpu_to_le64(t64 & ~((u64)t32 - 1));
dp->oldest_lsn = cpu_to_le64(rec_lsn);
copy_lcns:
/*
* Copy the Lcns from the log record into the Dirty Page Entry.
* TODO: For different page size support, must somehow make
* whole routine a loop, case Lcns do not fit below.
*/
t16 = le16_to_cpu(lrh->lcns_follow);
for (i = 0; i < t16; i++) {
size_t j = (size_t)(le64_to_cpu(lrh->target_vcn) -
le64_to_cpu(dp->vcn));
dp->page_lcns[j + i] = lrh->page_lcns[i];
}
goto next_log_record_analyze;
case DeleteDirtyClusters: {
u32 range_count =
le16_to_cpu(lrh->redo_len) / sizeof(struct LCN_RANGE);
const struct LCN_RANGE *r =
Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
/* Loop through all of the Lcn ranges this log record. */
for (i = 0; i < range_count; i++, r++) {
u64 lcn0 = le64_to_cpu(r->lcn);
u64 lcn_e = lcn0 + le64_to_cpu(r->len) - 1;
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
u32 j;
t32 = le32_to_cpu(dp->lcns_follow);
for (j = 0; j < t32; j++) {
t64 = le64_to_cpu(dp->page_lcns[j]);
if (t64 >= lcn0 && t64 <= lcn_e)
dp->page_lcns[j] = 0;
}
}
}
goto next_log_record_analyze;
;
}
case OpenNonresidentAttribute:
t16 = le16_to_cpu(lrh->target_attr);
if (t16 >= bytes_per_rt(oatbl)) {
/*
* Compute how big the table needs to be.
* Add 10 extra entries for some cushion.
*/
u32 new_e = t16 / le16_to_cpu(oatbl->size);
new_e += 10 - le16_to_cpu(oatbl->used);
oatbl = extend_rsttbl(oatbl, new_e, ~0u);
log->open_attr_tbl = oatbl;
if (!oatbl) {
err = -ENOMEM;
goto out;
}
}
/* Point to the entry being opened. */
oe = alloc_rsttbl_from_idx(&oatbl, t16);
log->open_attr_tbl = oatbl;
if (!oe) {
err = -ENOMEM;
goto out;
}
/* Initialize this entry from the log record. */
t16 = le16_to_cpu(lrh->redo_off);
if (!rst->major_ver) {
/* Convert version '0' into version '1'. */
struct OPEN_ATTR_ENRTY_32 *oe0 = Add2Ptr(lrh, t16);
oe->bytes_per_index = oe0->bytes_per_index;
oe->type = oe0->type;
oe->is_dirty_pages = oe0->is_dirty_pages;
oe->name_len = 0; //oe0.name_len;
oe->ref = oe0->ref;
oe->open_record_lsn = oe0->open_record_lsn;
} else {
memcpy(oe, Add2Ptr(lrh, t16), bytes_per_attr_entry);
}
t16 = le16_to_cpu(lrh->undo_len);
if (t16) {
oe->ptr = kmalloc(t16, GFP_NOFS);
if (!oe->ptr) {
err = -ENOMEM;
goto out;
}
oe->name_len = t16 / sizeof(short);
memcpy(oe->ptr,
Add2Ptr(lrh, le16_to_cpu(lrh->undo_off)), t16);
oe->is_attr_name = 1;
} else {
oe->ptr = NULL;
oe->is_attr_name = 0;
}
goto next_log_record_analyze;
case HotFix:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (dp) {
size_t j = le64_to_cpu(lrh->target_vcn) -
le64_to_cpu(dp->vcn);
if (dp->page_lcns[j])
dp->page_lcns[j] = lrh->page_lcns[0];
}
goto next_log_record_analyze;
case EndTopLevelAction:
tr = Add2Ptr(trtbl, transact_id);
tr->prev_lsn = cpu_to_le64(rec_lsn);
tr->undo_next_lsn = frh->client_undo_next_lsn;
goto next_log_record_analyze;
case PrepareTransaction:
tr = Add2Ptr(trtbl, transact_id);
tr->transact_state = TransactionPrepared;
goto next_log_record_analyze;
case CommitTransaction:
tr = Add2Ptr(trtbl, transact_id);
tr->transact_state = TransactionCommitted;
goto next_log_record_analyze;
case ForgetTransaction:
free_rsttbl_idx(trtbl, transact_id);
goto next_log_record_analyze;
case Noop:
case OpenAttributeTableDump:
case AttributeNamesDump:
case DirtyPageTableDump:
case TransactionTableDump:
/* The following cases require no action the Analysis Pass. */
goto next_log_record_analyze;
default:
/*
* All codes will be explicitly handled.
* If we see a code we do not expect, then we are trouble.
*/
goto next_log_record_analyze;
}
end_log_records_enumerate:
lcb_put(lcb);
lcb = NULL;
/*
* Scan the Dirty Page Table and Transaction Table for
* the lowest lsn, and return it as the Redo lsn.
*/
dp = NULL;
while ((dp = enum_rstbl(dptbl, dp))) {
t64 = le64_to_cpu(dp->oldest_lsn);
if (t64 && t64 < rlsn)
rlsn = t64;
}
tr = NULL;
while ((tr = enum_rstbl(trtbl, tr))) {
t64 = le64_to_cpu(tr->first_lsn);
if (t64 && t64 < rlsn)
rlsn = t64;
}
/*
* Only proceed if the Dirty Page Table or Transaction
* table are not empty.
*/
if ((!dptbl || !dptbl->total) && (!trtbl || !trtbl->total))
goto end_reply;
sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
if (is_ro)
goto out;
/* Reopen all of the attributes with dirty pages. */
oe = NULL;
next_open_attribute:
oe = enum_rstbl(oatbl, oe);
if (!oe) {
err = 0;
dp = NULL;
goto next_dirty_page;
}
oa = kzalloc(sizeof(struct OpenAttr), GFP_NOFS);
if (!oa) {
err = -ENOMEM;
goto out;
}
inode = ntfs_iget5(sbi->sb, &oe->ref, NULL);
if (IS_ERR(inode))
goto fake_attr;
if (is_bad_inode(inode)) {
iput(inode);
fake_attr:
if (oa->ni) {
iput(&oa->ni->vfs_inode);
oa->ni = NULL;
}
attr = attr_create_nonres_log(sbi, oe->type, 0, oe->ptr,
oe->name_len, 0);
if (!attr) {
kfree(oa);
err = -ENOMEM;
goto out;
}
oa->attr = attr;
oa->run1 = &oa->run0;
goto final_oe;
}
ni_oe = ntfs_i(inode);
oa->ni = ni_oe;
attr = ni_find_attr(ni_oe, NULL, NULL, oe->type, oe->ptr, oe->name_len,
NULL, NULL);
if (!attr)
goto fake_attr;
t32 = le32_to_cpu(attr->size);
oa->attr = kmemdup(attr, t32, GFP_NOFS);
if (!oa->attr)
goto fake_attr;
if (!S_ISDIR(inode->i_mode)) {
if (attr->type == ATTR_DATA && !attr->name_len) {
oa->run1 = &ni_oe->file.run;
goto final_oe;
}
} else {
if (attr->type == ATTR_ALLOC &&
attr->name_len == ARRAY_SIZE(I30_NAME) &&
!memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME))) {
oa->run1 = &ni_oe->dir.alloc_run;
goto final_oe;
}
}
if (attr->non_res) {
u16 roff = le16_to_cpu(attr->nres.run_off);
CLST svcn = le64_to_cpu(attr->nres.svcn);
if (roff > t32) {
kfree(oa->attr);
oa->attr = NULL;
goto fake_attr;
}
err = run_unpack(&oa->run0, sbi, inode->i_ino, svcn,
le64_to_cpu(attr->nres.evcn), svcn,
Add2Ptr(attr, roff), t32 - roff);
if (err < 0) {
kfree(oa->attr);
oa->attr = NULL;
goto fake_attr;
}
err = 0;
}
oa->run1 = &oa->run0;
attr = oa->attr;
final_oe:
if (oe->is_attr_name == 1)
kfree(oe->ptr);
oe->is_attr_name = 0;
oe->ptr = oa;
oe->name_len = attr->name_len;
goto next_open_attribute;
/*
* Now loop through the dirty page table to extract all of the Vcn/Lcn.
* Mapping that we have, and insert it into the appropriate run.
*/
next_dirty_page:
dp = enum_rstbl(dptbl, dp);
if (!dp)
goto do_redo_1;
oe = Add2Ptr(oatbl, le32_to_cpu(dp->target_attr));
if (oe->next != RESTART_ENTRY_ALLOCATED_LE)
goto next_dirty_page;
oa = oe->ptr;
if (!oa)
goto next_dirty_page;
i = -1;
next_dirty_page_vcn:
i += 1;
if (i >= le32_to_cpu(dp->lcns_follow))
goto next_dirty_page;
vcn = le64_to_cpu(dp->vcn) + i;
size = (vcn + 1) << sbi->cluster_bits;
if (!dp->page_lcns[i])
goto next_dirty_page_vcn;
rno = ino_get(&oe->ref);
if (rno <= MFT_REC_MIRR &&
size < (MFT_REC_VOL + 1) * sbi->record_size &&
oe->type == ATTR_DATA) {
goto next_dirty_page_vcn;
}
lcn = le64_to_cpu(dp->page_lcns[i]);
if ((!run_lookup_entry(oa->run1, vcn, &lcn0, &len0, NULL) ||
lcn0 != lcn) &&
!run_add_entry(oa->run1, vcn, lcn, 1, false)) {
err = -ENOMEM;
goto out;
}
attr = oa->attr;
if (size > le64_to_cpu(attr->nres.alloc_size)) {
attr->nres.valid_size = attr->nres.data_size =
attr->nres.alloc_size = cpu_to_le64(size);
}
goto next_dirty_page_vcn;
do_redo_1:
/*
* Perform the Redo Pass, to restore all of the dirty pages to the same
* contents that they had immediately before the crash. If the dirty
* page table is empty, then we can skip the entire Redo Pass.
*/
if (!dptbl || !dptbl->total)
goto do_undo_action;
rec_lsn = rlsn;
/*
* Read the record at the Redo lsn, before falling
* into common code to handle each record.
*/
err = read_log_rec_lcb(log, rlsn, lcb_ctx_next, &lcb);
if (err)
goto out;
/*
* Now loop to read all of our log records forwards, until
* we hit the end of the file, cleaning up at the end.
*/
do_action_next:
frh = lcb->lrh;
if (LfsClientRecord != frh->record_type)
goto read_next_log_do_action;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
lrh = lcb->log_rec;
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
/* Ignore log records that do not update pages. */
if (lrh->lcns_follow)
goto find_dirty_page;
goto read_next_log_do_action;
find_dirty_page:
t16 = le16_to_cpu(lrh->target_attr);
t64 = le64_to_cpu(lrh->target_vcn);
dp = find_dp(dptbl, t16, t64);
if (!dp)
goto read_next_log_do_action;
if (rec_lsn < le64_to_cpu(dp->oldest_lsn))
goto read_next_log_do_action;
t16 = le16_to_cpu(lrh->target_attr);
if (t16 >= bytes_per_rt(oatbl)) {
err = -EINVAL;
goto out;
}
oe = Add2Ptr(oatbl, t16);
if (oe->next != RESTART_ENTRY_ALLOCATED_LE) {
err = -EINVAL;
goto out;
}
oa = oe->ptr;
if (!oa) {
err = -EINVAL;
goto out;
}
attr = oa->attr;
vcn = le64_to_cpu(lrh->target_vcn);
if (!run_lookup_entry(oa->run1, vcn, &lcn, NULL, NULL) ||
lcn == SPARSE_LCN) {
goto read_next_log_do_action;
}
/* Point to the Redo data and get its length. */
data = Add2Ptr(lrh, le16_to_cpu(lrh->redo_off));
dlen = le16_to_cpu(lrh->redo_len);
/* Shorten length by any Lcns which were deleted. */
saved_len = dlen;
for (i = le16_to_cpu(lrh->lcns_follow); i; i--) {
size_t j;
u32 alen, voff;
voff = le16_to_cpu(lrh->record_off) +
le16_to_cpu(lrh->attr_off);
voff += le16_to_cpu(lrh->cluster_off) << SECTOR_SHIFT;
/* If the Vcn question is allocated, we can just get out. */
j = le64_to_cpu(lrh->target_vcn) - le64_to_cpu(dp->vcn);
if (dp->page_lcns[j + i - 1])
break;
if (!saved_len)
saved_len = 1;
/*
* Calculate the allocated space left relative to the
* log record Vcn, after removing this unallocated Vcn.
*/
alen = (i - 1) << sbi->cluster_bits;
/*
* If the update described this log record goes beyond
* the allocated space, then we will have to reduce the length.
*/
if (voff >= alen)
dlen = 0;
else if (voff + dlen > alen)
dlen = alen - voff;
}
/*
* If the resulting dlen from above is now zero,
* we can skip this log record.
*/
if (!dlen && saved_len)
goto read_next_log_do_action;
t16 = le16_to_cpu(lrh->redo_op);
if (can_skip_action(t16))
goto read_next_log_do_action;
/* Apply the Redo operation a common routine. */
err = do_action(log, oe, lrh, t16, data, dlen, rec_len, &rec_lsn);
if (err)
goto out;
/* Keep reading and looping back until end of file. */
read_next_log_do_action:
err = read_next_log_rec(log, lcb, &rec_lsn);
if (!err && rec_lsn)
goto do_action_next;
lcb_put(lcb);
lcb = NULL;
do_undo_action:
/* Scan Transaction Table. */
tr = NULL;
transaction_table_next:
tr = enum_rstbl(trtbl, tr);
if (!tr)
goto undo_action_done;
if (TransactionActive != tr->transact_state || !tr->undo_next_lsn) {
free_rsttbl_idx(trtbl, PtrOffset(trtbl, tr));
goto transaction_table_next;
}
log->transaction_id = PtrOffset(trtbl, tr);
undo_next_lsn = le64_to_cpu(tr->undo_next_lsn);
/*
* We only have to do anything if the transaction has
* something its undo_next_lsn field.
*/
if (!undo_next_lsn)
goto commit_undo;
/* Read the first record to be undone by this transaction. */
err = read_log_rec_lcb(log, undo_next_lsn, lcb_ctx_undo_next, &lcb);
if (err)
goto out;
/*
* Now loop to read all of our log records forwards,
* until we hit the end of the file, cleaning up at the end.
*/
undo_action_next:
lrh = lcb->log_rec;
frh = lcb->lrh;
transact_id = le32_to_cpu(frh->transact_id);
rec_len = le32_to_cpu(frh->client_data_len);
if (!check_log_rec(lrh, rec_len, transact_id, bytes_per_attr_entry)) {
err = -EINVAL;
goto out;
}
if (lrh->undo_op == cpu_to_le16(Noop))
goto read_next_log_undo_action;
oe = Add2Ptr(oatbl, le16_to_cpu(lrh->target_attr));
oa = oe->ptr;
t16 = le16_to_cpu(lrh->lcns_follow);
if (!t16)
goto add_allocated_vcns;
is_mapped = run_lookup_entry(oa->run1, le64_to_cpu(lrh->target_vcn),
&lcn, &clen, NULL);
/*
* If the mapping isn't already the table or the mapping
* corresponds to a hole the mapping, we need to make sure
* there is no partial page already memory.
*/
if (is_mapped && lcn != SPARSE_LCN && clen >= t16)
goto add_allocated_vcns;
vcn = le64_to_cpu(lrh->target_vcn);
vcn &= ~(u64)(log->clst_per_page - 1);
add_allocated_vcns:
for (i = 0, vcn = le64_to_cpu(lrh->target_vcn),
size = (vcn + 1) << sbi->cluster_bits;
i < t16; i++, vcn += 1, size += sbi->cluster_size) {
attr = oa->attr;
if (!attr->non_res) {
if (size > le32_to_cpu(attr->res.data_size))
attr->res.data_size = cpu_to_le32(size);
} else {
if (size > le64_to_cpu(attr->nres.data_size))
attr->nres.valid_size = attr->nres.data_size =
attr->nres.alloc_size =
cpu_to_le64(size);
}
}
t16 = le16_to_cpu(lrh->undo_op);
if (can_skip_action(t16))
goto read_next_log_undo_action;
/* Point to the Redo data and get its length. */
data = Add2Ptr(lrh, le16_to_cpu(lrh->undo_off));
dlen = le16_to_cpu(lrh->undo_len);
/* It is time to apply the undo action. */
err = do_action(log, oe, lrh, t16, data, dlen, rec_len, NULL);
read_next_log_undo_action:
/*
* Keep reading and looping back until we have read the
* last record for this transaction.
*/
err = read_next_log_rec(log, lcb, &rec_lsn);
if (err)
goto out;
if (rec_lsn)
goto undo_action_next;
lcb_put(lcb);
lcb = NULL;
commit_undo:
free_rsttbl_idx(trtbl, log->transaction_id);
log->transaction_id = 0;
goto transaction_table_next;
undo_action_done:
ntfs_update_mftmirr(sbi, 0);
sbi->flags &= ~NTFS_FLAGS_NEED_REPLAY;
end_reply:
err = 0;
if (is_ro)
goto out;
rh = kzalloc(log->page_size, GFP_NOFS);
if (!rh) {
err = -ENOMEM;
goto out;
}
rh->rhdr.sign = NTFS_RSTR_SIGNATURE;
rh->rhdr.fix_off = cpu_to_le16(offsetof(struct RESTART_HDR, fixups));
t16 = (log->page_size >> SECTOR_SHIFT) + 1;
rh->rhdr.fix_num = cpu_to_le16(t16);
rh->sys_page_size = cpu_to_le32(log->page_size);
rh->page_size = cpu_to_le32(log->page_size);
t16 = ALIGN(offsetof(struct RESTART_HDR, fixups) + sizeof(short) * t16,
8);
rh->ra_off = cpu_to_le16(t16);
rh->minor_ver = cpu_to_le16(1); // 0x1A:
rh->major_ver = cpu_to_le16(1); // 0x1C:
ra2 = Add2Ptr(rh, t16);
memcpy(ra2, ra, sizeof(struct RESTART_AREA));
ra2->client_idx[0] = 0;
ra2->client_idx[1] = LFS_NO_CLIENT_LE;
ra2->flags = cpu_to_le16(2);
le32_add_cpu(&ra2->open_log_count, 1);
ntfs_fix_pre_write(&rh->rhdr, log->page_size);
err = ntfs_sb_write_run(sbi, &ni->file.run, 0, rh, log->page_size, 0);
if (!err)
err = ntfs_sb_write_run(sbi, &log->ni->file.run, log->page_size,
rh, log->page_size, 0);
kfree(rh);
if (err)
goto out;
out:
kfree(rst);
if (lcb)
lcb_put(lcb);
/*
* Scan the Open Attribute Table to close all of
* the open attributes.
*/
oe = NULL;
while ((oe = enum_rstbl(oatbl, oe))) {
rno = ino_get(&oe->ref);
if (oe->is_attr_name == 1) {
kfree(oe->ptr);
oe->ptr = NULL;
continue;
}
if (oe->is_attr_name)
continue;
oa = oe->ptr;
if (!oa)
continue;
run_close(&oa->run0);
kfree(oa->attr);
if (oa->ni)
iput(&oa->ni->vfs_inode);
kfree(oa);
}
kfree(trtbl);
kfree(oatbl);
kfree(dptbl);
kfree(attr_names);
kfree(rst_info.r_page);
kfree(ra);
kfree(log->one_page_buf);
if (err)
sbi->flags |= NTFS_FLAGS_NEED_REPLAY;
if (err == -EROFS)
err = 0;
else if (log->set_dirty)
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
kfree(log);
return err;
}
| linux-master | fs/ntfs3/fslog.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
* TODO: try to use extents tree (instead of array)
*/
#include <linux/blkdev.h>
#include <linux/fs.h>
#include <linux/log2.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/* runs_tree is a continues memory. Try to avoid big size. */
#define NTFS3_RUN_MAX_BYTES 0x10000
struct ntfs_run {
CLST vcn; /* Virtual cluster number. */
CLST len; /* Length in clusters. */
CLST lcn; /* Logical cluster number. */
};
/*
* run_lookup - Lookup the index of a MCB entry that is first <= vcn.
*
* Case of success it will return non-zero value and set
* @index parameter to index of entry been found.
* Case of entry missing from list 'index' will be set to
* point to insertion position for the entry question.
*/
static bool run_lookup(const struct runs_tree *run, CLST vcn, size_t *index)
{
size_t min_idx, max_idx, mid_idx;
struct ntfs_run *r;
if (!run->count) {
*index = 0;
return false;
}
min_idx = 0;
max_idx = run->count - 1;
/* Check boundary cases specially, 'cause they cover the often requests. */
r = run->runs;
if (vcn < r->vcn) {
*index = 0;
return false;
}
if (vcn < r->vcn + r->len) {
*index = 0;
return true;
}
r += max_idx;
if (vcn >= r->vcn + r->len) {
*index = run->count;
return false;
}
if (vcn >= r->vcn) {
*index = max_idx;
return true;
}
do {
mid_idx = min_idx + ((max_idx - min_idx) >> 1);
r = run->runs + mid_idx;
if (vcn < r->vcn) {
max_idx = mid_idx - 1;
if (!mid_idx)
break;
} else if (vcn >= r->vcn + r->len) {
min_idx = mid_idx + 1;
} else {
*index = mid_idx;
return true;
}
} while (min_idx <= max_idx);
*index = max_idx + 1;
return false;
}
/*
* run_consolidate - Consolidate runs starting from a given one.
*/
static void run_consolidate(struct runs_tree *run, size_t index)
{
size_t i;
struct ntfs_run *r = run->runs + index;
while (index + 1 < run->count) {
/*
* I should merge current run with next
* if start of the next run lies inside one being tested.
*/
struct ntfs_run *n = r + 1;
CLST end = r->vcn + r->len;
CLST dl;
/* Stop if runs are not aligned one to another. */
if (n->vcn > end)
break;
dl = end - n->vcn;
/*
* If range at index overlaps with next one
* then I will either adjust it's start position
* or (if completely matches) dust remove one from the list.
*/
if (dl > 0) {
if (n->len <= dl)
goto remove_next_range;
n->len -= dl;
n->vcn += dl;
if (n->lcn != SPARSE_LCN)
n->lcn += dl;
dl = 0;
}
/*
* Stop if sparse mode does not match
* both current and next runs.
*/
if ((n->lcn == SPARSE_LCN) != (r->lcn == SPARSE_LCN)) {
index += 1;
r = n;
continue;
}
/*
* Check if volume block
* of a next run lcn does not match
* last volume block of the current run.
*/
if (n->lcn != SPARSE_LCN && n->lcn != r->lcn + r->len)
break;
/*
* Next and current are siblings.
* Eat/join.
*/
r->len += n->len - dl;
remove_next_range:
i = run->count - (index + 1);
if (i > 1)
memmove(n, n + 1, sizeof(*n) * (i - 1));
run->count -= 1;
}
}
/*
* run_is_mapped_full
*
* Return: True if range [svcn - evcn] is mapped.
*/
bool run_is_mapped_full(const struct runs_tree *run, CLST svcn, CLST evcn)
{
size_t i;
const struct ntfs_run *r, *end;
CLST next_vcn;
if (!run_lookup(run, svcn, &i))
return false;
end = run->runs + run->count;
r = run->runs + i;
for (;;) {
next_vcn = r->vcn + r->len;
if (next_vcn > evcn)
return true;
if (++r >= end)
return false;
if (r->vcn != next_vcn)
return false;
}
}
bool run_lookup_entry(const struct runs_tree *run, CLST vcn, CLST *lcn,
CLST *len, size_t *index)
{
size_t idx;
CLST gap;
struct ntfs_run *r;
/* Fail immediately if nrun was not touched yet. */
if (!run->runs)
return false;
if (!run_lookup(run, vcn, &idx))
return false;
r = run->runs + idx;
if (vcn >= r->vcn + r->len)
return false;
gap = vcn - r->vcn;
if (r->len <= gap)
return false;
*lcn = r->lcn == SPARSE_LCN ? SPARSE_LCN : (r->lcn + gap);
if (len)
*len = r->len - gap;
if (index)
*index = idx;
return true;
}
/*
* run_truncate_head - Decommit the range before vcn.
*/
void run_truncate_head(struct runs_tree *run, CLST vcn)
{
size_t index;
struct ntfs_run *r;
if (run_lookup(run, vcn, &index)) {
r = run->runs + index;
if (vcn > r->vcn) {
CLST dlen = vcn - r->vcn;
r->vcn = vcn;
r->len -= dlen;
if (r->lcn != SPARSE_LCN)
r->lcn += dlen;
}
if (!index)
return;
}
r = run->runs;
memmove(r, r + index, sizeof(*r) * (run->count - index));
run->count -= index;
if (!run->count) {
kvfree(run->runs);
run->runs = NULL;
run->allocated = 0;
}
}
/*
* run_truncate - Decommit the range after vcn.
*/
void run_truncate(struct runs_tree *run, CLST vcn)
{
size_t index;
/*
* If I hit the range then
* I have to truncate one.
* If range to be truncated is becoming empty
* then it will entirely be removed.
*/
if (run_lookup(run, vcn, &index)) {
struct ntfs_run *r = run->runs + index;
r->len = vcn - r->vcn;
if (r->len > 0)
index += 1;
}
/*
* At this point 'index' is set to position that
* should be thrown away (including index itself)
* Simple one - just set the limit.
*/
run->count = index;
/* Do not reallocate array 'runs'. Only free if possible. */
if (!index) {
kvfree(run->runs);
run->runs = NULL;
run->allocated = 0;
}
}
/*
* run_truncate_around - Trim head and tail if necessary.
*/
void run_truncate_around(struct runs_tree *run, CLST vcn)
{
run_truncate_head(run, vcn);
if (run->count >= NTFS3_RUN_MAX_BYTES / sizeof(struct ntfs_run) / 2)
run_truncate(run, (run->runs + (run->count >> 1))->vcn);
}
/*
* run_add_entry
*
* Sets location to known state.
* Run to be added may overlap with existing location.
*
* Return: false if of memory.
*/
bool run_add_entry(struct runs_tree *run, CLST vcn, CLST lcn, CLST len,
bool is_mft)
{
size_t used, index;
struct ntfs_run *r;
bool inrange;
CLST tail_vcn = 0, tail_len = 0, tail_lcn = 0;
bool should_add_tail = false;
/*
* Lookup the insertion point.
*
* Execute bsearch for the entry containing
* start position question.
*/
inrange = run_lookup(run, vcn, &index);
/*
* Shortcut here would be case of
* range not been found but one been added
* continues previous run.
* This case I can directly make use of
* existing range as my start point.
*/
if (!inrange && index > 0) {
struct ntfs_run *t = run->runs + index - 1;
if (t->vcn + t->len == vcn &&
(t->lcn == SPARSE_LCN) == (lcn == SPARSE_LCN) &&
(lcn == SPARSE_LCN || lcn == t->lcn + t->len)) {
inrange = true;
index -= 1;
}
}
/*
* At this point 'index' either points to the range
* containing start position or to the insertion position
* for a new range.
* So first let's check if range I'm probing is here already.
*/
if (!inrange) {
requires_new_range:
/*
* Range was not found.
* Insert at position 'index'
*/
used = run->count * sizeof(struct ntfs_run);
/*
* Check allocated space.
* If one is not enough to get one more entry
* then it will be reallocated.
*/
if (run->allocated < used + sizeof(struct ntfs_run)) {
size_t bytes;
struct ntfs_run *new_ptr;
/* Use power of 2 for 'bytes'. */
if (!used) {
bytes = 64;
} else if (used <= 16 * PAGE_SIZE) {
if (is_power_of_2(run->allocated))
bytes = run->allocated << 1;
else
bytes = (size_t)1
<< (2 + blksize_bits(used));
} else {
bytes = run->allocated + (16 * PAGE_SIZE);
}
WARN_ON(!is_mft && bytes > NTFS3_RUN_MAX_BYTES);
new_ptr = kvmalloc(bytes, GFP_KERNEL);
if (!new_ptr)
return false;
r = new_ptr + index;
memcpy(new_ptr, run->runs,
index * sizeof(struct ntfs_run));
memcpy(r + 1, run->runs + index,
sizeof(struct ntfs_run) * (run->count - index));
kvfree(run->runs);
run->runs = new_ptr;
run->allocated = bytes;
} else {
size_t i = run->count - index;
r = run->runs + index;
/* memmove appears to be a bottle neck here... */
if (i > 0)
memmove(r + 1, r, sizeof(struct ntfs_run) * i);
}
r->vcn = vcn;
r->lcn = lcn;
r->len = len;
run->count += 1;
} else {
r = run->runs + index;
/*
* If one of ranges was not allocated then we
* have to split location we just matched and
* insert current one.
* A common case this requires tail to be reinserted
* a recursive call.
*/
if (((lcn == SPARSE_LCN) != (r->lcn == SPARSE_LCN)) ||
(lcn != SPARSE_LCN && lcn != r->lcn + (vcn - r->vcn))) {
CLST to_eat = vcn - r->vcn;
CLST Tovcn = to_eat + len;
should_add_tail = Tovcn < r->len;
if (should_add_tail) {
tail_lcn = r->lcn == SPARSE_LCN ?
SPARSE_LCN :
(r->lcn + Tovcn);
tail_vcn = r->vcn + Tovcn;
tail_len = r->len - Tovcn;
}
if (to_eat > 0) {
r->len = to_eat;
inrange = false;
index += 1;
goto requires_new_range;
}
/* lcn should match one were going to add. */
r->lcn = lcn;
}
/*
* If existing range fits then were done.
* Otherwise extend found one and fall back to range jocode.
*/
if (r->vcn + r->len < vcn + len)
r->len += len - ((r->vcn + r->len) - vcn);
}
/*
* And normalize it starting from insertion point.
* It's possible that no insertion needed case if
* start point lies within the range of an entry
* that 'index' points to.
*/
if (inrange && index > 0)
index -= 1;
run_consolidate(run, index);
run_consolidate(run, index + 1);
/*
* A special case.
* We have to add extra range a tail.
*/
if (should_add_tail &&
!run_add_entry(run, tail_vcn, tail_lcn, tail_len, is_mft))
return false;
return true;
}
/* run_collapse_range
*
* Helper for attr_collapse_range(),
* which is helper for fallocate(collapse_range).
*/
bool run_collapse_range(struct runs_tree *run, CLST vcn, CLST len)
{
size_t index, eat;
struct ntfs_run *r, *e, *eat_start, *eat_end;
CLST end;
if (WARN_ON(!run_lookup(run, vcn, &index)))
return true; /* Should never be here. */
e = run->runs + run->count;
r = run->runs + index;
end = vcn + len;
if (vcn > r->vcn) {
if (r->vcn + r->len <= end) {
/* Collapse tail of run .*/
r->len = vcn - r->vcn;
} else if (r->lcn == SPARSE_LCN) {
/* Collapse a middle part of sparsed run. */
r->len -= len;
} else {
/* Collapse a middle part of normal run, split. */
if (!run_add_entry(run, vcn, SPARSE_LCN, len, false))
return false;
return run_collapse_range(run, vcn, len);
}
r += 1;
}
eat_start = r;
eat_end = r;
for (; r < e; r++) {
CLST d;
if (r->vcn >= end) {
r->vcn -= len;
continue;
}
if (r->vcn + r->len <= end) {
/* Eat this run. */
eat_end = r + 1;
continue;
}
d = end - r->vcn;
if (r->lcn != SPARSE_LCN)
r->lcn += d;
r->len -= d;
r->vcn -= len - d;
}
eat = eat_end - eat_start;
memmove(eat_start, eat_end, (e - eat_end) * sizeof(*r));
run->count -= eat;
return true;
}
/* run_insert_range
*
* Helper for attr_insert_range(),
* which is helper for fallocate(insert_range).
*/
bool run_insert_range(struct runs_tree *run, CLST vcn, CLST len)
{
size_t index;
struct ntfs_run *r, *e;
if (WARN_ON(!run_lookup(run, vcn, &index)))
return false; /* Should never be here. */
e = run->runs + run->count;
r = run->runs + index;
if (vcn > r->vcn)
r += 1;
for (; r < e; r++)
r->vcn += len;
r = run->runs + index;
if (vcn > r->vcn) {
/* split fragment. */
CLST len1 = vcn - r->vcn;
CLST len2 = r->len - len1;
CLST lcn2 = r->lcn == SPARSE_LCN ? SPARSE_LCN : (r->lcn + len1);
r->len = len1;
if (!run_add_entry(run, vcn + len, lcn2, len2, false))
return false;
}
if (!run_add_entry(run, vcn, SPARSE_LCN, len, false))
return false;
return true;
}
/*
* run_get_entry - Return index-th mapped region.
*/
bool run_get_entry(const struct runs_tree *run, size_t index, CLST *vcn,
CLST *lcn, CLST *len)
{
const struct ntfs_run *r;
if (index >= run->count)
return false;
r = run->runs + index;
if (!r->len)
return false;
if (vcn)
*vcn = r->vcn;
if (lcn)
*lcn = r->lcn;
if (len)
*len = r->len;
return true;
}
/*
* run_packed_size - Calculate the size of packed int64.
*/
#ifdef __BIG_ENDIAN
static inline int run_packed_size(const s64 n)
{
const u8 *p = (const u8 *)&n + sizeof(n) - 1;
if (n >= 0) {
if (p[-7] || p[-6] || p[-5] || p[-4])
p -= 4;
if (p[-3] || p[-2])
p -= 2;
if (p[-1])
p -= 1;
if (p[0] & 0x80)
p -= 1;
} else {
if (p[-7] != 0xff || p[-6] != 0xff || p[-5] != 0xff ||
p[-4] != 0xff)
p -= 4;
if (p[-3] != 0xff || p[-2] != 0xff)
p -= 2;
if (p[-1] != 0xff)
p -= 1;
if (!(p[0] & 0x80))
p -= 1;
}
return (const u8 *)&n + sizeof(n) - p;
}
/* Full trusted function. It does not check 'size' for errors. */
static inline void run_pack_s64(u8 *run_buf, u8 size, s64 v)
{
const u8 *p = (u8 *)&v;
switch (size) {
case 8:
run_buf[7] = p[0];
fallthrough;
case 7:
run_buf[6] = p[1];
fallthrough;
case 6:
run_buf[5] = p[2];
fallthrough;
case 5:
run_buf[4] = p[3];
fallthrough;
case 4:
run_buf[3] = p[4];
fallthrough;
case 3:
run_buf[2] = p[5];
fallthrough;
case 2:
run_buf[1] = p[6];
fallthrough;
case 1:
run_buf[0] = p[7];
}
}
/* Full trusted function. It does not check 'size' for errors. */
static inline s64 run_unpack_s64(const u8 *run_buf, u8 size, s64 v)
{
u8 *p = (u8 *)&v;
switch (size) {
case 8:
p[0] = run_buf[7];
fallthrough;
case 7:
p[1] = run_buf[6];
fallthrough;
case 6:
p[2] = run_buf[5];
fallthrough;
case 5:
p[3] = run_buf[4];
fallthrough;
case 4:
p[4] = run_buf[3];
fallthrough;
case 3:
p[5] = run_buf[2];
fallthrough;
case 2:
p[6] = run_buf[1];
fallthrough;
case 1:
p[7] = run_buf[0];
}
return v;
}
#else
static inline int run_packed_size(const s64 n)
{
const u8 *p = (const u8 *)&n;
if (n >= 0) {
if (p[7] || p[6] || p[5] || p[4])
p += 4;
if (p[3] || p[2])
p += 2;
if (p[1])
p += 1;
if (p[0] & 0x80)
p += 1;
} else {
if (p[7] != 0xff || p[6] != 0xff || p[5] != 0xff ||
p[4] != 0xff)
p += 4;
if (p[3] != 0xff || p[2] != 0xff)
p += 2;
if (p[1] != 0xff)
p += 1;
if (!(p[0] & 0x80))
p += 1;
}
return 1 + p - (const u8 *)&n;
}
/* Full trusted function. It does not check 'size' for errors. */
static inline void run_pack_s64(u8 *run_buf, u8 size, s64 v)
{
const u8 *p = (u8 *)&v;
/* memcpy( run_buf, &v, size); Is it faster? */
switch (size) {
case 8:
run_buf[7] = p[7];
fallthrough;
case 7:
run_buf[6] = p[6];
fallthrough;
case 6:
run_buf[5] = p[5];
fallthrough;
case 5:
run_buf[4] = p[4];
fallthrough;
case 4:
run_buf[3] = p[3];
fallthrough;
case 3:
run_buf[2] = p[2];
fallthrough;
case 2:
run_buf[1] = p[1];
fallthrough;
case 1:
run_buf[0] = p[0];
}
}
/* full trusted function. It does not check 'size' for errors */
static inline s64 run_unpack_s64(const u8 *run_buf, u8 size, s64 v)
{
u8 *p = (u8 *)&v;
/* memcpy( &v, run_buf, size); Is it faster? */
switch (size) {
case 8:
p[7] = run_buf[7];
fallthrough;
case 7:
p[6] = run_buf[6];
fallthrough;
case 6:
p[5] = run_buf[5];
fallthrough;
case 5:
p[4] = run_buf[4];
fallthrough;
case 4:
p[3] = run_buf[3];
fallthrough;
case 3:
p[2] = run_buf[2];
fallthrough;
case 2:
p[1] = run_buf[1];
fallthrough;
case 1:
p[0] = run_buf[0];
}
return v;
}
#endif
/*
* run_pack - Pack runs into buffer.
*
* packed_vcns - How much runs we have packed.
* packed_size - How much bytes we have used run_buf.
*/
int run_pack(const struct runs_tree *run, CLST svcn, CLST len, u8 *run_buf,
u32 run_buf_size, CLST *packed_vcns)
{
CLST next_vcn, vcn, lcn;
CLST prev_lcn = 0;
CLST evcn1 = svcn + len;
const struct ntfs_run *r, *r_end;
int packed_size = 0;
size_t i;
s64 dlcn;
int offset_size, size_size, tmp;
*packed_vcns = 0;
if (!len)
goto out;
/* Check all required entries [svcn, encv1) available. */
if (!run_lookup(run, svcn, &i))
return -ENOENT;
r_end = run->runs + run->count;
r = run->runs + i;
for (next_vcn = r->vcn + r->len; next_vcn < evcn1;
next_vcn = r->vcn + r->len) {
if (++r >= r_end || r->vcn != next_vcn)
return -ENOENT;
}
/* Repeat cycle above and pack runs. Assume no errors. */
r = run->runs + i;
len = svcn - r->vcn;
vcn = svcn;
lcn = r->lcn == SPARSE_LCN ? SPARSE_LCN : (r->lcn + len);
len = r->len - len;
for (;;) {
next_vcn = vcn + len;
if (next_vcn > evcn1)
len = evcn1 - vcn;
/* How much bytes required to pack len. */
size_size = run_packed_size(len);
/* offset_size - How much bytes is packed dlcn. */
if (lcn == SPARSE_LCN) {
offset_size = 0;
dlcn = 0;
} else {
/* NOTE: lcn can be less than prev_lcn! */
dlcn = (s64)lcn - prev_lcn;
offset_size = run_packed_size(dlcn);
prev_lcn = lcn;
}
tmp = run_buf_size - packed_size - 2 - offset_size;
if (tmp <= 0)
goto out;
/* Can we store this entire run. */
if (tmp < size_size)
goto out;
if (run_buf) {
/* Pack run header. */
run_buf[0] = ((u8)(size_size | (offset_size << 4)));
run_buf += 1;
/* Pack the length of run. */
run_pack_s64(run_buf, size_size, len);
run_buf += size_size;
/* Pack the offset from previous LCN. */
run_pack_s64(run_buf, offset_size, dlcn);
run_buf += offset_size;
}
packed_size += 1 + offset_size + size_size;
*packed_vcns += len;
if (packed_size + 1 >= run_buf_size || next_vcn >= evcn1)
goto out;
r += 1;
vcn = r->vcn;
lcn = r->lcn;
len = r->len;
}
out:
/* Store last zero. */
if (run_buf)
run_buf[0] = 0;
return packed_size + 1;
}
/*
* run_unpack - Unpack packed runs from @run_buf.
*
* Return: Error if negative, or real used bytes.
*/
int run_unpack(struct runs_tree *run, struct ntfs_sb_info *sbi, CLST ino,
CLST svcn, CLST evcn, CLST vcn, const u8 *run_buf,
int run_buf_size)
{
u64 prev_lcn, vcn64, lcn, next_vcn;
const u8 *run_last, *run_0;
bool is_mft = ino == MFT_REC_MFT;
if (run_buf_size < 0)
return -EINVAL;
/* Check for empty. */
if (evcn + 1 == svcn)
return 0;
if (evcn < svcn)
return -EINVAL;
run_0 = run_buf;
run_last = run_buf + run_buf_size;
prev_lcn = 0;
vcn64 = svcn;
/* Read all runs the chain. */
/* size_size - How much bytes is packed len. */
while (run_buf < run_last) {
/* size_size - How much bytes is packed len. */
u8 size_size = *run_buf & 0xF;
/* offset_size - How much bytes is packed dlcn. */
u8 offset_size = *run_buf++ >> 4;
u64 len;
if (!size_size)
break;
/*
* Unpack runs.
* NOTE: Runs are stored little endian order
* "len" is unsigned value, "dlcn" is signed.
* Large positive number requires to store 5 bytes
* e.g.: 05 FF 7E FF FF 00 00 00
*/
if (size_size > 8)
return -EINVAL;
len = run_unpack_s64(run_buf, size_size, 0);
/* Skip size_size. */
run_buf += size_size;
if (!len)
return -EINVAL;
if (!offset_size)
lcn = SPARSE_LCN64;
else if (offset_size <= 8) {
s64 dlcn;
/* Initial value of dlcn is -1 or 0. */
dlcn = (run_buf[offset_size - 1] & 0x80) ? (s64)-1 : 0;
dlcn = run_unpack_s64(run_buf, offset_size, dlcn);
/* Skip offset_size. */
run_buf += offset_size;
if (!dlcn)
return -EINVAL;
lcn = prev_lcn + dlcn;
prev_lcn = lcn;
} else
return -EINVAL;
next_vcn = vcn64 + len;
/* Check boundary. */
if (next_vcn > evcn + 1)
return -EINVAL;
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
if (next_vcn > 0x100000000ull || (lcn + len) > 0x100000000ull) {
ntfs_err(
sbi->sb,
"This driver is compiled without CONFIG_NTFS3_64BIT_CLUSTER (like windows driver).\n"
"Volume contains 64 bits run: vcn %llx, lcn %llx, len %llx.\n"
"Activate CONFIG_NTFS3_64BIT_CLUSTER to process this case",
vcn64, lcn, len);
return -EOPNOTSUPP;
}
#endif
if (lcn != SPARSE_LCN64 && lcn + len > sbi->used.bitmap.nbits) {
/* LCN range is out of volume. */
return -EINVAL;
}
if (!run)
; /* Called from check_attr(fslog.c) to check run. */
else if (run == RUN_DEALLOCATE) {
/*
* Called from ni_delete_all to free clusters
* without storing in run.
*/
if (lcn != SPARSE_LCN64)
mark_as_free_ex(sbi, lcn, len, true);
} else if (vcn64 >= vcn) {
if (!run_add_entry(run, vcn64, lcn, len, is_mft))
return -ENOMEM;
} else if (next_vcn > vcn) {
u64 dlen = vcn - vcn64;
if (!run_add_entry(run, vcn, lcn + dlen, len - dlen,
is_mft))
return -ENOMEM;
}
vcn64 = next_vcn;
}
if (vcn64 != evcn + 1) {
/* Not expected length of unpacked runs. */
return -EINVAL;
}
return run_buf - run_0;
}
#ifdef NTFS3_CHECK_FREE_CLST
/*
* run_unpack_ex - Unpack packed runs from "run_buf".
*
* Checks unpacked runs to be used in bitmap.
*
* Return: Error if negative, or real used bytes.
*/
int run_unpack_ex(struct runs_tree *run, struct ntfs_sb_info *sbi, CLST ino,
CLST svcn, CLST evcn, CLST vcn, const u8 *run_buf,
int run_buf_size)
{
int ret, err;
CLST next_vcn, lcn, len;
size_t index;
bool ok;
struct wnd_bitmap *wnd;
ret = run_unpack(run, sbi, ino, svcn, evcn, vcn, run_buf, run_buf_size);
if (ret <= 0)
return ret;
if (!sbi->used.bitmap.sb || !run || run == RUN_DEALLOCATE)
return ret;
if (ino == MFT_REC_BADCLUST)
return ret;
next_vcn = vcn = svcn;
wnd = &sbi->used.bitmap;
for (ok = run_lookup_entry(run, vcn, &lcn, &len, &index);
next_vcn <= evcn;
ok = run_get_entry(run, ++index, &vcn, &lcn, &len)) {
if (!ok || next_vcn != vcn)
return -EINVAL;
next_vcn = vcn + len;
if (lcn == SPARSE_LCN)
continue;
if (sbi->flags & NTFS_FLAGS_NEED_REPLAY)
continue;
down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
/* Check for free blocks. */
ok = wnd_is_used(wnd, lcn, len);
up_read(&wnd->rw_lock);
if (ok)
continue;
/* Looks like volume is corrupted. */
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
if (down_write_trylock(&wnd->rw_lock)) {
/* Mark all zero bits as used in range [lcn, lcn+len). */
size_t done;
err = wnd_set_used_safe(wnd, lcn, len, &done);
up_write(&wnd->rw_lock);
if (err)
return err;
}
}
return ret;
}
#endif
/*
* run_get_highest_vcn
*
* Return the highest vcn from a mapping pairs array
* it used while replaying log file.
*/
int run_get_highest_vcn(CLST vcn, const u8 *run_buf, u64 *highest_vcn)
{
u64 vcn64 = vcn;
u8 size_size;
while ((size_size = *run_buf & 0xF)) {
u8 offset_size = *run_buf++ >> 4;
u64 len;
if (size_size > 8 || offset_size > 8)
return -EINVAL;
len = run_unpack_s64(run_buf, size_size, 0);
if (!len)
return -EINVAL;
run_buf += size_size + offset_size;
vcn64 += len;
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
if (vcn64 > 0x100000000ull)
return -EINVAL;
#endif
}
*highest_vcn = vcn64 - 1;
return 0;
}
/*
* run_clone
*
* Make a copy of run
*/
int run_clone(const struct runs_tree *run, struct runs_tree *new_run)
{
size_t bytes = run->count * sizeof(struct ntfs_run);
if (bytes > new_run->allocated) {
struct ntfs_run *new_ptr = kvmalloc(bytes, GFP_KERNEL);
if (!new_ptr)
return -ENOMEM;
kvfree(new_run->runs);
new_run->runs = new_ptr;
new_run->allocated = bytes;
}
memcpy(new_run->runs, run->runs, bytes);
new_run->count = run->count;
return 0;
}
| linux-master | fs/ntfs3/run.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/fs.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* al_is_valid_le
*
* Return: True if @le is valid.
*/
static inline bool al_is_valid_le(const struct ntfs_inode *ni,
struct ATTR_LIST_ENTRY *le)
{
if (!le || !ni->attr_list.le || !ni->attr_list.size)
return false;
return PtrOffset(ni->attr_list.le, le) + le16_to_cpu(le->size) <=
ni->attr_list.size;
}
void al_destroy(struct ntfs_inode *ni)
{
run_close(&ni->attr_list.run);
kfree(ni->attr_list.le);
ni->attr_list.le = NULL;
ni->attr_list.size = 0;
ni->attr_list.dirty = false;
}
/*
* ntfs_load_attr_list
*
* This method makes sure that the ATTRIB list, if present,
* has been properly set up.
*/
int ntfs_load_attr_list(struct ntfs_inode *ni, struct ATTRIB *attr)
{
int err;
size_t lsize;
void *le = NULL;
if (ni->attr_list.size)
return 0;
if (!attr->non_res) {
lsize = le32_to_cpu(attr->res.data_size);
le = kmalloc(al_aligned(lsize), GFP_NOFS | __GFP_NOWARN);
if (!le) {
err = -ENOMEM;
goto out;
}
memcpy(le, resident_data(attr), lsize);
} else if (attr->nres.svcn) {
err = -EINVAL;
goto out;
} else {
u16 run_off = le16_to_cpu(attr->nres.run_off);
lsize = le64_to_cpu(attr->nres.data_size);
run_init(&ni->attr_list.run);
if (run_off > le32_to_cpu(attr->size)) {
err = -EINVAL;
goto out;
}
err = run_unpack_ex(&ni->attr_list.run, ni->mi.sbi, ni->mi.rno,
0, le64_to_cpu(attr->nres.evcn), 0,
Add2Ptr(attr, run_off),
le32_to_cpu(attr->size) - run_off);
if (err < 0)
goto out;
le = kmalloc(al_aligned(lsize), GFP_NOFS | __GFP_NOWARN);
if (!le) {
err = -ENOMEM;
goto out;
}
err = ntfs_read_run_nb(ni->mi.sbi, &ni->attr_list.run, 0, le,
lsize, NULL);
if (err)
goto out;
}
ni->attr_list.size = lsize;
ni->attr_list.le = le;
return 0;
out:
ni->attr_list.le = le;
al_destroy(ni);
return err;
}
/*
* al_enumerate
*
* Return:
* * The next list le.
* * If @le is NULL then return the first le.
*/
struct ATTR_LIST_ENTRY *al_enumerate(struct ntfs_inode *ni,
struct ATTR_LIST_ENTRY *le)
{
size_t off;
u16 sz;
if (!le) {
le = ni->attr_list.le;
} else {
sz = le16_to_cpu(le->size);
if (sz < sizeof(struct ATTR_LIST_ENTRY)) {
/* Impossible 'cause we should not return such le. */
return NULL;
}
le = Add2Ptr(le, sz);
}
/* Check boundary. */
off = PtrOffset(ni->attr_list.le, le);
if (off + sizeof(struct ATTR_LIST_ENTRY) > ni->attr_list.size) {
/* The regular end of list. */
return NULL;
}
sz = le16_to_cpu(le->size);
/* Check le for errors. */
if (sz < sizeof(struct ATTR_LIST_ENTRY) ||
off + sz > ni->attr_list.size ||
sz < le->name_off + le->name_len * sizeof(short)) {
return NULL;
}
return le;
}
/*
* al_find_le
*
* Find the first le in the list which matches type, name and VCN.
*
* Return: NULL if not found.
*/
struct ATTR_LIST_ENTRY *al_find_le(struct ntfs_inode *ni,
struct ATTR_LIST_ENTRY *le,
const struct ATTRIB *attr)
{
CLST svcn = attr_svcn(attr);
return al_find_ex(ni, le, attr->type, attr_name(attr), attr->name_len,
&svcn);
}
/*
* al_find_ex
*
* Find the first le in the list which matches type, name and VCN.
*
* Return: NULL if not found.
*/
struct ATTR_LIST_ENTRY *al_find_ex(struct ntfs_inode *ni,
struct ATTR_LIST_ENTRY *le,
enum ATTR_TYPE type, const __le16 *name,
u8 name_len, const CLST *vcn)
{
struct ATTR_LIST_ENTRY *ret = NULL;
u32 type_in = le32_to_cpu(type);
while ((le = al_enumerate(ni, le))) {
u64 le_vcn;
int diff = le32_to_cpu(le->type) - type_in;
/* List entries are sorted by type, name and VCN. */
if (diff < 0)
continue;
if (diff > 0)
return ret;
if (le->name_len != name_len)
continue;
le_vcn = le64_to_cpu(le->vcn);
if (!le_vcn) {
/*
* Compare entry names only for entry with vcn == 0.
*/
diff = ntfs_cmp_names(le_name(le), name_len, name,
name_len, ni->mi.sbi->upcase,
true);
if (diff < 0)
continue;
if (diff > 0)
return ret;
}
if (!vcn)
return le;
if (*vcn == le_vcn)
return le;
if (*vcn < le_vcn)
return ret;
ret = le;
}
return ret;
}
/*
* al_find_le_to_insert
*
* Find the first list entry which matches type, name and VCN.
*/
static struct ATTR_LIST_ENTRY *al_find_le_to_insert(struct ntfs_inode *ni,
enum ATTR_TYPE type,
const __le16 *name,
u8 name_len, CLST vcn)
{
struct ATTR_LIST_ENTRY *le = NULL, *prev;
u32 type_in = le32_to_cpu(type);
/* List entries are sorted by type, name and VCN. */
while ((le = al_enumerate(ni, prev = le))) {
int diff = le32_to_cpu(le->type) - type_in;
if (diff < 0)
continue;
if (diff > 0)
return le;
if (!le->vcn) {
/*
* Compare entry names only for entry with vcn == 0.
*/
diff = ntfs_cmp_names(le_name(le), le->name_len, name,
name_len, ni->mi.sbi->upcase,
true);
if (diff < 0)
continue;
if (diff > 0)
return le;
}
if (le64_to_cpu(le->vcn) >= vcn)
return le;
}
return prev ? Add2Ptr(prev, le16_to_cpu(prev->size)) : ni->attr_list.le;
}
/*
* al_add_le
*
* Add an "attribute list entry" to the list.
*/
int al_add_le(struct ntfs_inode *ni, enum ATTR_TYPE type, const __le16 *name,
u8 name_len, CLST svcn, __le16 id, const struct MFT_REF *ref,
struct ATTR_LIST_ENTRY **new_le)
{
int err;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
size_t off;
u16 sz;
size_t asize, new_asize, old_size;
u64 new_size;
typeof(ni->attr_list) *al = &ni->attr_list;
/*
* Compute the size of the new 'le'
*/
sz = le_size(name_len);
old_size = al->size;
new_size = old_size + sz;
asize = al_aligned(old_size);
new_asize = al_aligned(new_size);
/* Scan forward to the point at which the new 'le' should be inserted. */
le = al_find_le_to_insert(ni, type, name, name_len, svcn);
off = PtrOffset(al->le, le);
if (new_size > asize) {
void *ptr = kmalloc(new_asize, GFP_NOFS);
if (!ptr)
return -ENOMEM;
memcpy(ptr, al->le, off);
memcpy(Add2Ptr(ptr, off + sz), le, old_size - off);
le = Add2Ptr(ptr, off);
kfree(al->le);
al->le = ptr;
} else {
memmove(Add2Ptr(le, sz), le, old_size - off);
}
*new_le = le;
al->size = new_size;
le->type = type;
le->size = cpu_to_le16(sz);
le->name_len = name_len;
le->name_off = offsetof(struct ATTR_LIST_ENTRY, name);
le->vcn = cpu_to_le64(svcn);
le->ref = *ref;
le->id = id;
memcpy(le->name, name, sizeof(short) * name_len);
err = attr_set_size(ni, ATTR_LIST, NULL, 0, &al->run, new_size,
&new_size, true, &attr);
if (err) {
/* Undo memmove above. */
memmove(le, Add2Ptr(le, sz), old_size - off);
al->size = old_size;
return err;
}
al->dirty = true;
if (attr && attr->non_res) {
err = ntfs_sb_write_run(ni->mi.sbi, &al->run, 0, al->le,
al->size, 0);
if (err)
return err;
al->dirty = false;
}
return 0;
}
/*
* al_remove_le - Remove @le from attribute list.
*/
bool al_remove_le(struct ntfs_inode *ni, struct ATTR_LIST_ENTRY *le)
{
u16 size;
size_t off;
typeof(ni->attr_list) *al = &ni->attr_list;
if (!al_is_valid_le(ni, le))
return false;
/* Save on stack the size of 'le' */
size = le16_to_cpu(le->size);
off = PtrOffset(al->le, le);
memmove(le, Add2Ptr(le, size), al->size - (off + size));
al->size -= size;
al->dirty = true;
return true;
}
/*
* al_delete_le - Delete first le from the list which matches its parameters.
*/
bool al_delete_le(struct ntfs_inode *ni, enum ATTR_TYPE type, CLST vcn,
const __le16 *name, u8 name_len, const struct MFT_REF *ref)
{
u16 size;
struct ATTR_LIST_ENTRY *le;
size_t off;
typeof(ni->attr_list) *al = &ni->attr_list;
/* Scan forward to the first le that matches the input. */
le = al_find_ex(ni, NULL, type, name, name_len, &vcn);
if (!le)
return false;
off = PtrOffset(al->le, le);
next:
if (off >= al->size)
return false;
if (le->type != type)
return false;
if (le->name_len != name_len)
return false;
if (name_len && ntfs_cmp_names(le_name(le), name_len, name, name_len,
ni->mi.sbi->upcase, true))
return false;
if (le64_to_cpu(le->vcn) != vcn)
return false;
/*
* The caller specified a segment reference, so we have to
* scan through the matching entries until we find that segment
* reference or we run of matching entries.
*/
if (ref && memcmp(ref, &le->ref, sizeof(*ref))) {
off += le16_to_cpu(le->size);
le = Add2Ptr(al->le, off);
goto next;
}
/* Save on stack the size of 'le'. */
size = le16_to_cpu(le->size);
/* Delete the le. */
memmove(le, Add2Ptr(le, size), al->size - (off + size));
al->size -= size;
al->dirty = true;
return true;
}
int al_update(struct ntfs_inode *ni, int sync)
{
int err;
struct ATTRIB *attr;
typeof(ni->attr_list) *al = &ni->attr_list;
if (!al->dirty || !al->size)
return 0;
/*
* Attribute list increased on demand in al_add_le.
* Attribute list decreased here.
*/
err = attr_set_size(ni, ATTR_LIST, NULL, 0, &al->run, al->size, NULL,
false, &attr);
if (err)
goto out;
if (!attr->non_res) {
memcpy(resident_data(attr), al->le, al->size);
} else {
err = ntfs_sb_write_run(ni->mi.sbi, &al->run, 0, al->le,
al->size, sync);
if (err)
goto out;
attr->nres.valid_size = attr->nres.data_size;
}
ni->mi.dirty = true;
al->dirty = false;
out:
return err;
}
| linux-master | fs/ntfs3/attrlist.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
* Directory handling functions for NTFS-based filesystems.
*
*/
#include <linux/fs.h>
#include <linux/nls.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/* Convert little endian UTF-16 to NLS string. */
int ntfs_utf16_to_nls(struct ntfs_sb_info *sbi, const __le16 *name, u32 len,
u8 *buf, int buf_len)
{
int ret, warn;
u8 *op;
struct nls_table *nls = sbi->options->nls;
static_assert(sizeof(wchar_t) == sizeof(__le16));
if (!nls) {
/* UTF-16 -> UTF-8 */
ret = utf16s_to_utf8s((wchar_t *)name, len, UTF16_LITTLE_ENDIAN,
buf, buf_len);
buf[ret] = '\0';
return ret;
}
op = buf;
warn = 0;
while (len--) {
u16 ec;
int charlen;
char dump[5];
if (buf_len < NLS_MAX_CHARSET_SIZE) {
ntfs_warn(sbi->sb,
"filename was truncated while converting.");
break;
}
ec = le16_to_cpu(*name++);
charlen = nls->uni2char(ec, op, buf_len);
if (charlen > 0) {
op += charlen;
buf_len -= charlen;
continue;
}
*op++ = '_';
buf_len -= 1;
if (warn)
continue;
warn = 1;
hex_byte_pack(&dump[0], ec >> 8);
hex_byte_pack(&dump[2], ec);
dump[4] = 0;
ntfs_err(sbi->sb, "failed to convert \"%s\" to %s", dump,
nls->charset);
}
*op = '\0';
return op - buf;
}
// clang-format off
#define PLANE_SIZE 0x00010000
#define SURROGATE_PAIR 0x0000d800
#define SURROGATE_LOW 0x00000400
#define SURROGATE_BITS 0x000003ff
// clang-format on
/*
* put_utf16 - Modified version of put_utf16 from fs/nls/nls_base.c
*
* Function is sparse warnings free.
*/
static inline void put_utf16(wchar_t *s, unsigned int c,
enum utf16_endian endian)
{
static_assert(sizeof(wchar_t) == sizeof(__le16));
static_assert(sizeof(wchar_t) == sizeof(__be16));
switch (endian) {
default:
*s = (wchar_t)c;
break;
case UTF16_LITTLE_ENDIAN:
*(__le16 *)s = __cpu_to_le16(c);
break;
case UTF16_BIG_ENDIAN:
*(__be16 *)s = __cpu_to_be16(c);
break;
}
}
/*
* _utf8s_to_utf16s
*
* Modified version of 'utf8s_to_utf16s' allows to
* detect -ENAMETOOLONG without writing out of expected maximum.
*/
static int _utf8s_to_utf16s(const u8 *s, int inlen, enum utf16_endian endian,
wchar_t *pwcs, int maxout)
{
u16 *op;
int size;
unicode_t u;
op = pwcs;
while (inlen > 0 && *s) {
if (*s & 0x80) {
size = utf8_to_utf32(s, inlen, &u);
if (size < 0)
return -EINVAL;
s += size;
inlen -= size;
if (u >= PLANE_SIZE) {
if (maxout < 2)
return -ENAMETOOLONG;
u -= PLANE_SIZE;
put_utf16(op++,
SURROGATE_PAIR |
((u >> 10) & SURROGATE_BITS),
endian);
put_utf16(op++,
SURROGATE_PAIR | SURROGATE_LOW |
(u & SURROGATE_BITS),
endian);
maxout -= 2;
} else {
if (maxout < 1)
return -ENAMETOOLONG;
put_utf16(op++, u, endian);
maxout--;
}
} else {
if (maxout < 1)
return -ENAMETOOLONG;
put_utf16(op++, *s++, endian);
inlen--;
maxout--;
}
}
return op - pwcs;
}
/*
* ntfs_nls_to_utf16 - Convert input string to UTF-16.
* @name: Input name.
* @name_len: Input name length.
* @uni: Destination memory.
* @max_ulen: Destination memory.
* @endian: Endian of target UTF-16 string.
*
* This function is called:
* - to create NTFS name
* - to create symlink
*
* Return: UTF-16 string length or error (if negative).
*/
int ntfs_nls_to_utf16(struct ntfs_sb_info *sbi, const u8 *name, u32 name_len,
struct cpu_str *uni, u32 max_ulen,
enum utf16_endian endian)
{
int ret, slen;
const u8 *end;
struct nls_table *nls = sbi->options->nls;
u16 *uname = uni->name;
static_assert(sizeof(wchar_t) == sizeof(u16));
if (!nls) {
/* utf8 -> utf16 */
ret = _utf8s_to_utf16s(name, name_len, endian, uname, max_ulen);
uni->len = ret;
return ret;
}
for (ret = 0, end = name + name_len; name < end; ret++, name += slen) {
if (ret >= max_ulen)
return -ENAMETOOLONG;
slen = nls->char2uni(name, end - name, uname + ret);
if (!slen)
return -EINVAL;
if (slen < 0)
return slen;
}
#ifdef __BIG_ENDIAN
if (endian == UTF16_LITTLE_ENDIAN) {
int i = ret;
while (i--) {
__cpu_to_le16s(uname);
uname++;
}
}
#else
if (endian == UTF16_BIG_ENDIAN) {
int i = ret;
while (i--) {
__cpu_to_be16s(uname);
uname++;
}
}
#endif
uni->len = ret;
return ret;
}
/*
* dir_search_u - Helper function.
*/
struct inode *dir_search_u(struct inode *dir, const struct cpu_str *uni,
struct ntfs_fnd *fnd)
{
int err = 0;
struct super_block *sb = dir->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *ni = ntfs_i(dir);
struct NTFS_DE *e;
int diff;
struct inode *inode = NULL;
struct ntfs_fnd *fnd_a = NULL;
if (!fnd) {
fnd_a = fnd_get();
if (!fnd_a) {
err = -ENOMEM;
goto out;
}
fnd = fnd_a;
}
err = indx_find(&ni->dir, ni, NULL, uni, 0, sbi, &diff, &e, fnd);
if (err)
goto out;
if (diff) {
err = -ENOENT;
goto out;
}
inode = ntfs_iget5(sb, &e->ref, uni);
if (!IS_ERR(inode) && is_bad_inode(inode)) {
iput(inode);
err = -EINVAL;
}
out:
fnd_put(fnd_a);
return err == -ENOENT ? NULL : err ? ERR_PTR(err) : inode;
}
static inline int ntfs_filldir(struct ntfs_sb_info *sbi, struct ntfs_inode *ni,
const struct NTFS_DE *e, u8 *name,
struct dir_context *ctx)
{
const struct ATTR_FILE_NAME *fname;
unsigned long ino;
int name_len;
u32 dt_type;
fname = Add2Ptr(e, sizeof(struct NTFS_DE));
if (fname->type == FILE_NAME_DOS)
return 0;
if (!mi_is_ref(&ni->mi, &fname->home))
return 0;
ino = ino_get(&e->ref);
if (ino == MFT_REC_ROOT)
return 0;
/* Skip meta files. Unless option to show metafiles is set. */
if (!sbi->options->showmeta && ntfs_is_meta_file(sbi, ino))
return 0;
if (sbi->options->nohidden && (fname->dup.fa & FILE_ATTRIBUTE_HIDDEN))
return 0;
name_len = ntfs_utf16_to_nls(sbi, fname->name, fname->name_len, name,
PATH_MAX);
if (name_len <= 0) {
ntfs_warn(sbi->sb, "failed to convert name for inode %lx.",
ino);
return 0;
}
dt_type = (fname->dup.fa & FILE_ATTRIBUTE_DIRECTORY) ? DT_DIR : DT_REG;
return !dir_emit(ctx, (s8 *)name, name_len, ino, dt_type);
}
/*
* ntfs_read_hdr - Helper function for ntfs_readdir().
*/
static int ntfs_read_hdr(struct ntfs_sb_info *sbi, struct ntfs_inode *ni,
const struct INDEX_HDR *hdr, u64 vbo, u64 pos,
u8 *name, struct dir_context *ctx)
{
int err;
const struct NTFS_DE *e;
u32 e_size;
u32 end = le32_to_cpu(hdr->used);
u32 off = le32_to_cpu(hdr->de_off);
for (;; off += e_size) {
if (off + sizeof(struct NTFS_DE) > end)
return -1;
e = Add2Ptr(hdr, off);
e_size = le16_to_cpu(e->size);
if (e_size < sizeof(struct NTFS_DE) || off + e_size > end)
return -1;
if (de_is_last(e))
return 0;
/* Skip already enumerated. */
if (vbo + off < pos)
continue;
if (le16_to_cpu(e->key_size) < SIZEOF_ATTRIBUTE_FILENAME)
return -1;
ctx->pos = vbo + off;
/* Submit the name to the filldir callback. */
err = ntfs_filldir(sbi, ni, e, name, ctx);
if (err)
return err;
}
}
/*
* ntfs_readdir - file_operations::iterate_shared
*
* Use non sorted enumeration.
* We have an example of broken volume where sorted enumeration
* counts each name twice.
*/
static int ntfs_readdir(struct file *file, struct dir_context *ctx)
{
const struct INDEX_ROOT *root;
u64 vbo;
size_t bit;
loff_t eod;
int err = 0;
struct inode *dir = file_inode(file);
struct ntfs_inode *ni = ntfs_i(dir);
struct super_block *sb = dir->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
loff_t i_size = i_size_read(dir);
u32 pos = ctx->pos;
u8 *name = NULL;
struct indx_node *node = NULL;
u8 index_bits = ni->dir.index_bits;
/* Name is a buffer of PATH_MAX length. */
static_assert(NTFS_NAME_LEN * 4 < PATH_MAX);
eod = i_size + sbi->record_size;
if (pos >= eod)
return 0;
if (!dir_emit_dots(file, ctx))
return 0;
/* Allocate PATH_MAX bytes. */
name = __getname();
if (!name)
return -ENOMEM;
if (!ni->mi_loaded && ni->attr_list.size) {
/*
* Directory inode is locked for read.
* Load all subrecords to avoid 'write' access to 'ni' during
* directory reading.
*/
ni_lock(ni);
if (!ni->mi_loaded && ni->attr_list.size) {
err = ni_load_all_mi(ni);
if (!err)
ni->mi_loaded = true;
}
ni_unlock(ni);
if (err)
goto out;
}
root = indx_get_root(&ni->dir, ni, NULL, NULL);
if (!root) {
err = -EINVAL;
goto out;
}
if (pos >= sbi->record_size) {
bit = (pos - sbi->record_size) >> index_bits;
} else {
err = ntfs_read_hdr(sbi, ni, &root->ihdr, 0, pos, name, ctx);
if (err)
goto out;
bit = 0;
}
if (!i_size) {
ctx->pos = eod;
goto out;
}
for (;;) {
vbo = (u64)bit << index_bits;
if (vbo >= i_size) {
ctx->pos = eod;
goto out;
}
err = indx_used_bit(&ni->dir, ni, &bit);
if (err)
goto out;
if (bit == MINUS_ONE_T) {
ctx->pos = eod;
goto out;
}
vbo = (u64)bit << index_bits;
if (vbo >= i_size) {
ntfs_inode_err(dir, "Looks like your dir is corrupt");
err = -EINVAL;
goto out;
}
err = indx_read(&ni->dir, ni, bit << ni->dir.idx2vbn_bits,
&node);
if (err)
goto out;
err = ntfs_read_hdr(sbi, ni, &node->index->ihdr,
vbo + sbi->record_size, pos, name, ctx);
if (err)
goto out;
bit += 1;
}
out:
__putname(name);
put_indx_node(node);
if (err == -ENOENT) {
err = 0;
ctx->pos = pos;
}
return err;
}
static int ntfs_dir_count(struct inode *dir, bool *is_empty, size_t *dirs,
size_t *files)
{
int err = 0;
struct ntfs_inode *ni = ntfs_i(dir);
struct NTFS_DE *e = NULL;
struct INDEX_ROOT *root;
struct INDEX_HDR *hdr;
const struct ATTR_FILE_NAME *fname;
u32 e_size, off, end;
u64 vbo = 0;
size_t drs = 0, fles = 0, bit = 0;
loff_t i_size = ni->vfs_inode.i_size;
struct indx_node *node = NULL;
u8 index_bits = ni->dir.index_bits;
if (is_empty)
*is_empty = true;
root = indx_get_root(&ni->dir, ni, NULL, NULL);
if (!root)
return -EINVAL;
hdr = &root->ihdr;
for (;;) {
end = le32_to_cpu(hdr->used);
off = le32_to_cpu(hdr->de_off);
for (; off + sizeof(struct NTFS_DE) <= end; off += e_size) {
e = Add2Ptr(hdr, off);
e_size = le16_to_cpu(e->size);
if (e_size < sizeof(struct NTFS_DE) ||
off + e_size > end)
break;
if (de_is_last(e))
break;
fname = de_get_fname(e);
if (!fname)
continue;
if (fname->type == FILE_NAME_DOS)
continue;
if (is_empty) {
*is_empty = false;
if (!dirs && !files)
goto out;
}
if (fname->dup.fa & FILE_ATTRIBUTE_DIRECTORY)
drs += 1;
else
fles += 1;
}
if (vbo >= i_size)
goto out;
err = indx_used_bit(&ni->dir, ni, &bit);
if (err)
goto out;
if (bit == MINUS_ONE_T)
goto out;
vbo = (u64)bit << index_bits;
if (vbo >= i_size)
goto out;
err = indx_read(&ni->dir, ni, bit << ni->dir.idx2vbn_bits,
&node);
if (err)
goto out;
hdr = &node->index->ihdr;
bit += 1;
vbo = (u64)bit << ni->dir.idx2vbn_bits;
}
out:
put_indx_node(node);
if (dirs)
*dirs = drs;
if (files)
*files = fles;
return err;
}
bool dir_is_empty(struct inode *dir)
{
bool is_empty = false;
ntfs_dir_count(dir, &is_empty, NULL, NULL);
return is_empty;
}
// clang-format off
const struct file_operations ntfs_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.iterate_shared = ntfs_readdir,
.fsync = generic_file_fsync,
.open = ntfs_file_open,
};
// clang-format on
| linux-master | fs/ntfs3/dir.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/buffer_head.h>
#include <linux/fs.h>
#include <linux/mpage.h>
#include <linux/namei.h>
#include <linux/nls.h>
#include <linux/uio.h>
#include <linux/writeback.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* ntfs_read_mft - Read record and parses MFT.
*/
static struct inode *ntfs_read_mft(struct inode *inode,
const struct cpu_str *name,
const struct MFT_REF *ref)
{
int err = 0;
struct ntfs_inode *ni = ntfs_i(inode);
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
mode_t mode = 0;
struct ATTR_STD_INFO5 *std5 = NULL;
struct ATTR_LIST_ENTRY *le;
struct ATTRIB *attr;
bool is_match = false;
bool is_root = false;
bool is_dir;
unsigned long ino = inode->i_ino;
u32 rp_fa = 0, asize, t32;
u16 roff, rsize, names = 0;
const struct ATTR_FILE_NAME *fname = NULL;
const struct INDEX_ROOT *root;
struct REPARSE_DATA_BUFFER rp; // 0x18 bytes
u64 t64;
struct MFT_REC *rec;
struct runs_tree *run;
struct timespec64 ctime;
inode->i_op = NULL;
/* Setup 'uid' and 'gid' */
inode->i_uid = sbi->options->fs_uid;
inode->i_gid = sbi->options->fs_gid;
err = mi_init(&ni->mi, sbi, ino);
if (err)
goto out;
if (!sbi->mft.ni && ino == MFT_REC_MFT && !sb->s_root) {
t64 = sbi->mft.lbo >> sbi->cluster_bits;
t32 = bytes_to_cluster(sbi, MFT_REC_VOL * sbi->record_size);
sbi->mft.ni = ni;
init_rwsem(&ni->file.run_lock);
if (!run_add_entry(&ni->file.run, 0, t64, t32, true)) {
err = -ENOMEM;
goto out;
}
}
err = mi_read(&ni->mi, ino == MFT_REC_MFT);
if (err)
goto out;
rec = ni->mi.mrec;
if (sbi->flags & NTFS_FLAGS_LOG_REPLAYING) {
;
} else if (ref->seq != rec->seq) {
err = -EINVAL;
ntfs_err(sb, "MFT: r=%lx, expect seq=%x instead of %x!", ino,
le16_to_cpu(ref->seq), le16_to_cpu(rec->seq));
goto out;
} else if (!is_rec_inuse(rec)) {
err = -ESTALE;
ntfs_err(sb, "Inode r=%x is not in use!", (u32)ino);
goto out;
}
if (le32_to_cpu(rec->total) != sbi->record_size) {
/* Bad inode? */
err = -EINVAL;
goto out;
}
if (!is_rec_base(rec)) {
err = -EINVAL;
goto out;
}
/* Record should contain $I30 root. */
is_dir = rec->flags & RECORD_FLAG_DIR;
/* MFT_REC_MFT is not a dir */
if (is_dir && ino == MFT_REC_MFT) {
err = -EINVAL;
goto out;
}
inode->i_generation = le16_to_cpu(rec->seq);
/* Enumerate all struct Attributes MFT. */
le = NULL;
attr = NULL;
/*
* To reduce tab pressure use goto instead of
* while( (attr = ni_enum_attr_ex(ni, attr, &le, NULL) ))
*/
next_attr:
run = NULL;
err = -EINVAL;
attr = ni_enum_attr_ex(ni, attr, &le, NULL);
if (!attr)
goto end_enum;
if (le && le->vcn) {
/* This is non primary attribute segment. Ignore if not MFT. */
if (ino != MFT_REC_MFT || attr->type != ATTR_DATA)
goto next_attr;
run = &ni->file.run;
asize = le32_to_cpu(attr->size);
goto attr_unpack_run;
}
roff = attr->non_res ? 0 : le16_to_cpu(attr->res.data_off);
rsize = attr->non_res ? 0 : le32_to_cpu(attr->res.data_size);
asize = le32_to_cpu(attr->size);
/*
* Really this check was done in 'ni_enum_attr_ex' -> ... 'mi_enum_attr'.
* There not critical to check this case again
*/
if (attr->name_len &&
sizeof(short) * attr->name_len + le16_to_cpu(attr->name_off) >
asize)
goto out;
if (attr->non_res) {
t64 = le64_to_cpu(attr->nres.alloc_size);
if (le64_to_cpu(attr->nres.data_size) > t64 ||
le64_to_cpu(attr->nres.valid_size) > t64)
goto out;
}
switch (attr->type) {
case ATTR_STD:
if (attr->non_res ||
asize < sizeof(struct ATTR_STD_INFO) + roff ||
rsize < sizeof(struct ATTR_STD_INFO))
goto out;
if (std5)
goto next_attr;
std5 = Add2Ptr(attr, roff);
#ifdef STATX_BTIME
nt2kernel(std5->cr_time, &ni->i_crtime);
#endif
nt2kernel(std5->a_time, &inode->i_atime);
ctime = inode_get_ctime(inode);
nt2kernel(std5->c_time, &ctime);
nt2kernel(std5->m_time, &inode->i_mtime);
ni->std_fa = std5->fa;
if (asize >= sizeof(struct ATTR_STD_INFO5) + roff &&
rsize >= sizeof(struct ATTR_STD_INFO5))
ni->std_security_id = std5->security_id;
goto next_attr;
case ATTR_LIST:
if (attr->name_len || le || ino == MFT_REC_LOG)
goto out;
err = ntfs_load_attr_list(ni, attr);
if (err)
goto out;
le = NULL;
attr = NULL;
goto next_attr;
case ATTR_NAME:
if (attr->non_res || asize < SIZEOF_ATTRIBUTE_FILENAME + roff ||
rsize < SIZEOF_ATTRIBUTE_FILENAME)
goto out;
fname = Add2Ptr(attr, roff);
if (fname->type == FILE_NAME_DOS)
goto next_attr;
names += 1;
if (name && name->len == fname->name_len &&
!ntfs_cmp_names_cpu(name, (struct le_str *)&fname->name_len,
NULL, false))
is_match = true;
goto next_attr;
case ATTR_DATA:
if (is_dir) {
/* Ignore data attribute in dir record. */
goto next_attr;
}
if (ino == MFT_REC_BADCLUST && !attr->non_res)
goto next_attr;
if (attr->name_len &&
((ino != MFT_REC_BADCLUST || !attr->non_res ||
attr->name_len != ARRAY_SIZE(BAD_NAME) ||
memcmp(attr_name(attr), BAD_NAME, sizeof(BAD_NAME))) &&
(ino != MFT_REC_SECURE || !attr->non_res ||
attr->name_len != ARRAY_SIZE(SDS_NAME) ||
memcmp(attr_name(attr), SDS_NAME, sizeof(SDS_NAME))))) {
/* File contains stream attribute. Ignore it. */
goto next_attr;
}
if (is_attr_sparsed(attr))
ni->std_fa |= FILE_ATTRIBUTE_SPARSE_FILE;
else
ni->std_fa &= ~FILE_ATTRIBUTE_SPARSE_FILE;
if (is_attr_compressed(attr))
ni->std_fa |= FILE_ATTRIBUTE_COMPRESSED;
else
ni->std_fa &= ~FILE_ATTRIBUTE_COMPRESSED;
if (is_attr_encrypted(attr))
ni->std_fa |= FILE_ATTRIBUTE_ENCRYPTED;
else
ni->std_fa &= ~FILE_ATTRIBUTE_ENCRYPTED;
if (!attr->non_res) {
ni->i_valid = inode->i_size = rsize;
inode_set_bytes(inode, rsize);
}
mode = S_IFREG | (0777 & sbi->options->fs_fmask_inv);
if (!attr->non_res) {
ni->ni_flags |= NI_FLAG_RESIDENT;
goto next_attr;
}
inode_set_bytes(inode, attr_ondisk_size(attr));
ni->i_valid = le64_to_cpu(attr->nres.valid_size);
inode->i_size = le64_to_cpu(attr->nres.data_size);
if (!attr->nres.alloc_size)
goto next_attr;
run = ino == MFT_REC_BITMAP ? &sbi->used.bitmap.run :
&ni->file.run;
break;
case ATTR_ROOT:
if (attr->non_res)
goto out;
root = Add2Ptr(attr, roff);
if (attr->name_len != ARRAY_SIZE(I30_NAME) ||
memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME)))
goto next_attr;
if (root->type != ATTR_NAME ||
root->rule != NTFS_COLLATION_TYPE_FILENAME)
goto out;
if (!is_dir)
goto next_attr;
is_root = true;
ni->ni_flags |= NI_FLAG_DIR;
err = indx_init(&ni->dir, sbi, attr, INDEX_MUTEX_I30);
if (err)
goto out;
mode = sb->s_root ?
(S_IFDIR | (0777 & sbi->options->fs_dmask_inv)) :
(S_IFDIR | 0777);
goto next_attr;
case ATTR_ALLOC:
if (!is_root || attr->name_len != ARRAY_SIZE(I30_NAME) ||
memcmp(attr_name(attr), I30_NAME, sizeof(I30_NAME)))
goto next_attr;
inode->i_size = le64_to_cpu(attr->nres.data_size);
ni->i_valid = le64_to_cpu(attr->nres.valid_size);
inode_set_bytes(inode, le64_to_cpu(attr->nres.alloc_size));
run = &ni->dir.alloc_run;
break;
case ATTR_BITMAP:
if (ino == MFT_REC_MFT) {
if (!attr->non_res)
goto out;
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
/* 0x20000000 = 2^32 / 8 */
if (le64_to_cpu(attr->nres.alloc_size) >= 0x20000000)
goto out;
#endif
run = &sbi->mft.bitmap.run;
break;
} else if (is_dir && attr->name_len == ARRAY_SIZE(I30_NAME) &&
!memcmp(attr_name(attr), I30_NAME,
sizeof(I30_NAME)) &&
attr->non_res) {
run = &ni->dir.bitmap_run;
break;
}
goto next_attr;
case ATTR_REPARSE:
if (attr->name_len)
goto next_attr;
rp_fa = ni_parse_reparse(ni, attr, &rp);
switch (rp_fa) {
case REPARSE_LINK:
/*
* Normal symlink.
* Assume one unicode symbol == one utf8.
*/
inode->i_size = le16_to_cpu(rp.SymbolicLinkReparseBuffer
.PrintNameLength) /
sizeof(u16);
ni->i_valid = inode->i_size;
/* Clear directory bit. */
if (ni->ni_flags & NI_FLAG_DIR) {
indx_clear(&ni->dir);
memset(&ni->dir, 0, sizeof(ni->dir));
ni->ni_flags &= ~NI_FLAG_DIR;
} else {
run_close(&ni->file.run);
}
mode = S_IFLNK | 0777;
is_dir = false;
if (attr->non_res) {
run = &ni->file.run;
goto attr_unpack_run; // Double break.
}
break;
case REPARSE_COMPRESSED:
break;
case REPARSE_DEDUPLICATED:
break;
}
goto next_attr;
case ATTR_EA_INFO:
if (!attr->name_len &&
resident_data_ex(attr, sizeof(struct EA_INFO))) {
ni->ni_flags |= NI_FLAG_EA;
/*
* ntfs_get_wsl_perm updates inode->i_uid, inode->i_gid, inode->i_mode
*/
inode->i_mode = mode;
ntfs_get_wsl_perm(inode);
mode = inode->i_mode;
}
goto next_attr;
default:
goto next_attr;
}
attr_unpack_run:
roff = le16_to_cpu(attr->nres.run_off);
if (roff > asize) {
err = -EINVAL;
goto out;
}
t64 = le64_to_cpu(attr->nres.svcn);
err = run_unpack_ex(run, sbi, ino, t64, le64_to_cpu(attr->nres.evcn),
t64, Add2Ptr(attr, roff), asize - roff);
if (err < 0)
goto out;
err = 0;
goto next_attr;
end_enum:
if (!std5)
goto out;
if (!is_match && name) {
/* Reuse rec as buffer for ascii name. */
err = -ENOENT;
goto out;
}
if (std5->fa & FILE_ATTRIBUTE_READONLY)
mode &= ~0222;
if (!names) {
err = -EINVAL;
goto out;
}
if (names != le16_to_cpu(rec->hard_links)) {
/* Correct minor error on the fly. Do not mark inode as dirty. */
rec->hard_links = cpu_to_le16(names);
ni->mi.dirty = true;
}
set_nlink(inode, names);
if (S_ISDIR(mode)) {
ni->std_fa |= FILE_ATTRIBUTE_DIRECTORY;
/*
* Dot and dot-dot should be included in count but was not
* included in enumeration.
* Usually a hard links to directories are disabled.
*/
inode->i_op = &ntfs_dir_inode_operations;
inode->i_fop = &ntfs_dir_operations;
ni->i_valid = 0;
} else if (S_ISLNK(mode)) {
ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY;
inode->i_op = &ntfs_link_inode_operations;
inode->i_fop = NULL;
inode_nohighmem(inode);
} else if (S_ISREG(mode)) {
ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY;
inode->i_op = &ntfs_file_inode_operations;
inode->i_fop = &ntfs_file_operations;
inode->i_mapping->a_ops = is_compressed(ni) ? &ntfs_aops_cmpr :
&ntfs_aops;
if (ino != MFT_REC_MFT)
init_rwsem(&ni->file.run_lock);
} else if (S_ISCHR(mode) || S_ISBLK(mode) || S_ISFIFO(mode) ||
S_ISSOCK(mode)) {
inode->i_op = &ntfs_special_inode_operations;
init_special_inode(inode, mode, inode->i_rdev);
} else if (fname && fname->home.low == cpu_to_le32(MFT_REC_EXTEND) &&
fname->home.seq == cpu_to_le16(MFT_REC_EXTEND)) {
/* Records in $Extend are not a files or general directories. */
inode->i_op = &ntfs_file_inode_operations;
} else {
err = -EINVAL;
goto out;
}
if ((sbi->options->sys_immutable &&
(std5->fa & FILE_ATTRIBUTE_SYSTEM)) &&
!S_ISFIFO(mode) && !S_ISSOCK(mode) && !S_ISLNK(mode)) {
inode->i_flags |= S_IMMUTABLE;
} else {
inode->i_flags &= ~S_IMMUTABLE;
}
inode->i_mode = mode;
if (!(ni->ni_flags & NI_FLAG_EA)) {
/* If no xattr then no security (stored in xattr). */
inode->i_flags |= S_NOSEC;
}
if (ino == MFT_REC_MFT && !sb->s_root)
sbi->mft.ni = NULL;
unlock_new_inode(inode);
return inode;
out:
if (ino == MFT_REC_MFT && !sb->s_root)
sbi->mft.ni = NULL;
iget_failed(inode);
return ERR_PTR(err);
}
/*
* ntfs_test_inode
*
* Return: 1 if match.
*/
static int ntfs_test_inode(struct inode *inode, void *data)
{
struct MFT_REF *ref = data;
return ino_get(ref) == inode->i_ino;
}
static int ntfs_set_inode(struct inode *inode, void *data)
{
const struct MFT_REF *ref = data;
inode->i_ino = ino_get(ref);
return 0;
}
struct inode *ntfs_iget5(struct super_block *sb, const struct MFT_REF *ref,
const struct cpu_str *name)
{
struct inode *inode;
inode = iget5_locked(sb, ino_get(ref), ntfs_test_inode, ntfs_set_inode,
(void *)ref);
if (unlikely(!inode))
return ERR_PTR(-ENOMEM);
/* If this is a freshly allocated inode, need to read it now. */
if (inode->i_state & I_NEW)
inode = ntfs_read_mft(inode, name, ref);
else if (ref->seq != ntfs_i(inode)->mi.mrec->seq) {
/* Inode overlaps? */
_ntfs_bad_inode(inode);
}
if (IS_ERR(inode) && name)
ntfs_set_state(sb->s_fs_info, NTFS_DIRTY_ERROR);
return inode;
}
enum get_block_ctx {
GET_BLOCK_GENERAL = 0,
GET_BLOCK_WRITE_BEGIN = 1,
GET_BLOCK_DIRECT_IO_R = 2,
GET_BLOCK_DIRECT_IO_W = 3,
GET_BLOCK_BMAP = 4,
};
static noinline int ntfs_get_block_vbo(struct inode *inode, u64 vbo,
struct buffer_head *bh, int create,
enum get_block_ctx ctx)
{
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *ni = ntfs_i(inode);
struct folio *folio = bh->b_folio;
u8 cluster_bits = sbi->cluster_bits;
u32 block_size = sb->s_blocksize;
u64 bytes, lbo, valid;
u32 off;
int err;
CLST vcn, lcn, len;
bool new;
/* Clear previous state. */
clear_buffer_new(bh);
clear_buffer_uptodate(bh);
if (is_resident(ni)) {
ni_lock(ni);
err = attr_data_read_resident(ni, &folio->page);
ni_unlock(ni);
if (!err)
set_buffer_uptodate(bh);
bh->b_size = block_size;
return err;
}
vcn = vbo >> cluster_bits;
off = vbo & sbi->cluster_mask;
new = false;
err = attr_data_get_block(ni, vcn, 1, &lcn, &len, create ? &new : NULL,
create && sbi->cluster_size > PAGE_SIZE);
if (err)
goto out;
if (!len)
return 0;
bytes = ((u64)len << cluster_bits) - off;
if (lcn == SPARSE_LCN) {
if (!create) {
if (bh->b_size > bytes)
bh->b_size = bytes;
return 0;
}
WARN_ON(1);
}
if (new)
set_buffer_new(bh);
lbo = ((u64)lcn << cluster_bits) + off;
set_buffer_mapped(bh);
bh->b_bdev = sb->s_bdev;
bh->b_blocknr = lbo >> sb->s_blocksize_bits;
valid = ni->i_valid;
if (ctx == GET_BLOCK_DIRECT_IO_W) {
/* ntfs_direct_IO will update ni->i_valid. */
if (vbo >= valid)
set_buffer_new(bh);
} else if (create) {
/* Normal write. */
if (bytes > bh->b_size)
bytes = bh->b_size;
if (vbo >= valid)
set_buffer_new(bh);
if (vbo + bytes > valid) {
ni->i_valid = vbo + bytes;
mark_inode_dirty(inode);
}
} else if (vbo >= valid) {
/* Read out of valid data. */
clear_buffer_mapped(bh);
} else if (vbo + bytes <= valid) {
/* Normal read. */
} else if (vbo + block_size <= valid) {
/* Normal short read. */
bytes = block_size;
} else {
/*
* Read across valid size: vbo < valid && valid < vbo + block_size
*/
bytes = block_size;
if (folio) {
u32 voff = valid - vbo;
bh->b_size = block_size;
off = vbo & (PAGE_SIZE - 1);
folio_set_bh(bh, folio, off);
err = bh_read(bh, 0);
if (err < 0)
goto out;
folio_zero_segment(folio, off + voff, off + block_size);
}
}
if (bh->b_size > bytes)
bh->b_size = bytes;
#ifndef __LP64__
if (ctx == GET_BLOCK_DIRECT_IO_W || ctx == GET_BLOCK_DIRECT_IO_R) {
static_assert(sizeof(size_t) < sizeof(loff_t));
if (bytes > 0x40000000u)
bh->b_size = 0x40000000u;
}
#endif
return 0;
out:
return err;
}
int ntfs_get_block(struct inode *inode, sector_t vbn,
struct buffer_head *bh_result, int create)
{
return ntfs_get_block_vbo(inode, (u64)vbn << inode->i_blkbits,
bh_result, create, GET_BLOCK_GENERAL);
}
static int ntfs_get_block_bmap(struct inode *inode, sector_t vsn,
struct buffer_head *bh_result, int create)
{
return ntfs_get_block_vbo(inode,
(u64)vsn << inode->i_sb->s_blocksize_bits,
bh_result, create, GET_BLOCK_BMAP);
}
static sector_t ntfs_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping, block, ntfs_get_block_bmap);
}
static int ntfs_read_folio(struct file *file, struct folio *folio)
{
struct page *page = &folio->page;
int err;
struct address_space *mapping = page->mapping;
struct inode *inode = mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
if (is_resident(ni)) {
ni_lock(ni);
err = attr_data_read_resident(ni, page);
ni_unlock(ni);
if (err != E_NTFS_NONRESIDENT) {
unlock_page(page);
return err;
}
}
if (is_compressed(ni)) {
ni_lock(ni);
err = ni_readpage_cmpr(ni, page);
ni_unlock(ni);
return err;
}
/* Normal + sparse files. */
return mpage_read_folio(folio, ntfs_get_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);
u64 valid;
loff_t pos;
if (is_resident(ni)) {
/* No readahead for resident. */
return;
}
if (is_compressed(ni)) {
/* No readahead for compressed. */
return;
}
valid = ni->i_valid;
pos = readahead_pos(rac);
if (valid < i_size_read(inode) && pos <= valid &&
valid < pos + readahead_length(rac)) {
/* Range cross 'valid'. Read it page by page. */
return;
}
mpage_readahead(rac, ntfs_get_block);
}
static int ntfs_get_block_direct_IO_R(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
return ntfs_get_block_vbo(inode, (u64)iblock << inode->i_blkbits,
bh_result, create, GET_BLOCK_DIRECT_IO_R);
}
static int ntfs_get_block_direct_IO_W(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
return ntfs_get_block_vbo(inode, (u64)iblock << inode->i_blkbits,
bh_result, create, GET_BLOCK_DIRECT_IO_W);
}
static ssize_t ntfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
loff_t vbo = iocb->ki_pos;
loff_t end;
int wr = iov_iter_rw(iter) & WRITE;
size_t iter_count = iov_iter_count(iter);
loff_t valid;
ssize_t ret;
if (is_resident(ni)) {
/* Switch to buffered write. */
ret = 0;
goto out;
}
ret = blockdev_direct_IO(iocb, inode, iter,
wr ? ntfs_get_block_direct_IO_W :
ntfs_get_block_direct_IO_R);
if (ret > 0)
end = vbo + ret;
else if (wr && ret == -EIOCBQUEUED)
end = vbo + iter_count;
else
goto out;
valid = ni->i_valid;
if (wr) {
if (end > valid && !S_ISBLK(inode->i_mode)) {
ni->i_valid = end;
mark_inode_dirty(inode);
}
} else if (vbo < valid && valid < end) {
/* Fix page. */
iov_iter_revert(iter, end - valid);
iov_iter_zero(end - valid, iter);
}
out:
return ret;
}
int ntfs_set_size(struct inode *inode, u64 new_size)
{
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *ni = ntfs_i(inode);
int err;
/* Check for maximum file size. */
if (is_sparsed(ni) || is_compressed(ni)) {
if (new_size > sbi->maxbytes_sparse) {
err = -EFBIG;
goto out;
}
} else if (new_size > sbi->maxbytes) {
err = -EFBIG;
goto out;
}
ni_lock(ni);
down_write(&ni->file.run_lock);
err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run, new_size,
&ni->i_valid, true, NULL);
up_write(&ni->file.run_lock);
ni_unlock(ni);
mark_inode_dirty(inode);
out:
return err;
}
static int ntfs_resident_writepage(struct folio *folio,
struct writeback_control *wbc, void *data)
{
struct address_space *mapping = data;
struct ntfs_inode *ni = ntfs_i(mapping->host);
int ret;
ni_lock(ni);
ret = attr_data_write_resident(ni, &folio->page);
ni_unlock(ni);
if (ret != E_NTFS_NONRESIDENT)
folio_unlock(folio);
mapping_set_error(mapping, ret);
return ret;
}
static int ntfs_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
if (is_resident(ntfs_i(mapping->host)))
return write_cache_pages(mapping, wbc, ntfs_resident_writepage,
mapping);
return mpage_writepages(mapping, wbc, ntfs_get_block);
}
static int ntfs_get_block_write_begin(struct inode *inode, sector_t vbn,
struct buffer_head *bh_result, int create)
{
return ntfs_get_block_vbo(inode, (u64)vbn << inode->i_blkbits,
bh_result, create, GET_BLOCK_WRITE_BEGIN);
}
int ntfs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, u32 len, struct page **pagep, void **fsdata)
{
int err;
struct inode *inode = mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
*pagep = NULL;
if (is_resident(ni)) {
struct page *page =
grab_cache_page_write_begin(mapping, pos >> PAGE_SHIFT);
if (!page) {
err = -ENOMEM;
goto out;
}
ni_lock(ni);
err = attr_data_read_resident(ni, page);
ni_unlock(ni);
if (!err) {
*pagep = page;
goto out;
}
unlock_page(page);
put_page(page);
if (err != E_NTFS_NONRESIDENT)
goto out;
}
err = block_write_begin(mapping, pos, len, pagep,
ntfs_get_block_write_begin);
out:
return err;
}
/*
* ntfs_write_end - Address_space_operations::write_end.
*/
int ntfs_write_end(struct file *file, struct address_space *mapping, loff_t pos,
u32 len, u32 copied, struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
u64 valid = ni->i_valid;
bool dirty = false;
int err;
if (is_resident(ni)) {
ni_lock(ni);
err = attr_data_write_resident(ni, page);
ni_unlock(ni);
if (!err) {
dirty = true;
/* Clear any buffers in page. */
if (page_has_buffers(page)) {
struct buffer_head *head, *bh;
bh = head = page_buffers(page);
do {
clear_buffer_dirty(bh);
clear_buffer_mapped(bh);
set_buffer_uptodate(bh);
} while (head != (bh = bh->b_this_page));
}
SetPageUptodate(page);
err = copied;
}
unlock_page(page);
put_page(page);
} else {
err = generic_write_end(file, mapping, pos, len, copied, page,
fsdata);
}
if (err >= 0) {
if (!(ni->std_fa & FILE_ATTRIBUTE_ARCHIVE)) {
inode->i_mtime = inode_set_ctime_current(inode);
ni->std_fa |= FILE_ATTRIBUTE_ARCHIVE;
dirty = true;
}
if (valid != ni->i_valid) {
/* ni->i_valid is changed in ntfs_get_block_vbo. */
dirty = true;
}
if (pos + err > inode->i_size) {
inode->i_size = pos + err;
dirty = true;
}
if (dirty)
mark_inode_dirty(inode);
}
return err;
}
int reset_log_file(struct inode *inode)
{
int err;
loff_t pos = 0;
u32 log_size = inode->i_size;
struct address_space *mapping = inode->i_mapping;
for (;;) {
u32 len;
void *kaddr;
struct page *page;
len = pos + PAGE_SIZE > log_size ? (log_size - pos) : PAGE_SIZE;
err = block_write_begin(mapping, pos, len, &page,
ntfs_get_block_write_begin);
if (err)
goto out;
kaddr = kmap_atomic(page);
memset(kaddr, -1, len);
kunmap_atomic(kaddr);
flush_dcache_page(page);
err = block_write_end(NULL, mapping, pos, len, len, page, NULL);
if (err < 0)
goto out;
pos += len;
if (pos >= log_size)
break;
balance_dirty_pages_ratelimited(mapping);
}
out:
mark_inode_dirty_sync(inode);
return err;
}
int ntfs3_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return _ni_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
}
int ntfs_sync_inode(struct inode *inode)
{
return _ni_write_inode(inode, 1);
}
/*
* writeback_inode - Helper function for ntfs_flush_inodes().
*
* This writes both the inode and the file data blocks, waiting
* for in flight data blocks before the start of the call. It
* does not wait for any io started during the call.
*/
static int writeback_inode(struct inode *inode)
{
int ret = sync_inode_metadata(inode, 0);
if (!ret)
ret = filemap_fdatawrite(inode->i_mapping);
return ret;
}
/*
* ntfs_flush_inodes
*
* Write data and metadata corresponding to i1 and i2. The io is
* started but we do not wait for any of it to finish.
*
* filemap_flush() is used for the block device, so if there is a dirty
* page for a block already in flight, we will not wait and start the
* io over again.
*/
int ntfs_flush_inodes(struct super_block *sb, struct inode *i1,
struct inode *i2)
{
int ret = 0;
if (i1)
ret = writeback_inode(i1);
if (!ret && i2)
ret = writeback_inode(i2);
if (!ret)
ret = sync_blockdev_nowait(sb->s_bdev);
return ret;
}
int inode_write_data(struct inode *inode, const void *data, size_t bytes)
{
pgoff_t idx;
/* Write non resident data. */
for (idx = 0; bytes; idx++) {
size_t op = bytes > PAGE_SIZE ? PAGE_SIZE : bytes;
struct page *page = ntfs_map_page(inode->i_mapping, idx);
if (IS_ERR(page))
return PTR_ERR(page);
lock_page(page);
WARN_ON(!PageUptodate(page));
ClearPageUptodate(page);
memcpy(page_address(page), data, op);
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
bytes -= op;
data = Add2Ptr(data, PAGE_SIZE);
}
return 0;
}
/*
* ntfs_reparse_bytes
*
* Number of bytes for REPARSE_DATA_BUFFER(IO_REPARSE_TAG_SYMLINK)
* for unicode string of @uni_len length.
*/
static inline u32 ntfs_reparse_bytes(u32 uni_len)
{
/* Header + unicode string + decorated unicode string. */
return sizeof(short) * (2 * uni_len + 4) +
offsetof(struct REPARSE_DATA_BUFFER,
SymbolicLinkReparseBuffer.PathBuffer);
}
static struct REPARSE_DATA_BUFFER *
ntfs_create_reparse_buffer(struct ntfs_sb_info *sbi, const char *symname,
u32 size, u16 *nsize)
{
int i, err;
struct REPARSE_DATA_BUFFER *rp;
__le16 *rp_name;
typeof(rp->SymbolicLinkReparseBuffer) *rs;
rp = kzalloc(ntfs_reparse_bytes(2 * size + 2), GFP_NOFS);
if (!rp)
return ERR_PTR(-ENOMEM);
rs = &rp->SymbolicLinkReparseBuffer;
rp_name = rs->PathBuffer;
/* Convert link name to UTF-16. */
err = ntfs_nls_to_utf16(sbi, symname, size,
(struct cpu_str *)(rp_name - 1), 2 * size,
UTF16_LITTLE_ENDIAN);
if (err < 0)
goto out;
/* err = the length of unicode name of symlink. */
*nsize = ntfs_reparse_bytes(err);
if (*nsize > sbi->reparse.max_size) {
err = -EFBIG;
goto out;
}
/* Translate Linux '/' into Windows '\'. */
for (i = 0; i < err; i++) {
if (rp_name[i] == cpu_to_le16('/'))
rp_name[i] = cpu_to_le16('\\');
}
rp->ReparseTag = IO_REPARSE_TAG_SYMLINK;
rp->ReparseDataLength =
cpu_to_le16(*nsize - offsetof(struct REPARSE_DATA_BUFFER,
SymbolicLinkReparseBuffer));
/* PrintName + SubstituteName. */
rs->SubstituteNameOffset = cpu_to_le16(sizeof(short) * err);
rs->SubstituteNameLength = cpu_to_le16(sizeof(short) * err + 8);
rs->PrintNameLength = rs->SubstituteNameOffset;
/*
* TODO: Use relative path if possible to allow Windows to
* parse this path.
* 0-absolute path 1- relative path (SYMLINK_FLAG_RELATIVE).
*/
rs->Flags = 0;
memmove(rp_name + err + 4, rp_name, sizeof(short) * err);
/* Decorate SubstituteName. */
rp_name += err;
rp_name[0] = cpu_to_le16('\\');
rp_name[1] = cpu_to_le16('?');
rp_name[2] = cpu_to_le16('?');
rp_name[3] = cpu_to_le16('\\');
return rp;
out:
kfree(rp);
return ERR_PTR(err);
}
/*
* ntfs_create_inode
*
* Helper function for:
* - ntfs_create
* - ntfs_mknod
* - ntfs_symlink
* - ntfs_mkdir
* - ntfs_atomic_open
*
* NOTE: if fnd != NULL (ntfs_atomic_open) then @dir is locked
*/
struct inode *ntfs_create_inode(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry,
const struct cpu_str *uni, umode_t mode,
dev_t dev, const char *symname, u32 size,
struct ntfs_fnd *fnd)
{
int err;
struct super_block *sb = dir->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
const struct qstr *name = &dentry->d_name;
CLST ino = 0;
struct ntfs_inode *dir_ni = ntfs_i(dir);
struct ntfs_inode *ni = NULL;
struct inode *inode = NULL;
struct ATTRIB *attr;
struct ATTR_STD_INFO5 *std5;
struct ATTR_FILE_NAME *fname;
struct MFT_REC *rec;
u32 asize, dsize, sd_size;
enum FILE_ATTRIBUTE fa;
__le32 security_id = SECURITY_ID_INVALID;
CLST vcn;
const void *sd;
u16 t16, nsize = 0, aid = 0;
struct INDEX_ROOT *root, *dir_root;
struct NTFS_DE *e, *new_de = NULL;
struct REPARSE_DATA_BUFFER *rp = NULL;
bool rp_inserted = false;
if (!fnd)
ni_lock_dir(dir_ni);
dir_root = indx_get_root(&dir_ni->dir, dir_ni, NULL, NULL);
if (!dir_root) {
err = -EINVAL;
goto out1;
}
if (S_ISDIR(mode)) {
/* Use parent's directory attributes. */
fa = dir_ni->std_fa | FILE_ATTRIBUTE_DIRECTORY |
FILE_ATTRIBUTE_ARCHIVE;
/*
* By default child directory inherits parent attributes.
* Root directory is hidden + system.
* Make an exception for children in root.
*/
if (dir->i_ino == MFT_REC_ROOT)
fa &= ~(FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
} else if (S_ISLNK(mode)) {
/* It is good idea that link should be the same type (file/dir) as target */
fa = FILE_ATTRIBUTE_REPARSE_POINT;
/*
* Linux: there are dir/file/symlink and so on.
* NTFS: symlinks are "dir + reparse" or "file + reparse"
* It is good idea to create:
* dir + reparse if 'symname' points to directory
* or
* file + reparse if 'symname' points to file
* Unfortunately kern_path hangs if symname contains 'dir'.
*/
/*
* struct path path;
*
* if (!kern_path(symname, LOOKUP_FOLLOW, &path)){
* struct inode *target = d_inode(path.dentry);
*
* if (S_ISDIR(target->i_mode))
* fa |= FILE_ATTRIBUTE_DIRECTORY;
* // if ( target->i_sb == sb ){
* // use relative path?
* // }
* path_put(&path);
* }
*/
} else if (S_ISREG(mode)) {
if (sbi->options->sparse) {
/* Sparsed regular file, cause option 'sparse'. */
fa = FILE_ATTRIBUTE_SPARSE_FILE |
FILE_ATTRIBUTE_ARCHIVE;
} else if (dir_ni->std_fa & FILE_ATTRIBUTE_COMPRESSED) {
/* Compressed regular file, if parent is compressed. */
fa = FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_ARCHIVE;
} else {
/* Regular file, default attributes. */
fa = FILE_ATTRIBUTE_ARCHIVE;
}
} else {
fa = FILE_ATTRIBUTE_ARCHIVE;
}
/* If option "hide_dot_files" then set hidden attribute for dot files. */
if (sbi->options->hide_dot_files && name->name[0] == '.')
fa |= FILE_ATTRIBUTE_HIDDEN;
if (!(mode & 0222))
fa |= FILE_ATTRIBUTE_READONLY;
/* Allocate PATH_MAX bytes. */
new_de = __getname();
if (!new_de) {
err = -ENOMEM;
goto out1;
}
/* Mark rw ntfs as dirty. it will be cleared at umount. */
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
/* Step 1: allocate and fill new mft record. */
err = ntfs_look_free_mft(sbi, &ino, false, NULL, NULL);
if (err)
goto out2;
ni = ntfs_new_inode(sbi, ino, S_ISDIR(mode) ? RECORD_FLAG_DIR : 0);
if (IS_ERR(ni)) {
err = PTR_ERR(ni);
ni = NULL;
goto out3;
}
inode = &ni->vfs_inode;
inode_init_owner(idmap, inode, dir, mode);
mode = inode->i_mode;
ni->i_crtime = current_time(inode);
rec = ni->mi.mrec;
rec->hard_links = cpu_to_le16(1);
attr = Add2Ptr(rec, le16_to_cpu(rec->attr_off));
/* Get default security id. */
sd = s_default_security;
sd_size = sizeof(s_default_security);
if (is_ntfs3(sbi)) {
security_id = dir_ni->std_security_id;
if (le32_to_cpu(security_id) < SECURITY_ID_FIRST) {
security_id = sbi->security.def_security_id;
if (security_id == SECURITY_ID_INVALID &&
!ntfs_insert_security(sbi, sd, sd_size,
&security_id, NULL))
sbi->security.def_security_id = security_id;
}
}
/* Insert standard info. */
std5 = Add2Ptr(attr, SIZEOF_RESIDENT);
if (security_id == SECURITY_ID_INVALID) {
dsize = sizeof(struct ATTR_STD_INFO);
} else {
dsize = sizeof(struct ATTR_STD_INFO5);
std5->security_id = security_id;
ni->std_security_id = security_id;
}
asize = SIZEOF_RESIDENT + dsize;
attr->type = ATTR_STD;
attr->size = cpu_to_le32(asize);
attr->id = cpu_to_le16(aid++);
attr->res.data_off = SIZEOF_RESIDENT_LE;
attr->res.data_size = cpu_to_le32(dsize);
std5->cr_time = std5->m_time = std5->c_time = std5->a_time =
kernel2nt(&ni->i_crtime);
std5->fa = ni->std_fa = fa;
attr = Add2Ptr(attr, asize);
/* Insert file name. */
err = fill_name_de(sbi, new_de, name, uni);
if (err)
goto out4;
mi_get_ref(&ni->mi, &new_de->ref);
fname = (struct ATTR_FILE_NAME *)(new_de + 1);
if (sbi->options->windows_names &&
!valid_windows_name(sbi, (struct le_str *)&fname->name_len)) {
err = -EINVAL;
goto out4;
}
mi_get_ref(&dir_ni->mi, &fname->home);
fname->dup.cr_time = fname->dup.m_time = fname->dup.c_time =
fname->dup.a_time = std5->cr_time;
fname->dup.alloc_size = fname->dup.data_size = 0;
fname->dup.fa = std5->fa;
fname->dup.ea_size = fname->dup.reparse = 0;
dsize = le16_to_cpu(new_de->key_size);
asize = ALIGN(SIZEOF_RESIDENT + dsize, 8);
attr->type = ATTR_NAME;
attr->size = cpu_to_le32(asize);
attr->res.data_off = SIZEOF_RESIDENT_LE;
attr->res.flags = RESIDENT_FLAG_INDEXED;
attr->id = cpu_to_le16(aid++);
attr->res.data_size = cpu_to_le32(dsize);
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), fname, dsize);
attr = Add2Ptr(attr, asize);
if (security_id == SECURITY_ID_INVALID) {
/* Insert security attribute. */
asize = SIZEOF_RESIDENT + ALIGN(sd_size, 8);
attr->type = ATTR_SECURE;
attr->size = cpu_to_le32(asize);
attr->id = cpu_to_le16(aid++);
attr->res.data_off = SIZEOF_RESIDENT_LE;
attr->res.data_size = cpu_to_le32(sd_size);
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), sd, sd_size);
attr = Add2Ptr(attr, asize);
}
attr->id = cpu_to_le16(aid++);
if (fa & FILE_ATTRIBUTE_DIRECTORY) {
/*
* Regular directory or symlink to directory.
* Create root attribute.
*/
dsize = sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE);
asize = sizeof(I30_NAME) + SIZEOF_RESIDENT + dsize;
attr->type = ATTR_ROOT;
attr->size = cpu_to_le32(asize);
attr->name_len = ARRAY_SIZE(I30_NAME);
attr->name_off = SIZEOF_RESIDENT_LE;
attr->res.data_off =
cpu_to_le16(sizeof(I30_NAME) + SIZEOF_RESIDENT);
attr->res.data_size = cpu_to_le32(dsize);
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), I30_NAME,
sizeof(I30_NAME));
root = Add2Ptr(attr, sizeof(I30_NAME) + SIZEOF_RESIDENT);
memcpy(root, dir_root, offsetof(struct INDEX_ROOT, ihdr));
root->ihdr.de_off = cpu_to_le32(sizeof(struct INDEX_HDR));
root->ihdr.used = cpu_to_le32(sizeof(struct INDEX_HDR) +
sizeof(struct NTFS_DE));
root->ihdr.total = root->ihdr.used;
e = Add2Ptr(root, sizeof(struct INDEX_ROOT));
e->size = cpu_to_le16(sizeof(struct NTFS_DE));
e->flags = NTFS_IE_LAST;
} else if (S_ISLNK(mode)) {
/*
* Symlink to file.
* Create empty resident data attribute.
*/
asize = SIZEOF_RESIDENT;
/* Insert empty ATTR_DATA */
attr->type = ATTR_DATA;
attr->size = cpu_to_le32(SIZEOF_RESIDENT);
attr->name_off = SIZEOF_RESIDENT_LE;
attr->res.data_off = SIZEOF_RESIDENT_LE;
} else if (S_ISREG(mode)) {
/*
* Regular file. Create empty non resident data attribute.
*/
attr->type = ATTR_DATA;
attr->non_res = 1;
attr->nres.evcn = cpu_to_le64(-1ll);
if (fa & FILE_ATTRIBUTE_SPARSE_FILE) {
attr->size = cpu_to_le32(SIZEOF_NONRESIDENT_EX + 8);
attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
attr->flags = ATTR_FLAG_SPARSED;
asize = SIZEOF_NONRESIDENT_EX + 8;
} else if (fa & FILE_ATTRIBUTE_COMPRESSED) {
attr->size = cpu_to_le32(SIZEOF_NONRESIDENT_EX + 8);
attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
attr->flags = ATTR_FLAG_COMPRESSED;
attr->nres.c_unit = COMPRESSION_UNIT;
asize = SIZEOF_NONRESIDENT_EX + 8;
} else {
attr->size = cpu_to_le32(SIZEOF_NONRESIDENT + 8);
attr->name_off = SIZEOF_NONRESIDENT_LE;
asize = SIZEOF_NONRESIDENT + 8;
}
attr->nres.run_off = attr->name_off;
} else {
/*
* Node. Create empty resident data attribute.
*/
attr->type = ATTR_DATA;
attr->size = cpu_to_le32(SIZEOF_RESIDENT);
attr->name_off = SIZEOF_RESIDENT_LE;
if (fa & FILE_ATTRIBUTE_SPARSE_FILE)
attr->flags = ATTR_FLAG_SPARSED;
else if (fa & FILE_ATTRIBUTE_COMPRESSED)
attr->flags = ATTR_FLAG_COMPRESSED;
attr->res.data_off = SIZEOF_RESIDENT_LE;
asize = SIZEOF_RESIDENT;
ni->ni_flags |= NI_FLAG_RESIDENT;
}
if (S_ISDIR(mode)) {
ni->ni_flags |= NI_FLAG_DIR;
err = indx_init(&ni->dir, sbi, attr, INDEX_MUTEX_I30);
if (err)
goto out4;
} else if (S_ISLNK(mode)) {
rp = ntfs_create_reparse_buffer(sbi, symname, size, &nsize);
if (IS_ERR(rp)) {
err = PTR_ERR(rp);
rp = NULL;
goto out4;
}
/*
* Insert ATTR_REPARSE.
*/
attr = Add2Ptr(attr, asize);
attr->type = ATTR_REPARSE;
attr->id = cpu_to_le16(aid++);
/* Resident or non resident? */
asize = ALIGN(SIZEOF_RESIDENT + nsize, 8);
t16 = PtrOffset(rec, attr);
/*
* Below function 'ntfs_save_wsl_perm' requires 0x78 bytes.
* It is good idea to keep extened attributes resident.
*/
if (asize + t16 + 0x78 + 8 > sbi->record_size) {
CLST alen;
CLST clst = bytes_to_cluster(sbi, nsize);
/* Bytes per runs. */
t16 = sbi->record_size - t16 - SIZEOF_NONRESIDENT;
attr->non_res = 1;
attr->nres.evcn = cpu_to_le64(clst - 1);
attr->name_off = SIZEOF_NONRESIDENT_LE;
attr->nres.run_off = attr->name_off;
attr->nres.data_size = cpu_to_le64(nsize);
attr->nres.valid_size = attr->nres.data_size;
attr->nres.alloc_size =
cpu_to_le64(ntfs_up_cluster(sbi, nsize));
err = attr_allocate_clusters(sbi, &ni->file.run, 0, 0,
clst, NULL, ALLOCATE_DEF,
&alen, 0, NULL, NULL);
if (err)
goto out5;
err = run_pack(&ni->file.run, 0, clst,
Add2Ptr(attr, SIZEOF_NONRESIDENT), t16,
&vcn);
if (err < 0)
goto out5;
if (vcn != clst) {
err = -EINVAL;
goto out5;
}
asize = SIZEOF_NONRESIDENT + ALIGN(err, 8);
/* Write non resident data. */
err = ntfs_sb_write_run(sbi, &ni->file.run, 0, rp,
nsize, 0);
if (err)
goto out5;
} else {
attr->res.data_off = SIZEOF_RESIDENT_LE;
attr->res.data_size = cpu_to_le32(nsize);
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), rp, nsize);
}
/* Size of symlink equals the length of input string. */
inode->i_size = size;
attr->size = cpu_to_le32(asize);
err = ntfs_insert_reparse(sbi, IO_REPARSE_TAG_SYMLINK,
&new_de->ref);
if (err)
goto out5;
rp_inserted = true;
}
attr = Add2Ptr(attr, asize);
attr->type = ATTR_END;
rec->used = cpu_to_le32(PtrOffset(rec, attr) + 8);
rec->next_attr_id = cpu_to_le16(aid);
inode->i_generation = le16_to_cpu(rec->seq);
if (S_ISDIR(mode)) {
inode->i_op = &ntfs_dir_inode_operations;
inode->i_fop = &ntfs_dir_operations;
} else if (S_ISLNK(mode)) {
inode->i_op = &ntfs_link_inode_operations;
inode->i_fop = NULL;
inode->i_mapping->a_ops = &ntfs_aops;
inode->i_size = size;
inode_nohighmem(inode);
} else if (S_ISREG(mode)) {
inode->i_op = &ntfs_file_inode_operations;
inode->i_fop = &ntfs_file_operations;
inode->i_mapping->a_ops = is_compressed(ni) ? &ntfs_aops_cmpr :
&ntfs_aops;
init_rwsem(&ni->file.run_lock);
} else {
inode->i_op = &ntfs_special_inode_operations;
init_special_inode(inode, mode, dev);
}
#ifdef CONFIG_NTFS3_FS_POSIX_ACL
if (!S_ISLNK(mode) && (sb->s_flags & SB_POSIXACL)) {
err = ntfs_init_acl(idmap, inode, dir);
if (err)
goto out5;
} else
#endif
{
inode->i_flags |= S_NOSEC;
}
/*
* ntfs_init_acl and ntfs_save_wsl_perm update extended attribute.
* The packed size of extended attribute is stored in direntry too.
* 'fname' here points to inside new_de.
*/
ntfs_save_wsl_perm(inode, &fname->dup.ea_size);
/*
* update ea_size in file_name attribute too.
* Use ni_find_attr cause layout of MFT record may be changed
* in ntfs_init_acl and ntfs_save_wsl_perm.
*/
attr = ni_find_attr(ni, NULL, NULL, ATTR_NAME, NULL, 0, NULL, NULL);
if (attr) {
struct ATTR_FILE_NAME *fn;
fn = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
if (fn)
fn->dup.ea_size = fname->dup.ea_size;
}
/* We do not need to update parent directory later */
ni->ni_flags &= ~NI_FLAG_UPDATE_PARENT;
/* Step 2: Add new name in index. */
err = indx_insert_entry(&dir_ni->dir, dir_ni, new_de, sbi, fnd, 0);
if (err)
goto out6;
/*
* Call 'd_instantiate' after inode->i_op is set
* but before finish_open.
*/
d_instantiate(dentry, inode);
/* Set original time. inode times (i_ctime) may be changed in ntfs_init_acl. */
inode->i_atime = inode->i_mtime = inode_set_ctime_to_ts(inode, ni->i_crtime);
dir->i_mtime = inode_set_ctime_to_ts(dir, ni->i_crtime);
mark_inode_dirty(dir);
mark_inode_dirty(inode);
/* Normal exit. */
goto out2;
out6:
if (rp_inserted)
ntfs_remove_reparse(sbi, IO_REPARSE_TAG_SYMLINK, &new_de->ref);
out5:
if (!S_ISDIR(mode))
run_deallocate(sbi, &ni->file.run, false);
out4:
clear_rec_inuse(rec);
clear_nlink(inode);
ni->mi.dirty = false;
discard_new_inode(inode);
out3:
ntfs_mark_rec_free(sbi, ino, false);
out2:
__putname(new_de);
kfree(rp);
out1:
if (!fnd)
ni_unlock(dir_ni);
if (err)
return ERR_PTR(err);
unlock_new_inode(inode);
return inode;
}
int ntfs_link_inode(struct inode *inode, struct dentry *dentry)
{
int err;
struct ntfs_inode *ni = ntfs_i(inode);
struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
struct NTFS_DE *de;
/* Allocate PATH_MAX bytes. */
de = __getname();
if (!de)
return -ENOMEM;
/* Mark rw ntfs as dirty. It will be cleared at umount. */
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
/* Construct 'de'. */
err = fill_name_de(sbi, de, &dentry->d_name, NULL);
if (err)
goto out;
err = ni_add_name(ntfs_i(d_inode(dentry->d_parent)), ni, de);
out:
__putname(de);
return err;
}
/*
* ntfs_unlink_inode
*
* inode_operations::unlink
* inode_operations::rmdir
*/
int ntfs_unlink_inode(struct inode *dir, const struct dentry *dentry)
{
int err;
struct ntfs_sb_info *sbi = dir->i_sb->s_fs_info;
struct inode *inode = d_inode(dentry);
struct ntfs_inode *ni = ntfs_i(inode);
struct ntfs_inode *dir_ni = ntfs_i(dir);
struct NTFS_DE *de, *de2 = NULL;
int undo_remove;
if (ntfs_is_meta_file(sbi, ni->mi.rno))
return -EINVAL;
/* Allocate PATH_MAX bytes. */
de = __getname();
if (!de)
return -ENOMEM;
ni_lock(ni);
if (S_ISDIR(inode->i_mode) && !dir_is_empty(inode)) {
err = -ENOTEMPTY;
goto out;
}
err = fill_name_de(sbi, de, &dentry->d_name, NULL);
if (err < 0)
goto out;
undo_remove = 0;
err = ni_remove_name(dir_ni, ni, de, &de2, &undo_remove);
if (!err) {
drop_nlink(inode);
dir->i_mtime = inode_set_ctime_current(dir);
mark_inode_dirty(dir);
inode_set_ctime_to_ts(inode, inode_get_ctime(dir));
if (inode->i_nlink)
mark_inode_dirty(inode);
} else if (!ni_remove_name_undo(dir_ni, ni, de, de2, undo_remove)) {
_ntfs_bad_inode(inode);
} else {
if (ni_is_dirty(dir))
mark_inode_dirty(dir);
if (ni_is_dirty(inode))
mark_inode_dirty(inode);
}
out:
ni_unlock(ni);
__putname(de);
return err;
}
void ntfs_evict_inode(struct inode *inode)
{
truncate_inode_pages_final(&inode->i_data);
invalidate_inode_buffers(inode);
clear_inode(inode);
ni_clear(ntfs_i(inode));
}
/*
* ntfs_translate_junction
*
* Translate a Windows junction target to the Linux equivalent.
* On junctions, targets are always absolute (they include the drive
* letter). We have no way of knowing if the target is for the current
* mounted device or not so we just assume it is.
*/
static int ntfs_translate_junction(const struct super_block *sb,
const struct dentry *link_de, char *target,
int target_len, int target_max)
{
int tl_len, err = target_len;
char *link_path_buffer = NULL, *link_path;
char *translated = NULL;
char *target_start;
int copy_len;
link_path_buffer = kmalloc(PATH_MAX, GFP_NOFS);
if (!link_path_buffer) {
err = -ENOMEM;
goto out;
}
/* Get link path, relative to mount point */
link_path = dentry_path_raw(link_de, link_path_buffer, PATH_MAX);
if (IS_ERR(link_path)) {
ntfs_err(sb, "Error getting link path");
err = -EINVAL;
goto out;
}
translated = kmalloc(PATH_MAX, GFP_NOFS);
if (!translated) {
err = -ENOMEM;
goto out;
}
/* Make translated path a relative path to mount point */
strcpy(translated, "./");
++link_path; /* Skip leading / */
for (tl_len = sizeof("./") - 1; *link_path; ++link_path) {
if (*link_path == '/') {
if (PATH_MAX - tl_len < sizeof("../")) {
ntfs_err(sb,
"Link path %s has too many components",
link_path);
err = -EINVAL;
goto out;
}
strcpy(translated + tl_len, "../");
tl_len += sizeof("../") - 1;
}
}
/* Skip drive letter */
target_start = target;
while (*target_start && *target_start != ':')
++target_start;
if (!*target_start) {
ntfs_err(sb, "Link target (%s) missing drive separator",
target);
err = -EINVAL;
goto out;
}
/* Skip drive separator and leading /, if exists */
target_start += 1 + (target_start[1] == '/');
copy_len = target_len - (target_start - target);
if (PATH_MAX - tl_len <= copy_len) {
ntfs_err(sb, "Link target %s too large for buffer (%d <= %d)",
target_start, PATH_MAX - tl_len, copy_len);
err = -EINVAL;
goto out;
}
/* translated path has a trailing / and target_start does not */
strcpy(translated + tl_len, target_start);
tl_len += copy_len;
if (target_max <= tl_len) {
ntfs_err(sb, "Target path %s too large for buffer (%d <= %d)",
translated, target_max, tl_len);
err = -EINVAL;
goto out;
}
strcpy(target, translated);
err = tl_len;
out:
kfree(link_path_buffer);
kfree(translated);
return err;
}
static noinline int ntfs_readlink_hlp(const struct dentry *link_de,
struct inode *inode, char *buffer,
int buflen)
{
int i, err = -EINVAL;
struct ntfs_inode *ni = ntfs_i(inode);
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
u64 size;
u16 ulen = 0;
void *to_free = NULL;
struct REPARSE_DATA_BUFFER *rp;
const __le16 *uname;
struct ATTRIB *attr;
/* Reparse data present. Try to parse it. */
static_assert(!offsetof(struct REPARSE_DATA_BUFFER, ReparseTag));
static_assert(sizeof(u32) == sizeof(rp->ReparseTag));
*buffer = 0;
attr = ni_find_attr(ni, NULL, NULL, ATTR_REPARSE, NULL, 0, NULL, NULL);
if (!attr)
goto out;
if (!attr->non_res) {
rp = resident_data_ex(attr, sizeof(struct REPARSE_DATA_BUFFER));
if (!rp)
goto out;
size = le32_to_cpu(attr->res.data_size);
} else {
size = le64_to_cpu(attr->nres.data_size);
rp = NULL;
}
if (size > sbi->reparse.max_size || size <= sizeof(u32))
goto out;
if (!rp) {
rp = kmalloc(size, GFP_NOFS);
if (!rp) {
err = -ENOMEM;
goto out;
}
to_free = rp;
/* Read into temporal buffer. */
err = ntfs_read_run_nb(sbi, &ni->file.run, 0, rp, size, NULL);
if (err)
goto out;
}
/* Microsoft Tag. */
switch (rp->ReparseTag) {
case IO_REPARSE_TAG_MOUNT_POINT:
/* Mount points and junctions. */
/* Can we use 'Rp->MountPointReparseBuffer.PrintNameLength'? */
if (size <= offsetof(struct REPARSE_DATA_BUFFER,
MountPointReparseBuffer.PathBuffer))
goto out;
uname = Add2Ptr(rp,
offsetof(struct REPARSE_DATA_BUFFER,
MountPointReparseBuffer.PathBuffer) +
le16_to_cpu(rp->MountPointReparseBuffer
.PrintNameOffset));
ulen = le16_to_cpu(rp->MountPointReparseBuffer.PrintNameLength);
break;
case IO_REPARSE_TAG_SYMLINK:
/* FolderSymbolicLink */
/* Can we use 'Rp->SymbolicLinkReparseBuffer.PrintNameLength'? */
if (size <= offsetof(struct REPARSE_DATA_BUFFER,
SymbolicLinkReparseBuffer.PathBuffer))
goto out;
uname = Add2Ptr(
rp, offsetof(struct REPARSE_DATA_BUFFER,
SymbolicLinkReparseBuffer.PathBuffer) +
le16_to_cpu(rp->SymbolicLinkReparseBuffer
.PrintNameOffset));
ulen = le16_to_cpu(
rp->SymbolicLinkReparseBuffer.PrintNameLength);
break;
case IO_REPARSE_TAG_CLOUD:
case IO_REPARSE_TAG_CLOUD_1:
case IO_REPARSE_TAG_CLOUD_2:
case IO_REPARSE_TAG_CLOUD_3:
case IO_REPARSE_TAG_CLOUD_4:
case IO_REPARSE_TAG_CLOUD_5:
case IO_REPARSE_TAG_CLOUD_6:
case IO_REPARSE_TAG_CLOUD_7:
case IO_REPARSE_TAG_CLOUD_8:
case IO_REPARSE_TAG_CLOUD_9:
case IO_REPARSE_TAG_CLOUD_A:
case IO_REPARSE_TAG_CLOUD_B:
case IO_REPARSE_TAG_CLOUD_C:
case IO_REPARSE_TAG_CLOUD_D:
case IO_REPARSE_TAG_CLOUD_E:
case IO_REPARSE_TAG_CLOUD_F:
err = sizeof("OneDrive") - 1;
if (err > buflen)
err = buflen;
memcpy(buffer, "OneDrive", err);
goto out;
default:
if (IsReparseTagMicrosoft(rp->ReparseTag)) {
/* Unknown Microsoft Tag. */
goto out;
}
if (!IsReparseTagNameSurrogate(rp->ReparseTag) ||
size <= sizeof(struct REPARSE_POINT)) {
goto out;
}
/* Users tag. */
uname = Add2Ptr(rp, sizeof(struct REPARSE_POINT));
ulen = le16_to_cpu(rp->ReparseDataLength) -
sizeof(struct REPARSE_POINT);
}
/* Convert nlen from bytes to UNICODE chars. */
ulen >>= 1;
/* Check that name is available. */
if (!ulen || uname + ulen > (__le16 *)Add2Ptr(rp, size))
goto out;
/* If name is already zero terminated then truncate it now. */
if (!uname[ulen - 1])
ulen -= 1;
err = ntfs_utf16_to_nls(sbi, uname, ulen, buffer, buflen);
if (err < 0)
goto out;
/* Translate Windows '\' into Linux '/'. */
for (i = 0; i < err; i++) {
if (buffer[i] == '\\')
buffer[i] = '/';
}
/* Always set last zero. */
buffer[err] = 0;
/* If this is a junction, translate the link target. */
if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
err = ntfs_translate_junction(sb, link_de, buffer, err, buflen);
out:
kfree(to_free);
return err;
}
static const char *ntfs_get_link(struct dentry *de, struct inode *inode,
struct delayed_call *done)
{
int err;
char *ret;
if (!de)
return ERR_PTR(-ECHILD);
ret = kmalloc(PAGE_SIZE, GFP_NOFS);
if (!ret)
return ERR_PTR(-ENOMEM);
err = ntfs_readlink_hlp(de, inode, ret, PAGE_SIZE);
if (err < 0) {
kfree(ret);
return ERR_PTR(err);
}
set_delayed_call(done, kfree_link, ret);
return ret;
}
// clang-format off
const struct inode_operations ntfs_link_inode_operations = {
.get_link = ntfs_get_link,
.setattr = ntfs3_setattr,
.listxattr = ntfs_listxattr,
};
const struct address_space_operations ntfs_aops = {
.read_folio = ntfs_read_folio,
.readahead = ntfs_readahead,
.writepages = ntfs_writepages,
.write_begin = ntfs_write_begin,
.write_end = ntfs_write_end,
.direct_IO = ntfs_direct_IO,
.bmap = ntfs_bmap,
.dirty_folio = block_dirty_folio,
.migrate_folio = buffer_migrate_folio,
.invalidate_folio = block_invalidate_folio,
};
const struct address_space_operations ntfs_aops_cmpr = {
.read_folio = ntfs_read_folio,
.readahead = ntfs_readahead,
};
// clang-format on
| linux-master | fs/ntfs3/inode.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
static const struct INDEX_NAMES {
const __le16 *name;
u8 name_len;
} s_index_names[INDEX_MUTEX_TOTAL] = {
{ I30_NAME, ARRAY_SIZE(I30_NAME) }, { SII_NAME, ARRAY_SIZE(SII_NAME) },
{ SDH_NAME, ARRAY_SIZE(SDH_NAME) }, { SO_NAME, ARRAY_SIZE(SO_NAME) },
{ SQ_NAME, ARRAY_SIZE(SQ_NAME) }, { SR_NAME, ARRAY_SIZE(SR_NAME) },
};
/*
* cmp_fnames - Compare two names in index.
*
* if l1 != 0
* Both names are little endian on-disk ATTR_FILE_NAME structs.
* else
* key1 - cpu_str, key2 - ATTR_FILE_NAME
*/
static int cmp_fnames(const void *key1, size_t l1, const void *key2, size_t l2,
const void *data)
{
const struct ATTR_FILE_NAME *f2 = key2;
const struct ntfs_sb_info *sbi = data;
const struct ATTR_FILE_NAME *f1;
u16 fsize2;
bool both_case;
if (l2 <= offsetof(struct ATTR_FILE_NAME, name))
return -1;
fsize2 = fname_full_size(f2);
if (l2 < fsize2)
return -1;
both_case = f2->type != FILE_NAME_DOS && !sbi->options->nocase;
if (!l1) {
const struct le_str *s2 = (struct le_str *)&f2->name_len;
/*
* If names are equal (case insensitive)
* try to compare it case sensitive.
*/
return ntfs_cmp_names_cpu(key1, s2, sbi->upcase, both_case);
}
f1 = key1;
return ntfs_cmp_names(f1->name, f1->name_len, f2->name, f2->name_len,
sbi->upcase, both_case);
}
/*
* cmp_uint - $SII of $Secure and $Q of Quota
*/
static int cmp_uint(const void *key1, size_t l1, const void *key2, size_t l2,
const void *data)
{
const u32 *k1 = key1;
const u32 *k2 = key2;
if (l2 < sizeof(u32))
return -1;
if (*k1 < *k2)
return -1;
if (*k1 > *k2)
return 1;
return 0;
}
/*
* cmp_sdh - $SDH of $Secure
*/
static int cmp_sdh(const void *key1, size_t l1, const void *key2, size_t l2,
const void *data)
{
const struct SECURITY_KEY *k1 = key1;
const struct SECURITY_KEY *k2 = key2;
u32 t1, t2;
if (l2 < sizeof(struct SECURITY_KEY))
return -1;
t1 = le32_to_cpu(k1->hash);
t2 = le32_to_cpu(k2->hash);
/* First value is a hash value itself. */
if (t1 < t2)
return -1;
if (t1 > t2)
return 1;
/* Second value is security Id. */
if (data) {
t1 = le32_to_cpu(k1->sec_id);
t2 = le32_to_cpu(k2->sec_id);
if (t1 < t2)
return -1;
if (t1 > t2)
return 1;
}
return 0;
}
/*
* cmp_uints - $O of ObjId and "$R" for Reparse.
*/
static int cmp_uints(const void *key1, size_t l1, const void *key2, size_t l2,
const void *data)
{
const __le32 *k1 = key1;
const __le32 *k2 = key2;
size_t count;
if ((size_t)data == 1) {
/*
* ni_delete_all -> ntfs_remove_reparse ->
* delete all with this reference.
* k1, k2 - pointers to REPARSE_KEY
*/
k1 += 1; // Skip REPARSE_KEY.ReparseTag
k2 += 1; // Skip REPARSE_KEY.ReparseTag
if (l2 <= sizeof(int))
return -1;
l2 -= sizeof(int);
if (l1 <= sizeof(int))
return 1;
l1 -= sizeof(int);
}
if (l2 < sizeof(int))
return -1;
for (count = min(l1, l2) >> 2; count > 0; --count, ++k1, ++k2) {
u32 t1 = le32_to_cpu(*k1);
u32 t2 = le32_to_cpu(*k2);
if (t1 > t2)
return 1;
if (t1 < t2)
return -1;
}
if (l1 > l2)
return 1;
if (l1 < l2)
return -1;
return 0;
}
static inline NTFS_CMP_FUNC get_cmp_func(const struct INDEX_ROOT *root)
{
switch (root->type) {
case ATTR_NAME:
if (root->rule == NTFS_COLLATION_TYPE_FILENAME)
return &cmp_fnames;
break;
case ATTR_ZERO:
switch (root->rule) {
case NTFS_COLLATION_TYPE_UINT:
return &cmp_uint;
case NTFS_COLLATION_TYPE_SECURITY_HASH:
return &cmp_sdh;
case NTFS_COLLATION_TYPE_UINTS:
return &cmp_uints;
default:
break;
}
break;
default:
break;
}
return NULL;
}
struct bmp_buf {
struct ATTRIB *b;
struct mft_inode *mi;
struct buffer_head *bh;
ulong *buf;
size_t bit;
u32 nbits;
u64 new_valid;
};
static int bmp_buf_get(struct ntfs_index *indx, struct ntfs_inode *ni,
size_t bit, struct bmp_buf *bbuf)
{
struct ATTRIB *b;
size_t data_size, valid_size, vbo, off = bit >> 3;
struct ntfs_sb_info *sbi = ni->mi.sbi;
CLST vcn = off >> sbi->cluster_bits;
struct ATTR_LIST_ENTRY *le = NULL;
struct buffer_head *bh;
struct super_block *sb;
u32 blocksize;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
bbuf->bh = NULL;
b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
&vcn, &bbuf->mi);
bbuf->b = b;
if (!b)
return -EINVAL;
if (!b->non_res) {
data_size = le32_to_cpu(b->res.data_size);
if (off >= data_size)
return -EINVAL;
bbuf->buf = (ulong *)resident_data(b);
bbuf->bit = 0;
bbuf->nbits = data_size * 8;
return 0;
}
data_size = le64_to_cpu(b->nres.data_size);
if (WARN_ON(off >= data_size)) {
/* Looks like filesystem error. */
return -EINVAL;
}
valid_size = le64_to_cpu(b->nres.valid_size);
bh = ntfs_bread_run(sbi, &indx->bitmap_run, off);
if (!bh)
return -EIO;
if (IS_ERR(bh))
return PTR_ERR(bh);
bbuf->bh = bh;
if (buffer_locked(bh))
__wait_on_buffer(bh);
lock_buffer(bh);
sb = sbi->sb;
blocksize = sb->s_blocksize;
vbo = off & ~(size_t)sbi->block_mask;
bbuf->new_valid = vbo + blocksize;
if (bbuf->new_valid <= valid_size)
bbuf->new_valid = 0;
else if (bbuf->new_valid > data_size)
bbuf->new_valid = data_size;
if (vbo >= valid_size) {
memset(bh->b_data, 0, blocksize);
} else if (vbo + blocksize > valid_size) {
u32 voff = valid_size & sbi->block_mask;
memset(bh->b_data + voff, 0, blocksize - voff);
}
bbuf->buf = (ulong *)bh->b_data;
bbuf->bit = 8 * (off & ~(size_t)sbi->block_mask);
bbuf->nbits = 8 * blocksize;
return 0;
}
static void bmp_buf_put(struct bmp_buf *bbuf, bool dirty)
{
struct buffer_head *bh = bbuf->bh;
struct ATTRIB *b = bbuf->b;
if (!bh) {
if (b && !b->non_res && dirty)
bbuf->mi->dirty = true;
return;
}
if (!dirty)
goto out;
if (bbuf->new_valid) {
b->nres.valid_size = cpu_to_le64(bbuf->new_valid);
bbuf->mi->dirty = true;
}
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
out:
unlock_buffer(bh);
put_bh(bh);
}
/*
* indx_mark_used - Mark the bit @bit as used.
*/
static int indx_mark_used(struct ntfs_index *indx, struct ntfs_inode *ni,
size_t bit)
{
int err;
struct bmp_buf bbuf;
err = bmp_buf_get(indx, ni, bit, &bbuf);
if (err)
return err;
__set_bit_le(bit - bbuf.bit, bbuf.buf);
bmp_buf_put(&bbuf, true);
return 0;
}
/*
* indx_mark_free - Mark the bit @bit as free.
*/
static int indx_mark_free(struct ntfs_index *indx, struct ntfs_inode *ni,
size_t bit)
{
int err;
struct bmp_buf bbuf;
err = bmp_buf_get(indx, ni, bit, &bbuf);
if (err)
return err;
__clear_bit_le(bit - bbuf.bit, bbuf.buf);
bmp_buf_put(&bbuf, true);
return 0;
}
/*
* scan_nres_bitmap
*
* If ntfs_readdir calls this function (indx_used_bit -> scan_nres_bitmap),
* inode is shared locked and no ni_lock.
* Use rw_semaphore for read/write access to bitmap_run.
*/
static int scan_nres_bitmap(struct ntfs_inode *ni, struct ATTRIB *bitmap,
struct ntfs_index *indx, size_t from,
bool (*fn)(const ulong *buf, u32 bit, u32 bits,
size_t *ret),
size_t *ret)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct super_block *sb = sbi->sb;
struct runs_tree *run = &indx->bitmap_run;
struct rw_semaphore *lock = &indx->run_lock;
u32 nbits = sb->s_blocksize * 8;
u32 blocksize = sb->s_blocksize;
u64 valid_size = le64_to_cpu(bitmap->nres.valid_size);
u64 data_size = le64_to_cpu(bitmap->nres.data_size);
sector_t eblock = bytes_to_block(sb, data_size);
size_t vbo = from >> 3;
sector_t blk = (vbo & sbi->cluster_mask) >> sb->s_blocksize_bits;
sector_t vblock = vbo >> sb->s_blocksize_bits;
sector_t blen, block;
CLST lcn, clen, vcn, vcn_next;
size_t idx;
struct buffer_head *bh;
bool ok;
*ret = MINUS_ONE_T;
if (vblock >= eblock)
return 0;
from &= nbits - 1;
vcn = vbo >> sbi->cluster_bits;
down_read(lock);
ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
up_read(lock);
next_run:
if (!ok) {
int err;
const struct INDEX_NAMES *name = &s_index_names[indx->type];
down_write(lock);
err = attr_load_runs_vcn(ni, ATTR_BITMAP, name->name,
name->name_len, run, vcn);
up_write(lock);
if (err)
return err;
down_read(lock);
ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
up_read(lock);
if (!ok)
return -EINVAL;
}
blen = (sector_t)clen * sbi->blocks_per_cluster;
block = (sector_t)lcn * sbi->blocks_per_cluster;
for (; blk < blen; blk++, from = 0) {
bh = ntfs_bread(sb, block + blk);
if (!bh)
return -EIO;
vbo = (u64)vblock << sb->s_blocksize_bits;
if (vbo >= valid_size) {
memset(bh->b_data, 0, blocksize);
} else if (vbo + blocksize > valid_size) {
u32 voff = valid_size & sbi->block_mask;
memset(bh->b_data + voff, 0, blocksize - voff);
}
if (vbo + blocksize > data_size)
nbits = 8 * (data_size - vbo);
ok = nbits > from ?
(*fn)((ulong *)bh->b_data, from, nbits, ret) :
false;
put_bh(bh);
if (ok) {
*ret += 8 * vbo;
return 0;
}
if (++vblock >= eblock) {
*ret = MINUS_ONE_T;
return 0;
}
}
blk = 0;
vcn_next = vcn + clen;
down_read(lock);
ok = run_get_entry(run, ++idx, &vcn, &lcn, &clen) && vcn == vcn_next;
if (!ok)
vcn = vcn_next;
up_read(lock);
goto next_run;
}
static bool scan_for_free(const ulong *buf, u32 bit, u32 bits, size_t *ret)
{
size_t pos = find_next_zero_bit_le(buf, bits, bit);
if (pos >= bits)
return false;
*ret = pos;
return true;
}
/*
* indx_find_free - Look for free bit.
*
* Return: -1 if no free bits.
*/
static int indx_find_free(struct ntfs_index *indx, struct ntfs_inode *ni,
size_t *bit, struct ATTRIB **bitmap)
{
struct ATTRIB *b;
struct ATTR_LIST_ENTRY *le = NULL;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
int err;
b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
NULL, NULL);
if (!b)
return -ENOENT;
*bitmap = b;
*bit = MINUS_ONE_T;
if (!b->non_res) {
u32 nbits = 8 * le32_to_cpu(b->res.data_size);
size_t pos = find_next_zero_bit_le(resident_data(b), nbits, 0);
if (pos < nbits)
*bit = pos;
} else {
err = scan_nres_bitmap(ni, b, indx, 0, &scan_for_free, bit);
if (err)
return err;
}
return 0;
}
static bool scan_for_used(const ulong *buf, u32 bit, u32 bits, size_t *ret)
{
size_t pos = find_next_bit_le(buf, bits, bit);
if (pos >= bits)
return false;
*ret = pos;
return true;
}
/*
* indx_used_bit - Look for used bit.
*
* Return: MINUS_ONE_T if no used bits.
*/
int indx_used_bit(struct ntfs_index *indx, struct ntfs_inode *ni, size_t *bit)
{
struct ATTRIB *b;
struct ATTR_LIST_ENTRY *le = NULL;
size_t from = *bit;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
int err;
b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
NULL, NULL);
if (!b)
return -ENOENT;
*bit = MINUS_ONE_T;
if (!b->non_res) {
u32 nbits = le32_to_cpu(b->res.data_size) * 8;
size_t pos = find_next_bit_le(resident_data(b), nbits, from);
if (pos < nbits)
*bit = pos;
} else {
err = scan_nres_bitmap(ni, b, indx, from, &scan_for_used, bit);
if (err)
return err;
}
return 0;
}
/*
* hdr_find_split
*
* Find a point at which the index allocation buffer would like to be split.
* NOTE: This function should never return 'END' entry NULL returns on error.
*/
static const struct NTFS_DE *hdr_find_split(const struct INDEX_HDR *hdr)
{
size_t o;
const struct NTFS_DE *e = hdr_first_de(hdr);
u32 used_2 = le32_to_cpu(hdr->used) >> 1;
u16 esize;
if (!e || de_is_last(e))
return NULL;
esize = le16_to_cpu(e->size);
for (o = le32_to_cpu(hdr->de_off) + esize; o < used_2; o += esize) {
const struct NTFS_DE *p = e;
e = Add2Ptr(hdr, o);
/* We must not return END entry. */
if (de_is_last(e))
return p;
esize = le16_to_cpu(e->size);
}
return e;
}
/*
* hdr_insert_head - Insert some entries at the beginning of the buffer.
*
* It is used to insert entries into a newly-created buffer.
*/
static const struct NTFS_DE *hdr_insert_head(struct INDEX_HDR *hdr,
const void *ins, u32 ins_bytes)
{
u32 to_move;
struct NTFS_DE *e = hdr_first_de(hdr);
u32 used = le32_to_cpu(hdr->used);
if (!e)
return NULL;
/* Now we just make room for the inserted entries and jam it in. */
to_move = used - le32_to_cpu(hdr->de_off);
memmove(Add2Ptr(e, ins_bytes), e, to_move);
memcpy(e, ins, ins_bytes);
hdr->used = cpu_to_le32(used + ins_bytes);
return e;
}
/*
* index_hdr_check
*
* return true if INDEX_HDR is valid
*/
static bool index_hdr_check(const struct INDEX_HDR *hdr, u32 bytes)
{
u32 end = le32_to_cpu(hdr->used);
u32 tot = le32_to_cpu(hdr->total);
u32 off = le32_to_cpu(hdr->de_off);
if (!IS_ALIGNED(off, 8) || tot > bytes || end > tot ||
off + sizeof(struct NTFS_DE) > end) {
/* incorrect index buffer. */
return false;
}
return true;
}
/*
* index_buf_check
*
* return true if INDEX_BUFFER seems is valid
*/
static bool index_buf_check(const struct INDEX_BUFFER *ib, u32 bytes,
const CLST *vbn)
{
const struct NTFS_RECORD_HEADER *rhdr = &ib->rhdr;
u16 fo = le16_to_cpu(rhdr->fix_off);
u16 fn = le16_to_cpu(rhdr->fix_num);
if (bytes <= offsetof(struct INDEX_BUFFER, ihdr) ||
rhdr->sign != NTFS_INDX_SIGNATURE ||
fo < sizeof(struct INDEX_BUFFER)
/* Check index buffer vbn. */
|| (vbn && *vbn != le64_to_cpu(ib->vbn)) || (fo % sizeof(short)) ||
fo + fn * sizeof(short) >= bytes ||
fn != ((bytes >> SECTOR_SHIFT) + 1)) {
/* incorrect index buffer. */
return false;
}
return index_hdr_check(&ib->ihdr,
bytes - offsetof(struct INDEX_BUFFER, ihdr));
}
void fnd_clear(struct ntfs_fnd *fnd)
{
int i;
for (i = fnd->level - 1; i >= 0; i--) {
struct indx_node *n = fnd->nodes[i];
if (!n)
continue;
put_indx_node(n);
fnd->nodes[i] = NULL;
}
fnd->level = 0;
fnd->root_de = NULL;
}
static int fnd_push(struct ntfs_fnd *fnd, struct indx_node *n,
struct NTFS_DE *e)
{
int i = fnd->level;
if (i < 0 || i >= ARRAY_SIZE(fnd->nodes))
return -EINVAL;
fnd->nodes[i] = n;
fnd->de[i] = e;
fnd->level += 1;
return 0;
}
static struct indx_node *fnd_pop(struct ntfs_fnd *fnd)
{
struct indx_node *n;
int i = fnd->level;
i -= 1;
n = fnd->nodes[i];
fnd->nodes[i] = NULL;
fnd->level = i;
return n;
}
static bool fnd_is_empty(struct ntfs_fnd *fnd)
{
if (!fnd->level)
return !fnd->root_de;
return !fnd->de[fnd->level - 1];
}
/*
* hdr_find_e - Locate an entry the index buffer.
*
* If no matching entry is found, it returns the first entry which is greater
* than the desired entry If the search key is greater than all the entries the
* buffer, it returns the 'end' entry. This function does a binary search of the
* current index buffer, for the first entry that is <= to the search value.
*
* Return: NULL if error.
*/
static struct NTFS_DE *hdr_find_e(const struct ntfs_index *indx,
const struct INDEX_HDR *hdr, const void *key,
size_t key_len, const void *ctx, int *diff)
{
struct NTFS_DE *e, *found = NULL;
NTFS_CMP_FUNC cmp = indx->cmp;
int min_idx = 0, mid_idx, max_idx = 0;
int diff2;
int table_size = 8;
u32 e_size, e_key_len;
u32 end = le32_to_cpu(hdr->used);
u32 off = le32_to_cpu(hdr->de_off);
u32 total = le32_to_cpu(hdr->total);
u16 offs[128];
fill_table:
if (end > total)
return NULL;
if (off + sizeof(struct NTFS_DE) > end)
return NULL;
e = Add2Ptr(hdr, off);
e_size = le16_to_cpu(e->size);
if (e_size < sizeof(struct NTFS_DE) || off + e_size > end)
return NULL;
if (!de_is_last(e)) {
offs[max_idx] = off;
off += e_size;
max_idx++;
if (max_idx < table_size)
goto fill_table;
max_idx--;
}
binary_search:
e_key_len = le16_to_cpu(e->key_size);
diff2 = (*cmp)(key, key_len, e + 1, e_key_len, ctx);
if (diff2 > 0) {
if (found) {
min_idx = mid_idx + 1;
} else {
if (de_is_last(e))
return NULL;
max_idx = 0;
table_size = min(table_size * 2, (int)ARRAY_SIZE(offs));
goto fill_table;
}
} else if (diff2 < 0) {
if (found)
max_idx = mid_idx - 1;
else
max_idx--;
found = e;
} else {
*diff = 0;
return e;
}
if (min_idx > max_idx) {
*diff = -1;
return found;
}
mid_idx = (min_idx + max_idx) >> 1;
e = Add2Ptr(hdr, offs[mid_idx]);
goto binary_search;
}
/*
* hdr_insert_de - Insert an index entry into the buffer.
*
* 'before' should be a pointer previously returned from hdr_find_e.
*/
static struct NTFS_DE *hdr_insert_de(const struct ntfs_index *indx,
struct INDEX_HDR *hdr,
const struct NTFS_DE *de,
struct NTFS_DE *before, const void *ctx)
{
int diff;
size_t off = PtrOffset(hdr, before);
u32 used = le32_to_cpu(hdr->used);
u32 total = le32_to_cpu(hdr->total);
u16 de_size = le16_to_cpu(de->size);
/* First, check to see if there's enough room. */
if (used + de_size > total)
return NULL;
/* We know there's enough space, so we know we'll succeed. */
if (before) {
/* Check that before is inside Index. */
if (off >= used || off < le32_to_cpu(hdr->de_off) ||
off + le16_to_cpu(before->size) > total) {
return NULL;
}
goto ok;
}
/* No insert point is applied. Get it manually. */
before = hdr_find_e(indx, hdr, de + 1, le16_to_cpu(de->key_size), ctx,
&diff);
if (!before)
return NULL;
off = PtrOffset(hdr, before);
ok:
/* Now we just make room for the entry and jam it in. */
memmove(Add2Ptr(before, de_size), before, used - off);
hdr->used = cpu_to_le32(used + de_size);
memcpy(before, de, de_size);
return before;
}
/*
* hdr_delete_de - Remove an entry from the index buffer.
*/
static inline struct NTFS_DE *hdr_delete_de(struct INDEX_HDR *hdr,
struct NTFS_DE *re)
{
u32 used = le32_to_cpu(hdr->used);
u16 esize = le16_to_cpu(re->size);
u32 off = PtrOffset(hdr, re);
int bytes = used - (off + esize);
/* check INDEX_HDR valid before using INDEX_HDR */
if (!check_index_header(hdr, le32_to_cpu(hdr->total)))
return NULL;
if (off >= used || esize < sizeof(struct NTFS_DE) ||
bytes < sizeof(struct NTFS_DE))
return NULL;
hdr->used = cpu_to_le32(used - esize);
memmove(re, Add2Ptr(re, esize), bytes);
return re;
}
void indx_clear(struct ntfs_index *indx)
{
run_close(&indx->alloc_run);
run_close(&indx->bitmap_run);
}
int indx_init(struct ntfs_index *indx, struct ntfs_sb_info *sbi,
const struct ATTRIB *attr, enum index_mutex_classed type)
{
u32 t32;
const struct INDEX_ROOT *root = resident_data(attr);
t32 = le32_to_cpu(attr->res.data_size);
if (t32 <= offsetof(struct INDEX_ROOT, ihdr) ||
!index_hdr_check(&root->ihdr,
t32 - offsetof(struct INDEX_ROOT, ihdr))) {
goto out;
}
/* Check root fields. */
if (!root->index_block_clst)
goto out;
indx->type = type;
indx->idx2vbn_bits = __ffs(root->index_block_clst);
t32 = le32_to_cpu(root->index_block_size);
indx->index_bits = blksize_bits(t32);
/* Check index record size. */
if (t32 < sbi->cluster_size) {
/* Index record is smaller than a cluster, use 512 blocks. */
if (t32 != root->index_block_clst * SECTOR_SIZE)
goto out;
/* Check alignment to a cluster. */
if ((sbi->cluster_size >> SECTOR_SHIFT) &
(root->index_block_clst - 1)) {
goto out;
}
indx->vbn2vbo_bits = SECTOR_SHIFT;
} else {
/* Index record must be a multiple of cluster size. */
if (t32 != root->index_block_clst << sbi->cluster_bits)
goto out;
indx->vbn2vbo_bits = sbi->cluster_bits;
}
init_rwsem(&indx->run_lock);
indx->cmp = get_cmp_func(root);
if (!indx->cmp)
goto out;
return 0;
out:
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
return -EINVAL;
}
static struct indx_node *indx_new(struct ntfs_index *indx,
struct ntfs_inode *ni, CLST vbn,
const __le64 *sub_vbn)
{
int err;
struct NTFS_DE *e;
struct indx_node *r;
struct INDEX_HDR *hdr;
struct INDEX_BUFFER *index;
u64 vbo = (u64)vbn << indx->vbn2vbo_bits;
u32 bytes = 1u << indx->index_bits;
u16 fn;
u32 eo;
r = kzalloc(sizeof(struct indx_node), GFP_NOFS);
if (!r)
return ERR_PTR(-ENOMEM);
index = kzalloc(bytes, GFP_NOFS);
if (!index) {
kfree(r);
return ERR_PTR(-ENOMEM);
}
err = ntfs_get_bh(ni->mi.sbi, &indx->alloc_run, vbo, bytes, &r->nb);
if (err) {
kfree(index);
kfree(r);
return ERR_PTR(err);
}
/* Create header. */
index->rhdr.sign = NTFS_INDX_SIGNATURE;
index->rhdr.fix_off = cpu_to_le16(sizeof(struct INDEX_BUFFER)); // 0x28
fn = (bytes >> SECTOR_SHIFT) + 1; // 9
index->rhdr.fix_num = cpu_to_le16(fn);
index->vbn = cpu_to_le64(vbn);
hdr = &index->ihdr;
eo = ALIGN(sizeof(struct INDEX_BUFFER) + fn * sizeof(short), 8);
hdr->de_off = cpu_to_le32(eo);
e = Add2Ptr(hdr, eo);
if (sub_vbn) {
e->flags = NTFS_IE_LAST | NTFS_IE_HAS_SUBNODES;
e->size = cpu_to_le16(sizeof(struct NTFS_DE) + sizeof(u64));
hdr->used =
cpu_to_le32(eo + sizeof(struct NTFS_DE) + sizeof(u64));
de_set_vbn_le(e, *sub_vbn);
hdr->flags = 1;
} else {
e->size = cpu_to_le16(sizeof(struct NTFS_DE));
hdr->used = cpu_to_le32(eo + sizeof(struct NTFS_DE));
e->flags = NTFS_IE_LAST;
}
hdr->total = cpu_to_le32(bytes - offsetof(struct INDEX_BUFFER, ihdr));
r->index = index;
return r;
}
struct INDEX_ROOT *indx_get_root(struct ntfs_index *indx, struct ntfs_inode *ni,
struct ATTRIB **attr, struct mft_inode **mi)
{
struct ATTR_LIST_ENTRY *le = NULL;
struct ATTRIB *a;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
struct INDEX_ROOT *root;
a = ni_find_attr(ni, NULL, &le, ATTR_ROOT, in->name, in->name_len, NULL,
mi);
if (!a)
return NULL;
if (attr)
*attr = a;
root = resident_data_ex(a, sizeof(struct INDEX_ROOT));
/* length check */
if (root &&
offsetof(struct INDEX_ROOT, ihdr) + le32_to_cpu(root->ihdr.used) >
le32_to_cpu(a->res.data_size)) {
return NULL;
}
return root;
}
static int indx_write(struct ntfs_index *indx, struct ntfs_inode *ni,
struct indx_node *node, int sync)
{
struct INDEX_BUFFER *ib = node->index;
return ntfs_write_bh(ni->mi.sbi, &ib->rhdr, &node->nb, sync);
}
/*
* indx_read
*
* If ntfs_readdir calls this function
* inode is shared locked and no ni_lock.
* Use rw_semaphore for read/write access to alloc_run.
*/
int indx_read(struct ntfs_index *indx, struct ntfs_inode *ni, CLST vbn,
struct indx_node **node)
{
int err;
struct INDEX_BUFFER *ib;
struct runs_tree *run = &indx->alloc_run;
struct rw_semaphore *lock = &indx->run_lock;
u64 vbo = (u64)vbn << indx->vbn2vbo_bits;
u32 bytes = 1u << indx->index_bits;
struct indx_node *in = *node;
const struct INDEX_NAMES *name;
if (!in) {
in = kzalloc(sizeof(struct indx_node), GFP_NOFS);
if (!in)
return -ENOMEM;
} else {
nb_put(&in->nb);
}
ib = in->index;
if (!ib) {
ib = kmalloc(bytes, GFP_NOFS);
if (!ib) {
err = -ENOMEM;
goto out;
}
}
down_read(lock);
err = ntfs_read_bh(ni->mi.sbi, run, vbo, &ib->rhdr, bytes, &in->nb);
up_read(lock);
if (!err)
goto ok;
if (err == -E_NTFS_FIXUP)
goto ok;
if (err != -ENOENT)
goto out;
name = &s_index_names[indx->type];
down_write(lock);
err = attr_load_runs_range(ni, ATTR_ALLOC, name->name, name->name_len,
run, vbo, vbo + bytes);
up_write(lock);
if (err)
goto out;
down_read(lock);
err = ntfs_read_bh(ni->mi.sbi, run, vbo, &ib->rhdr, bytes, &in->nb);
up_read(lock);
if (err == -E_NTFS_FIXUP)
goto ok;
if (err)
goto out;
ok:
if (!index_buf_check(ib, bytes, &vbn)) {
ntfs_inode_err(&ni->vfs_inode, "directory corrupted");
ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_ERROR);
err = -EINVAL;
goto out;
}
if (err == -E_NTFS_FIXUP) {
ntfs_write_bh(ni->mi.sbi, &ib->rhdr, &in->nb, 0);
err = 0;
}
/* check for index header length */
if (offsetof(struct INDEX_BUFFER, ihdr) + le32_to_cpu(ib->ihdr.used) >
bytes) {
err = -EINVAL;
goto out;
}
in->index = ib;
*node = in;
out:
if (err == -E_NTFS_CORRUPT) {
ntfs_inode_err(&ni->vfs_inode, "directory corrupted");
ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_ERROR);
err = -EINVAL;
}
if (ib != in->index)
kfree(ib);
if (*node != in) {
nb_put(&in->nb);
kfree(in);
}
return err;
}
/*
* indx_find - Scan NTFS directory for given entry.
*/
int indx_find(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct INDEX_ROOT *root, const void *key, size_t key_len,
const void *ctx, int *diff, struct NTFS_DE **entry,
struct ntfs_fnd *fnd)
{
int err;
struct NTFS_DE *e;
struct indx_node *node;
if (!root)
root = indx_get_root(&ni->dir, ni, NULL, NULL);
if (!root) {
/* Should not happen. */
return -EINVAL;
}
/* Check cache. */
e = fnd->level ? fnd->de[fnd->level - 1] : fnd->root_de;
if (e && !de_is_last(e) &&
!(*indx->cmp)(key, key_len, e + 1, le16_to_cpu(e->key_size), ctx)) {
*entry = e;
*diff = 0;
return 0;
}
/* Soft finder reset. */
fnd_clear(fnd);
/* Lookup entry that is <= to the search value. */
e = hdr_find_e(indx, &root->ihdr, key, key_len, ctx, diff);
if (!e)
return -EINVAL;
fnd->root_de = e;
for (;;) {
node = NULL;
if (*diff >= 0 || !de_has_vcn_ex(e))
break;
/* Read next level. */
err = indx_read(indx, ni, de_get_vbn(e), &node);
if (err) {
/* io error? */
return err;
}
/* Lookup entry that is <= to the search value. */
e = hdr_find_e(indx, &node->index->ihdr, key, key_len, ctx,
diff);
if (!e) {
put_indx_node(node);
return -EINVAL;
}
fnd_push(fnd, node, e);
}
*entry = e;
return 0;
}
int indx_find_sort(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct INDEX_ROOT *root, struct NTFS_DE **entry,
struct ntfs_fnd *fnd)
{
int err;
struct indx_node *n = NULL;
struct NTFS_DE *e;
size_t iter = 0;
int level = fnd->level;
if (!*entry) {
/* Start find. */
e = hdr_first_de(&root->ihdr);
if (!e)
return 0;
fnd_clear(fnd);
fnd->root_de = e;
} else if (!level) {
if (de_is_last(fnd->root_de)) {
*entry = NULL;
return 0;
}
e = hdr_next_de(&root->ihdr, fnd->root_de);
if (!e)
return -EINVAL;
fnd->root_de = e;
} else {
n = fnd->nodes[level - 1];
e = fnd->de[level - 1];
if (de_is_last(e))
goto pop_level;
e = hdr_next_de(&n->index->ihdr, e);
if (!e)
return -EINVAL;
fnd->de[level - 1] = e;
}
/* Just to avoid tree cycle. */
next_iter:
if (iter++ >= 1000)
return -EINVAL;
while (de_has_vcn_ex(e)) {
if (le16_to_cpu(e->size) <
sizeof(struct NTFS_DE) + sizeof(u64)) {
if (n) {
fnd_pop(fnd);
kfree(n);
}
return -EINVAL;
}
/* Read next level. */
err = indx_read(indx, ni, de_get_vbn(e), &n);
if (err)
return err;
/* Try next level. */
e = hdr_first_de(&n->index->ihdr);
if (!e) {
kfree(n);
return -EINVAL;
}
fnd_push(fnd, n, e);
}
if (le16_to_cpu(e->size) > sizeof(struct NTFS_DE)) {
*entry = e;
return 0;
}
pop_level:
for (;;) {
if (!de_is_last(e))
goto next_iter;
/* Pop one level. */
if (n) {
fnd_pop(fnd);
kfree(n);
}
level = fnd->level;
if (level) {
n = fnd->nodes[level - 1];
e = fnd->de[level - 1];
} else if (fnd->root_de) {
n = NULL;
e = fnd->root_de;
fnd->root_de = NULL;
} else {
*entry = NULL;
return 0;
}
if (le16_to_cpu(e->size) > sizeof(struct NTFS_DE)) {
*entry = e;
if (!fnd->root_de)
fnd->root_de = e;
return 0;
}
}
}
int indx_find_raw(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct INDEX_ROOT *root, struct NTFS_DE **entry,
size_t *off, struct ntfs_fnd *fnd)
{
int err;
struct indx_node *n = NULL;
struct NTFS_DE *e = NULL;
struct NTFS_DE *e2;
size_t bit;
CLST next_used_vbn;
CLST next_vbn;
u32 record_size = ni->mi.sbi->record_size;
/* Use non sorted algorithm. */
if (!*entry) {
/* This is the first call. */
e = hdr_first_de(&root->ihdr);
if (!e)
return 0;
fnd_clear(fnd);
fnd->root_de = e;
/* The first call with setup of initial element. */
if (*off >= record_size) {
next_vbn = (((*off - record_size) >> indx->index_bits))
<< indx->idx2vbn_bits;
/* Jump inside cycle 'for'. */
goto next;
}
/* Start enumeration from root. */
*off = 0;
} else if (!fnd->root_de)
return -EINVAL;
for (;;) {
/* Check if current entry can be used. */
if (e && le16_to_cpu(e->size) > sizeof(struct NTFS_DE))
goto ok;
if (!fnd->level) {
/* Continue to enumerate root. */
if (!de_is_last(fnd->root_de)) {
e = hdr_next_de(&root->ihdr, fnd->root_de);
if (!e)
return -EINVAL;
fnd->root_de = e;
continue;
}
/* Start to enumerate indexes from 0. */
next_vbn = 0;
} else {
/* Continue to enumerate indexes. */
e2 = fnd->de[fnd->level - 1];
n = fnd->nodes[fnd->level - 1];
if (!de_is_last(e2)) {
e = hdr_next_de(&n->index->ihdr, e2);
if (!e)
return -EINVAL;
fnd->de[fnd->level - 1] = e;
continue;
}
/* Continue with next index. */
next_vbn = le64_to_cpu(n->index->vbn) +
root->index_block_clst;
}
next:
/* Release current index. */
if (n) {
fnd_pop(fnd);
put_indx_node(n);
n = NULL;
}
/* Skip all free indexes. */
bit = next_vbn >> indx->idx2vbn_bits;
err = indx_used_bit(indx, ni, &bit);
if (err == -ENOENT || bit == MINUS_ONE_T) {
/* No used indexes. */
*entry = NULL;
return 0;
}
next_used_vbn = bit << indx->idx2vbn_bits;
/* Read buffer into memory. */
err = indx_read(indx, ni, next_used_vbn, &n);
if (err)
return err;
e = hdr_first_de(&n->index->ihdr);
fnd_push(fnd, n, e);
if (!e)
return -EINVAL;
}
ok:
/* Return offset to restore enumerator if necessary. */
if (!n) {
/* 'e' points in root, */
*off = PtrOffset(&root->ihdr, e);
} else {
/* 'e' points in index, */
*off = (le64_to_cpu(n->index->vbn) << indx->vbn2vbo_bits) +
record_size + PtrOffset(&n->index->ihdr, e);
}
*entry = e;
return 0;
}
/*
* indx_create_allocate - Create "Allocation + Bitmap" attributes.
*/
static int indx_create_allocate(struct ntfs_index *indx, struct ntfs_inode *ni,
CLST *vbn)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *bitmap;
struct ATTRIB *alloc;
u32 data_size = 1u << indx->index_bits;
u32 alloc_size = ntfs_up_cluster(sbi, data_size);
CLST len = alloc_size >> sbi->cluster_bits;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
CLST alen;
struct runs_tree run;
run_init(&run);
err = attr_allocate_clusters(sbi, &run, 0, 0, len, NULL, ALLOCATE_DEF,
&alen, 0, NULL, NULL);
if (err)
goto out;
err = ni_insert_nonresident(ni, ATTR_ALLOC, in->name, in->name_len,
&run, 0, len, 0, &alloc, NULL, NULL);
if (err)
goto out1;
alloc->nres.valid_size = alloc->nres.data_size = cpu_to_le64(data_size);
err = ni_insert_resident(ni, bitmap_size(1), ATTR_BITMAP, in->name,
in->name_len, &bitmap, NULL, NULL);
if (err)
goto out2;
if (in->name == I30_NAME) {
ni->vfs_inode.i_size = data_size;
inode_set_bytes(&ni->vfs_inode, alloc_size);
}
memcpy(&indx->alloc_run, &run, sizeof(run));
*vbn = 0;
return 0;
out2:
mi_remove_attr(NULL, &ni->mi, alloc);
out1:
run_deallocate(sbi, &run, false);
out:
return err;
}
/*
* indx_add_allocate - Add clusters to index.
*/
static int indx_add_allocate(struct ntfs_index *indx, struct ntfs_inode *ni,
CLST *vbn)
{
int err;
size_t bit;
u64 data_size;
u64 bmp_size, bmp_size_v;
struct ATTRIB *bmp, *alloc;
struct mft_inode *mi;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
err = indx_find_free(indx, ni, &bit, &bmp);
if (err)
goto out1;
if (bit != MINUS_ONE_T) {
bmp = NULL;
} else {
if (bmp->non_res) {
bmp_size = le64_to_cpu(bmp->nres.data_size);
bmp_size_v = le64_to_cpu(bmp->nres.valid_size);
} else {
bmp_size = bmp_size_v = le32_to_cpu(bmp->res.data_size);
}
bit = bmp_size << 3;
}
data_size = (u64)(bit + 1) << indx->index_bits;
if (bmp) {
/* Increase bitmap. */
err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
&indx->bitmap_run, bitmap_size(bit + 1),
NULL, true, NULL);
if (err)
goto out1;
}
alloc = ni_find_attr(ni, NULL, NULL, ATTR_ALLOC, in->name, in->name_len,
NULL, &mi);
if (!alloc) {
err = -EINVAL;
if (bmp)
goto out2;
goto out1;
}
/* Increase allocation. */
err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
&indx->alloc_run, data_size, &data_size, true,
NULL);
if (err) {
if (bmp)
goto out2;
goto out1;
}
if (in->name == I30_NAME)
ni->vfs_inode.i_size = data_size;
*vbn = bit << indx->idx2vbn_bits;
return 0;
out2:
/* Ops. No space? */
attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
&indx->bitmap_run, bmp_size, &bmp_size_v, false, NULL);
out1:
return err;
}
/*
* indx_insert_into_root - Attempt to insert an entry into the index root.
*
* @undo - True if we undoing previous remove.
* If necessary, it will twiddle the index b-tree.
*/
static int indx_insert_into_root(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct NTFS_DE *new_de,
struct NTFS_DE *root_de, const void *ctx,
struct ntfs_fnd *fnd, bool undo)
{
int err = 0;
struct NTFS_DE *e, *e0, *re;
struct mft_inode *mi;
struct ATTRIB *attr;
struct INDEX_HDR *hdr;
struct indx_node *n;
CLST new_vbn;
__le64 *sub_vbn, t_vbn;
u16 new_de_size;
u32 hdr_used, hdr_total, asize, to_move;
u32 root_size, new_root_size;
struct ntfs_sb_info *sbi;
int ds_root;
struct INDEX_ROOT *root, *a_root;
/* Get the record this root placed in. */
root = indx_get_root(indx, ni, &attr, &mi);
if (!root)
return -EINVAL;
/*
* Try easy case:
* hdr_insert_de will succeed if there's
* room the root for the new entry.
*/
hdr = &root->ihdr;
sbi = ni->mi.sbi;
new_de_size = le16_to_cpu(new_de->size);
hdr_used = le32_to_cpu(hdr->used);
hdr_total = le32_to_cpu(hdr->total);
asize = le32_to_cpu(attr->size);
root_size = le32_to_cpu(attr->res.data_size);
ds_root = new_de_size + hdr_used - hdr_total;
/* If 'undo' is set then reduce requirements. */
if ((undo || asize + ds_root < sbi->max_bytes_per_attr) &&
mi_resize_attr(mi, attr, ds_root)) {
hdr->total = cpu_to_le32(hdr_total + ds_root);
e = hdr_insert_de(indx, hdr, new_de, root_de, ctx);
WARN_ON(!e);
fnd_clear(fnd);
fnd->root_de = e;
return 0;
}
/* Make a copy of root attribute to restore if error. */
a_root = kmemdup(attr, asize, GFP_NOFS);
if (!a_root)
return -ENOMEM;
/*
* Copy all the non-end entries from
* the index root to the new buffer.
*/
to_move = 0;
e0 = hdr_first_de(hdr);
/* Calculate the size to copy. */
for (e = e0;; e = hdr_next_de(hdr, e)) {
if (!e) {
err = -EINVAL;
goto out_free_root;
}
if (de_is_last(e))
break;
to_move += le16_to_cpu(e->size);
}
if (!to_move) {
re = NULL;
} else {
re = kmemdup(e0, to_move, GFP_NOFS);
if (!re) {
err = -ENOMEM;
goto out_free_root;
}
}
sub_vbn = NULL;
if (de_has_vcn(e)) {
t_vbn = de_get_vbn_le(e);
sub_vbn = &t_vbn;
}
new_root_size = sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE) +
sizeof(u64);
ds_root = new_root_size - root_size;
if (ds_root > 0 && asize + ds_root > sbi->max_bytes_per_attr) {
/* Make root external. */
err = -EOPNOTSUPP;
goto out_free_re;
}
if (ds_root)
mi_resize_attr(mi, attr, ds_root);
/* Fill first entry (vcn will be set later). */
e = (struct NTFS_DE *)(root + 1);
memset(e, 0, sizeof(struct NTFS_DE));
e->size = cpu_to_le16(sizeof(struct NTFS_DE) + sizeof(u64));
e->flags = NTFS_IE_HAS_SUBNODES | NTFS_IE_LAST;
hdr->flags = 1;
hdr->used = hdr->total =
cpu_to_le32(new_root_size - offsetof(struct INDEX_ROOT, ihdr));
fnd->root_de = hdr_first_de(hdr);
mi->dirty = true;
/* Create alloc and bitmap attributes (if not). */
err = run_is_empty(&indx->alloc_run) ?
indx_create_allocate(indx, ni, &new_vbn) :
indx_add_allocate(indx, ni, &new_vbn);
/* Layout of record may be changed, so rescan root. */
root = indx_get_root(indx, ni, &attr, &mi);
if (!root) {
/* Bug? */
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
err = -EINVAL;
goto out_free_re;
}
if (err) {
/* Restore root. */
if (mi_resize_attr(mi, attr, -ds_root)) {
memcpy(attr, a_root, asize);
} else {
/* Bug? */
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
}
goto out_free_re;
}
e = (struct NTFS_DE *)(root + 1);
*(__le64 *)(e + 1) = cpu_to_le64(new_vbn);
mi->dirty = true;
/* Now we can create/format the new buffer and copy the entries into. */
n = indx_new(indx, ni, new_vbn, sub_vbn);
if (IS_ERR(n)) {
err = PTR_ERR(n);
goto out_free_re;
}
hdr = &n->index->ihdr;
hdr_used = le32_to_cpu(hdr->used);
hdr_total = le32_to_cpu(hdr->total);
/* Copy root entries into new buffer. */
hdr_insert_head(hdr, re, to_move);
/* Update bitmap attribute. */
indx_mark_used(indx, ni, new_vbn >> indx->idx2vbn_bits);
/* Check if we can insert new entry new index buffer. */
if (hdr_used + new_de_size > hdr_total) {
/*
* This occurs if MFT record is the same or bigger than index
* buffer. Move all root new index and have no space to add
* new entry classic case when MFT record is 1K and index
* buffer 4K the problem should not occurs.
*/
kfree(re);
indx_write(indx, ni, n, 0);
put_indx_node(n);
fnd_clear(fnd);
err = indx_insert_entry(indx, ni, new_de, ctx, fnd, undo);
goto out_free_root;
}
/*
* Now root is a parent for new index buffer.
* Insert NewEntry a new buffer.
*/
e = hdr_insert_de(indx, hdr, new_de, NULL, ctx);
if (!e) {
err = -EINVAL;
goto out_put_n;
}
fnd_push(fnd, n, e);
/* Just write updates index into disk. */
indx_write(indx, ni, n, 0);
n = NULL;
out_put_n:
put_indx_node(n);
out_free_re:
kfree(re);
out_free_root:
kfree(a_root);
return err;
}
/*
* indx_insert_into_buffer
*
* Attempt to insert an entry into an Index Allocation Buffer.
* If necessary, it will split the buffer.
*/
static int
indx_insert_into_buffer(struct ntfs_index *indx, struct ntfs_inode *ni,
struct INDEX_ROOT *root, const struct NTFS_DE *new_de,
const void *ctx, int level, struct ntfs_fnd *fnd)
{
int err;
const struct NTFS_DE *sp;
struct NTFS_DE *e, *de_t, *up_e;
struct indx_node *n2;
struct indx_node *n1 = fnd->nodes[level];
struct INDEX_HDR *hdr1 = &n1->index->ihdr;
struct INDEX_HDR *hdr2;
u32 to_copy, used, used1;
CLST new_vbn;
__le64 t_vbn, *sub_vbn;
u16 sp_size;
void *hdr1_saved = NULL;
/* Try the most easy case. */
e = fnd->level - 1 == level ? fnd->de[level] : NULL;
e = hdr_insert_de(indx, hdr1, new_de, e, ctx);
fnd->de[level] = e;
if (e) {
/* Just write updated index into disk. */
indx_write(indx, ni, n1, 0);
return 0;
}
/*
* No space to insert into buffer. Split it.
* To split we:
* - Save split point ('cause index buffers will be changed)
* - Allocate NewBuffer and copy all entries <= sp into new buffer
* - Remove all entries (sp including) from TargetBuffer
* - Insert NewEntry into left or right buffer (depending on sp <=>
* NewEntry)
* - Insert sp into parent buffer (or root)
* - Make sp a parent for new buffer
*/
sp = hdr_find_split(hdr1);
if (!sp)
return -EINVAL;
sp_size = le16_to_cpu(sp->size);
up_e = kmalloc(sp_size + sizeof(u64), GFP_NOFS);
if (!up_e)
return -ENOMEM;
memcpy(up_e, sp, sp_size);
used1 = le32_to_cpu(hdr1->used);
hdr1_saved = kmemdup(hdr1, used1, GFP_NOFS);
if (!hdr1_saved) {
err = -ENOMEM;
goto out;
}
if (!hdr1->flags) {
up_e->flags |= NTFS_IE_HAS_SUBNODES;
up_e->size = cpu_to_le16(sp_size + sizeof(u64));
sub_vbn = NULL;
} else {
t_vbn = de_get_vbn_le(up_e);
sub_vbn = &t_vbn;
}
/* Allocate on disk a new index allocation buffer. */
err = indx_add_allocate(indx, ni, &new_vbn);
if (err)
goto out;
/* Allocate and format memory a new index buffer. */
n2 = indx_new(indx, ni, new_vbn, sub_vbn);
if (IS_ERR(n2)) {
err = PTR_ERR(n2);
goto out;
}
hdr2 = &n2->index->ihdr;
/* Make sp a parent for new buffer. */
de_set_vbn(up_e, new_vbn);
/* Copy all the entries <= sp into the new buffer. */
de_t = hdr_first_de(hdr1);
to_copy = PtrOffset(de_t, sp);
hdr_insert_head(hdr2, de_t, to_copy);
/* Remove all entries (sp including) from hdr1. */
used = used1 - to_copy - sp_size;
memmove(de_t, Add2Ptr(sp, sp_size), used - le32_to_cpu(hdr1->de_off));
hdr1->used = cpu_to_le32(used);
/*
* Insert new entry into left or right buffer
* (depending on sp <=> new_de).
*/
hdr_insert_de(indx,
(*indx->cmp)(new_de + 1, le16_to_cpu(new_de->key_size),
up_e + 1, le16_to_cpu(up_e->key_size),
ctx) < 0 ?
hdr2 :
hdr1,
new_de, NULL, ctx);
indx_mark_used(indx, ni, new_vbn >> indx->idx2vbn_bits);
indx_write(indx, ni, n1, 0);
indx_write(indx, ni, n2, 0);
put_indx_node(n2);
/*
* We've finished splitting everybody, so we are ready to
* insert the promoted entry into the parent.
*/
if (!level) {
/* Insert in root. */
err = indx_insert_into_root(indx, ni, up_e, NULL, ctx, fnd, 0);
} else {
/*
* The target buffer's parent is another index buffer.
* TODO: Remove recursion.
*/
err = indx_insert_into_buffer(indx, ni, root, up_e, ctx,
level - 1, fnd);
}
if (err) {
/*
* Undo critical operations.
*/
indx_mark_free(indx, ni, new_vbn >> indx->idx2vbn_bits);
memcpy(hdr1, hdr1_saved, used1);
indx_write(indx, ni, n1, 0);
}
out:
kfree(up_e);
kfree(hdr1_saved);
return err;
}
/*
* indx_insert_entry - Insert new entry into index.
*
* @undo - True if we undoing previous remove.
*/
int indx_insert_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct NTFS_DE *new_de, const void *ctx,
struct ntfs_fnd *fnd, bool undo)
{
int err;
int diff;
struct NTFS_DE *e;
struct ntfs_fnd *fnd_a = NULL;
struct INDEX_ROOT *root;
if (!fnd) {
fnd_a = fnd_get();
if (!fnd_a) {
err = -ENOMEM;
goto out1;
}
fnd = fnd_a;
}
root = indx_get_root(indx, ni, NULL, NULL);
if (!root) {
err = -EINVAL;
goto out;
}
if (fnd_is_empty(fnd)) {
/*
* Find the spot the tree where we want to
* insert the new entry.
*/
err = indx_find(indx, ni, root, new_de + 1,
le16_to_cpu(new_de->key_size), ctx, &diff, &e,
fnd);
if (err)
goto out;
if (!diff) {
err = -EEXIST;
goto out;
}
}
if (!fnd->level) {
/*
* The root is also a leaf, so we'll insert the
* new entry into it.
*/
err = indx_insert_into_root(indx, ni, new_de, fnd->root_de, ctx,
fnd, undo);
} else {
/*
* Found a leaf buffer, so we'll insert the new entry into it.
*/
err = indx_insert_into_buffer(indx, ni, root, new_de, ctx,
fnd->level - 1, fnd);
}
out:
fnd_put(fnd_a);
out1:
return err;
}
/*
* indx_find_buffer - Locate a buffer from the tree.
*/
static struct indx_node *indx_find_buffer(struct ntfs_index *indx,
struct ntfs_inode *ni,
const struct INDEX_ROOT *root,
__le64 vbn, struct indx_node *n)
{
int err;
const struct NTFS_DE *e;
struct indx_node *r;
const struct INDEX_HDR *hdr = n ? &n->index->ihdr : &root->ihdr;
/* Step 1: Scan one level. */
for (e = hdr_first_de(hdr);; e = hdr_next_de(hdr, e)) {
if (!e)
return ERR_PTR(-EINVAL);
if (de_has_vcn(e) && vbn == de_get_vbn_le(e))
return n;
if (de_is_last(e))
break;
}
/* Step2: Do recursion. */
e = Add2Ptr(hdr, le32_to_cpu(hdr->de_off));
for (;;) {
if (de_has_vcn_ex(e)) {
err = indx_read(indx, ni, de_get_vbn(e), &n);
if (err)
return ERR_PTR(err);
r = indx_find_buffer(indx, ni, root, vbn, n);
if (r)
return r;
}
if (de_is_last(e))
break;
e = Add2Ptr(e, le16_to_cpu(e->size));
}
return NULL;
}
/*
* indx_shrink - Deallocate unused tail indexes.
*/
static int indx_shrink(struct ntfs_index *indx, struct ntfs_inode *ni,
size_t bit)
{
int err = 0;
u64 bpb, new_data;
size_t nbits;
struct ATTRIB *b;
struct ATTR_LIST_ENTRY *le = NULL;
const struct INDEX_NAMES *in = &s_index_names[indx->type];
b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
NULL, NULL);
if (!b)
return -ENOENT;
if (!b->non_res) {
unsigned long pos;
const unsigned long *bm = resident_data(b);
nbits = (size_t)le32_to_cpu(b->res.data_size) * 8;
if (bit >= nbits)
return 0;
pos = find_next_bit_le(bm, nbits, bit);
if (pos < nbits)
return 0;
} else {
size_t used = MINUS_ONE_T;
nbits = le64_to_cpu(b->nres.data_size) * 8;
if (bit >= nbits)
return 0;
err = scan_nres_bitmap(ni, b, indx, bit, &scan_for_used, &used);
if (err)
return err;
if (used != MINUS_ONE_T)
return 0;
}
new_data = (u64)bit << indx->index_bits;
err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
&indx->alloc_run, new_data, &new_data, false, NULL);
if (err)
return err;
if (in->name == I30_NAME)
ni->vfs_inode.i_size = new_data;
bpb = bitmap_size(bit);
if (bpb * 8 == nbits)
return 0;
err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
&indx->bitmap_run, bpb, &bpb, false, NULL);
return err;
}
static int indx_free_children(struct ntfs_index *indx, struct ntfs_inode *ni,
const struct NTFS_DE *e, bool trim)
{
int err;
struct indx_node *n = NULL;
struct INDEX_HDR *hdr;
CLST vbn = de_get_vbn(e);
size_t i;
err = indx_read(indx, ni, vbn, &n);
if (err)
return err;
hdr = &n->index->ihdr;
/* First, recurse into the children, if any. */
if (hdr_has_subnode(hdr)) {
for (e = hdr_first_de(hdr); e; e = hdr_next_de(hdr, e)) {
indx_free_children(indx, ni, e, false);
if (de_is_last(e))
break;
}
}
put_indx_node(n);
i = vbn >> indx->idx2vbn_bits;
/*
* We've gotten rid of the children; add this buffer to the free list.
*/
indx_mark_free(indx, ni, i);
if (!trim)
return 0;
/*
* If there are no used indexes after current free index
* then we can truncate allocation and bitmap.
* Use bitmap to estimate the case.
*/
indx_shrink(indx, ni, i + 1);
return 0;
}
/*
* indx_get_entry_to_replace
*
* Find a replacement entry for a deleted entry.
* Always returns a node entry:
* NTFS_IE_HAS_SUBNODES is set the flags and the size includes the sub_vcn.
*/
static int indx_get_entry_to_replace(struct ntfs_index *indx,
struct ntfs_inode *ni,
const struct NTFS_DE *de_next,
struct NTFS_DE **de_to_replace,
struct ntfs_fnd *fnd)
{
int err;
int level = -1;
CLST vbn;
struct NTFS_DE *e, *te, *re;
struct indx_node *n;
struct INDEX_BUFFER *ib;
*de_to_replace = NULL;
/* Find first leaf entry down from de_next. */
vbn = de_get_vbn(de_next);
for (;;) {
n = NULL;
err = indx_read(indx, ni, vbn, &n);
if (err)
goto out;
e = hdr_first_de(&n->index->ihdr);
fnd_push(fnd, n, e);
if (!de_is_last(e)) {
/*
* This buffer is non-empty, so its first entry
* could be used as the replacement entry.
*/
level = fnd->level - 1;
}
if (!de_has_vcn(e))
break;
/* This buffer is a node. Continue to go down. */
vbn = de_get_vbn(e);
}
if (level == -1)
goto out;
n = fnd->nodes[level];
te = hdr_first_de(&n->index->ihdr);
/* Copy the candidate entry into the replacement entry buffer. */
re = kmalloc(le16_to_cpu(te->size) + sizeof(u64), GFP_NOFS);
if (!re) {
err = -ENOMEM;
goto out;
}
*de_to_replace = re;
memcpy(re, te, le16_to_cpu(te->size));
if (!de_has_vcn(re)) {
/*
* The replacement entry we found doesn't have a sub_vcn.
* increase its size to hold one.
*/
le16_add_cpu(&re->size, sizeof(u64));
re->flags |= NTFS_IE_HAS_SUBNODES;
} else {
/*
* The replacement entry we found was a node entry, which
* means that all its child buffers are empty. Return them
* to the free pool.
*/
indx_free_children(indx, ni, te, true);
}
/*
* Expunge the replacement entry from its former location,
* and then write that buffer.
*/
ib = n->index;
e = hdr_delete_de(&ib->ihdr, te);
fnd->de[level] = e;
indx_write(indx, ni, n, 0);
if (ib_is_leaf(ib) && ib_is_empty(ib)) {
/* An empty leaf. */
return 0;
}
out:
fnd_clear(fnd);
return err;
}
/*
* indx_delete_entry - Delete an entry from the index.
*/
int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
const void *key, u32 key_len, const void *ctx)
{
int err, diff;
struct INDEX_ROOT *root;
struct INDEX_HDR *hdr;
struct ntfs_fnd *fnd, *fnd2;
struct INDEX_BUFFER *ib;
struct NTFS_DE *e, *re, *next, *prev, *me;
struct indx_node *n, *n2d = NULL;
__le64 sub_vbn;
int level, level2;
struct ATTRIB *attr;
struct mft_inode *mi;
u32 e_size, root_size, new_root_size;
size_t trim_bit;
const struct INDEX_NAMES *in;
fnd = fnd_get();
if (!fnd) {
err = -ENOMEM;
goto out2;
}
fnd2 = fnd_get();
if (!fnd2) {
err = -ENOMEM;
goto out1;
}
root = indx_get_root(indx, ni, &attr, &mi);
if (!root) {
err = -EINVAL;
goto out;
}
/* Locate the entry to remove. */
err = indx_find(indx, ni, root, key, key_len, ctx, &diff, &e, fnd);
if (err)
goto out;
if (!e || diff) {
err = -ENOENT;
goto out;
}
level = fnd->level;
if (level) {
n = fnd->nodes[level - 1];
e = fnd->de[level - 1];
ib = n->index;
hdr = &ib->ihdr;
} else {
hdr = &root->ihdr;
e = fnd->root_de;
n = NULL;
}
e_size = le16_to_cpu(e->size);
if (!de_has_vcn_ex(e)) {
/* The entry to delete is a leaf, so we can just rip it out. */
hdr_delete_de(hdr, e);
if (!level) {
hdr->total = hdr->used;
/* Shrink resident root attribute. */
mi_resize_attr(mi, attr, 0 - e_size);
goto out;
}
indx_write(indx, ni, n, 0);
/*
* Check to see if removing that entry made
* the leaf empty.
*/
if (ib_is_leaf(ib) && ib_is_empty(ib)) {
fnd_pop(fnd);
fnd_push(fnd2, n, e);
}
} else {
/*
* The entry we wish to delete is a node buffer, so we
* have to find a replacement for it.
*/
next = de_get_next(e);
err = indx_get_entry_to_replace(indx, ni, next, &re, fnd2);
if (err)
goto out;
if (re) {
de_set_vbn_le(re, de_get_vbn_le(e));
hdr_delete_de(hdr, e);
err = level ? indx_insert_into_buffer(indx, ni, root,
re, ctx,
fnd->level - 1,
fnd) :
indx_insert_into_root(indx, ni, re, e,
ctx, fnd, 0);
kfree(re);
if (err)
goto out;
} else {
/*
* There is no replacement for the current entry.
* This means that the subtree rooted at its node
* is empty, and can be deleted, which turn means
* that the node can just inherit the deleted
* entry sub_vcn.
*/
indx_free_children(indx, ni, next, true);
de_set_vbn_le(next, de_get_vbn_le(e));
hdr_delete_de(hdr, e);
if (level) {
indx_write(indx, ni, n, 0);
} else {
hdr->total = hdr->used;
/* Shrink resident root attribute. */
mi_resize_attr(mi, attr, 0 - e_size);
}
}
}
/* Delete a branch of tree. */
if (!fnd2 || !fnd2->level)
goto out;
/* Reinit root 'cause it can be changed. */
root = indx_get_root(indx, ni, &attr, &mi);
if (!root) {
err = -EINVAL;
goto out;
}
n2d = NULL;
sub_vbn = fnd2->nodes[0]->index->vbn;
level2 = 0;
level = fnd->level;
hdr = level ? &fnd->nodes[level - 1]->index->ihdr : &root->ihdr;
/* Scan current level. */
for (e = hdr_first_de(hdr);; e = hdr_next_de(hdr, e)) {
if (!e) {
err = -EINVAL;
goto out;
}
if (de_has_vcn(e) && sub_vbn == de_get_vbn_le(e))
break;
if (de_is_last(e)) {
e = NULL;
break;
}
}
if (!e) {
/* Do slow search from root. */
struct indx_node *in;
fnd_clear(fnd);
in = indx_find_buffer(indx, ni, root, sub_vbn, NULL);
if (IS_ERR(in)) {
err = PTR_ERR(in);
goto out;
}
if (in)
fnd_push(fnd, in, NULL);
}
/* Merge fnd2 -> fnd. */
for (level = 0; level < fnd2->level; level++) {
fnd_push(fnd, fnd2->nodes[level], fnd2->de[level]);
fnd2->nodes[level] = NULL;
}
fnd2->level = 0;
hdr = NULL;
for (level = fnd->level; level; level--) {
struct indx_node *in = fnd->nodes[level - 1];
ib = in->index;
if (ib_is_empty(ib)) {
sub_vbn = ib->vbn;
} else {
hdr = &ib->ihdr;
n2d = in;
level2 = level;
break;
}
}
if (!hdr)
hdr = &root->ihdr;
e = hdr_first_de(hdr);
if (!e) {
err = -EINVAL;
goto out;
}
if (hdr != &root->ihdr || !de_is_last(e)) {
prev = NULL;
while (!de_is_last(e)) {
if (de_has_vcn(e) && sub_vbn == de_get_vbn_le(e))
break;
prev = e;
e = hdr_next_de(hdr, e);
if (!e) {
err = -EINVAL;
goto out;
}
}
if (sub_vbn != de_get_vbn_le(e)) {
/*
* Didn't find the parent entry, although this buffer
* is the parent trail. Something is corrupt.
*/
err = -EINVAL;
goto out;
}
if (de_is_last(e)) {
/*
* Since we can't remove the end entry, we'll remove
* its predecessor instead. This means we have to
* transfer the predecessor's sub_vcn to the end entry.
* Note: This index block is not empty, so the
* predecessor must exist.
*/
if (!prev) {
err = -EINVAL;
goto out;
}
if (de_has_vcn(prev)) {
de_set_vbn_le(e, de_get_vbn_le(prev));
} else if (de_has_vcn(e)) {
le16_sub_cpu(&e->size, sizeof(u64));
e->flags &= ~NTFS_IE_HAS_SUBNODES;
le32_sub_cpu(&hdr->used, sizeof(u64));
}
e = prev;
}
/*
* Copy the current entry into a temporary buffer (stripping
* off its down-pointer, if any) and delete it from the current
* buffer or root, as appropriate.
*/
e_size = le16_to_cpu(e->size);
me = kmemdup(e, e_size, GFP_NOFS);
if (!me) {
err = -ENOMEM;
goto out;
}
if (de_has_vcn(me)) {
me->flags &= ~NTFS_IE_HAS_SUBNODES;
le16_sub_cpu(&me->size, sizeof(u64));
}
hdr_delete_de(hdr, e);
if (hdr == &root->ihdr) {
level = 0;
hdr->total = hdr->used;
/* Shrink resident root attribute. */
mi_resize_attr(mi, attr, 0 - e_size);
} else {
indx_write(indx, ni, n2d, 0);
level = level2;
}
/* Mark unused buffers as free. */
trim_bit = -1;
for (; level < fnd->level; level++) {
ib = fnd->nodes[level]->index;
if (ib_is_empty(ib)) {
size_t k = le64_to_cpu(ib->vbn) >>
indx->idx2vbn_bits;
indx_mark_free(indx, ni, k);
if (k < trim_bit)
trim_bit = k;
}
}
fnd_clear(fnd);
/*fnd->root_de = NULL;*/
/*
* Re-insert the entry into the tree.
* Find the spot the tree where we want to insert the new entry.
*/
err = indx_insert_entry(indx, ni, me, ctx, fnd, 0);
kfree(me);
if (err)
goto out;
if (trim_bit != -1)
indx_shrink(indx, ni, trim_bit);
} else {
/*
* This tree needs to be collapsed down to an empty root.
* Recreate the index root as an empty leaf and free all
* the bits the index allocation bitmap.
*/
fnd_clear(fnd);
fnd_clear(fnd2);
in = &s_index_names[indx->type];
err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
&indx->alloc_run, 0, NULL, false, NULL);
if (in->name == I30_NAME)
ni->vfs_inode.i_size = 0;
err = ni_remove_attr(ni, ATTR_ALLOC, in->name, in->name_len,
false, NULL);
run_close(&indx->alloc_run);
err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
&indx->bitmap_run, 0, NULL, false, NULL);
err = ni_remove_attr(ni, ATTR_BITMAP, in->name, in->name_len,
false, NULL);
run_close(&indx->bitmap_run);
root = indx_get_root(indx, ni, &attr, &mi);
if (!root) {
err = -EINVAL;
goto out;
}
root_size = le32_to_cpu(attr->res.data_size);
new_root_size =
sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE);
if (new_root_size != root_size &&
!mi_resize_attr(mi, attr, new_root_size - root_size)) {
err = -EINVAL;
goto out;
}
/* Fill first entry. */
e = (struct NTFS_DE *)(root + 1);
e->ref.low = 0;
e->ref.high = 0;
e->ref.seq = 0;
e->size = cpu_to_le16(sizeof(struct NTFS_DE));
e->flags = NTFS_IE_LAST; // 0x02
e->key_size = 0;
e->res = 0;
hdr = &root->ihdr;
hdr->flags = 0;
hdr->used = hdr->total = cpu_to_le32(
new_root_size - offsetof(struct INDEX_ROOT, ihdr));
mi->dirty = true;
}
out:
fnd_put(fnd2);
out1:
fnd_put(fnd);
out2:
return err;
}
/*
* Update duplicated information in directory entry
* 'dup' - info from MFT record
*/
int indx_update_dup(struct ntfs_inode *ni, struct ntfs_sb_info *sbi,
const struct ATTR_FILE_NAME *fname,
const struct NTFS_DUP_INFO *dup, int sync)
{
int err, diff;
struct NTFS_DE *e = NULL;
struct ATTR_FILE_NAME *e_fname;
struct ntfs_fnd *fnd;
struct INDEX_ROOT *root;
struct mft_inode *mi;
struct ntfs_index *indx = &ni->dir;
fnd = fnd_get();
if (!fnd)
return -ENOMEM;
root = indx_get_root(indx, ni, NULL, &mi);
if (!root) {
err = -EINVAL;
goto out;
}
/* Find entry in directory. */
err = indx_find(indx, ni, root, fname, fname_full_size(fname), sbi,
&diff, &e, fnd);
if (err)
goto out;
if (!e) {
err = -EINVAL;
goto out;
}
if (diff) {
err = -EINVAL;
goto out;
}
e_fname = (struct ATTR_FILE_NAME *)(e + 1);
if (!memcmp(&e_fname->dup, dup, sizeof(*dup))) {
/*
* Nothing to update in index! Try to avoid this call.
*/
goto out;
}
memcpy(&e_fname->dup, dup, sizeof(*dup));
if (fnd->level) {
/* Directory entry in index. */
err = indx_write(indx, ni, fnd->nodes[fnd->level - 1], sync);
} else {
/* Directory entry in directory MFT record. */
mi->dirty = true;
if (sync)
err = mi_write(mi, 1);
else
mark_inode_dirty(&ni->vfs_inode);
}
out:
fnd_put(fnd);
return err;
}
| linux-master | fs/ntfs3/index.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/fs.h>
#include <linux/nls.h>
#include <linux/ctype.h>
#include <linux/posix_acl.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* fill_name_de - Format NTFS_DE in @buf.
*/
int fill_name_de(struct ntfs_sb_info *sbi, void *buf, const struct qstr *name,
const struct cpu_str *uni)
{
int err;
struct NTFS_DE *e = buf;
u16 data_size;
struct ATTR_FILE_NAME *fname = (struct ATTR_FILE_NAME *)(e + 1);
#ifndef CONFIG_NTFS3_64BIT_CLUSTER
e->ref.high = fname->home.high = 0;
#endif
if (uni) {
#ifdef __BIG_ENDIAN
int ulen = uni->len;
__le16 *uname = fname->name;
const u16 *name_cpu = uni->name;
while (ulen--)
*uname++ = cpu_to_le16(*name_cpu++);
#else
memcpy(fname->name, uni->name, uni->len * sizeof(u16));
#endif
fname->name_len = uni->len;
} else {
/* Convert input string to unicode. */
err = ntfs_nls_to_utf16(sbi, name->name, name->len,
(struct cpu_str *)&fname->name_len,
NTFS_NAME_LEN, UTF16_LITTLE_ENDIAN);
if (err < 0)
return err;
}
fname->type = FILE_NAME_POSIX;
data_size = fname_full_size(fname);
e->size = cpu_to_le16(ALIGN(data_size, 8) + sizeof(struct NTFS_DE));
e->key_size = cpu_to_le16(data_size);
e->flags = 0;
e->res = 0;
return 0;
}
/*
* ntfs_lookup - inode_operations::lookup
*/
static struct dentry *ntfs_lookup(struct inode *dir, struct dentry *dentry,
u32 flags)
{
struct ntfs_inode *ni = ntfs_i(dir);
struct cpu_str *uni = __getname();
struct inode *inode;
int err;
if (!uni)
inode = ERR_PTR(-ENOMEM);
else {
err = ntfs_nls_to_utf16(ni->mi.sbi, dentry->d_name.name,
dentry->d_name.len, uni, NTFS_NAME_LEN,
UTF16_HOST_ENDIAN);
if (err < 0)
inode = ERR_PTR(err);
else {
ni_lock(ni);
inode = dir_search_u(dir, uni, NULL);
ni_unlock(ni);
}
__putname(uni);
}
/*
* Check for a null pointer
* If the MFT record of ntfs inode is not a base record, inode->i_op can be NULL.
* This causes null pointer dereference in d_splice_alias().
*/
if (!IS_ERR_OR_NULL(inode) && !inode->i_op) {
iput(inode);
inode = ERR_PTR(-EINVAL);
}
return d_splice_alias(inode, dentry);
}
/*
* ntfs_create - inode_operations::create
*/
static int ntfs_create(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, bool excl)
{
struct inode *inode;
inode = ntfs_create_inode(idmap, dir, dentry, NULL, S_IFREG | mode, 0,
NULL, 0, NULL);
return IS_ERR(inode) ? PTR_ERR(inode) : 0;
}
/*
* ntfs_mknod
*
* inode_operations::mknod
*/
static int ntfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, dev_t rdev)
{
struct inode *inode;
inode = ntfs_create_inode(idmap, dir, dentry, NULL, mode, rdev, NULL, 0,
NULL);
return IS_ERR(inode) ? PTR_ERR(inode) : 0;
}
/*
* ntfs_link - inode_operations::link
*/
static int ntfs_link(struct dentry *ode, struct inode *dir, struct dentry *de)
{
int err;
struct inode *inode = d_inode(ode);
struct ntfs_inode *ni = ntfs_i(inode);
if (S_ISDIR(inode->i_mode))
return -EPERM;
if (inode->i_nlink >= NTFS_LINK_MAX)
return -EMLINK;
ni_lock_dir(ntfs_i(dir));
if (inode != dir)
ni_lock(ni);
inc_nlink(inode);
ihold(inode);
err = ntfs_link_inode(inode, de);
if (!err) {
dir->i_mtime = inode_set_ctime_to_ts(inode,
inode_set_ctime_current(dir));
mark_inode_dirty(inode);
mark_inode_dirty(dir);
d_instantiate(de, inode);
} else {
drop_nlink(inode);
iput(inode);
}
if (inode != dir)
ni_unlock(ni);
ni_unlock(ntfs_i(dir));
return err;
}
/*
* ntfs_unlink - inode_operations::unlink
*/
static int ntfs_unlink(struct inode *dir, struct dentry *dentry)
{
struct ntfs_inode *ni = ntfs_i(dir);
int err;
ni_lock_dir(ni);
err = ntfs_unlink_inode(dir, dentry);
ni_unlock(ni);
return err;
}
/*
* ntfs_symlink - inode_operations::symlink
*/
static int ntfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, const char *symname)
{
u32 size = strlen(symname);
struct inode *inode;
inode = ntfs_create_inode(idmap, dir, dentry, NULL, S_IFLNK | 0777, 0,
symname, size, NULL);
return IS_ERR(inode) ? PTR_ERR(inode) : 0;
}
/*
* ntfs_mkdir- inode_operations::mkdir
*/
static int ntfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode)
{
struct inode *inode;
inode = ntfs_create_inode(idmap, dir, dentry, NULL, S_IFDIR | mode, 0,
NULL, 0, NULL);
return IS_ERR(inode) ? PTR_ERR(inode) : 0;
}
/*
* ntfs_rmdir - inode_operations::rmdir
*/
static int ntfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct ntfs_inode *ni = ntfs_i(dir);
int err;
ni_lock_dir(ni);
err = ntfs_unlink_inode(dir, dentry);
ni_unlock(ni);
return err;
}
/*
* ntfs_rename - inode_operations::rename
*/
static int ntfs_rename(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, struct inode *new_dir,
struct dentry *new_dentry, u32 flags)
{
int err;
struct super_block *sb = dir->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *dir_ni = ntfs_i(dir);
struct ntfs_inode *new_dir_ni = ntfs_i(new_dir);
struct inode *inode = d_inode(dentry);
struct ntfs_inode *ni = ntfs_i(inode);
struct inode *new_inode = d_inode(new_dentry);
struct NTFS_DE *de, *new_de;
bool is_same, is_bad;
/*
* de - memory of PATH_MAX bytes:
* [0-1024) - original name (dentry->d_name)
* [1024-2048) - paired to original name, usually DOS variant of dentry->d_name
* [2048-3072) - new name (new_dentry->d_name)
*/
static_assert(SIZEOF_ATTRIBUTE_FILENAME_MAX + SIZEOF_RESIDENT < 1024);
static_assert(SIZEOF_ATTRIBUTE_FILENAME_MAX + sizeof(struct NTFS_DE) <
1024);
static_assert(PATH_MAX >= 4 * 1024);
if (flags & ~RENAME_NOREPLACE)
return -EINVAL;
is_same = dentry->d_name.len == new_dentry->d_name.len &&
!memcmp(dentry->d_name.name, new_dentry->d_name.name,
dentry->d_name.len);
if (is_same && dir == new_dir) {
/* Nothing to do. */
return 0;
}
if (ntfs_is_meta_file(sbi, inode->i_ino)) {
/* Should we print an error? */
return -EINVAL;
}
if (new_inode) {
/* Target name exists. Unlink it. */
dget(new_dentry);
ni_lock_dir(new_dir_ni);
err = ntfs_unlink_inode(new_dir, new_dentry);
ni_unlock(new_dir_ni);
dput(new_dentry);
if (err)
return err;
}
/* Allocate PATH_MAX bytes. */
de = __getname();
if (!de)
return -ENOMEM;
/* Translate dentry->d_name into unicode form. */
err = fill_name_de(sbi, de, &dentry->d_name, NULL);
if (err < 0)
goto out;
if (is_same) {
/* Reuse 'de'. */
new_de = de;
} else {
/* Translate new_dentry->d_name into unicode form. */
new_de = Add2Ptr(de, 2048);
err = fill_name_de(sbi, new_de, &new_dentry->d_name, NULL);
if (err < 0)
goto out;
}
ni_lock_dir(dir_ni);
ni_lock(ni);
if (dir_ni != new_dir_ni)
ni_lock_dir2(new_dir_ni);
is_bad = false;
err = ni_rename(dir_ni, new_dir_ni, ni, de, new_de, &is_bad);
if (is_bad) {
/* Restore after failed rename failed too. */
_ntfs_bad_inode(inode);
} else if (!err) {
simple_rename_timestamp(dir, dentry, new_dir, new_dentry);
mark_inode_dirty(inode);
mark_inode_dirty(dir);
if (dir != new_dir)
mark_inode_dirty(new_dir);
if (IS_DIRSYNC(dir))
ntfs_sync_inode(dir);
if (IS_DIRSYNC(new_dir))
ntfs_sync_inode(inode);
}
if (dir_ni != new_dir_ni)
ni_unlock(new_dir_ni);
ni_unlock(ni);
ni_unlock(dir_ni);
out:
__putname(de);
return err;
}
/*
* ntfs_atomic_open
*
* inode_operations::atomic_open
*/
static int ntfs_atomic_open(struct inode *dir, struct dentry *dentry,
struct file *file, u32 flags, umode_t mode)
{
int err;
struct inode *inode;
struct ntfs_fnd *fnd = NULL;
struct ntfs_inode *ni = ntfs_i(dir);
struct dentry *d = NULL;
struct cpu_str *uni = __getname();
bool locked = false;
if (!uni)
return -ENOMEM;
err = ntfs_nls_to_utf16(ni->mi.sbi, dentry->d_name.name,
dentry->d_name.len, uni, NTFS_NAME_LEN,
UTF16_HOST_ENDIAN);
if (err < 0)
goto out;
#ifdef CONFIG_NTFS3_FS_POSIX_ACL
if (IS_POSIXACL(dir)) {
/*
* Load in cache current acl to avoid ni_lock(dir):
* ntfs_create_inode -> ntfs_init_acl -> posix_acl_create ->
* ntfs_get_acl -> ntfs_get_acl_ex -> ni_lock
*/
struct posix_acl *p = get_inode_acl(dir, ACL_TYPE_DEFAULT);
if (IS_ERR(p)) {
err = PTR_ERR(p);
goto out;
}
posix_acl_release(p);
}
#endif
if (d_in_lookup(dentry)) {
ni_lock_dir(ni);
locked = true;
fnd = fnd_get();
if (!fnd) {
err = -ENOMEM;
goto out1;
}
d = d_splice_alias(dir_search_u(dir, uni, fnd), dentry);
if (IS_ERR(d)) {
err = PTR_ERR(d);
d = NULL;
goto out2;
}
if (d)
dentry = d;
}
if (!(flags & O_CREAT) || d_really_is_positive(dentry)) {
err = finish_no_open(file, d);
goto out2;
}
file->f_mode |= FMODE_CREATED;
/*
* fnd contains tree's path to insert to.
* If fnd is not NULL then dir is locked.
*/
inode = ntfs_create_inode(mnt_idmap(file->f_path.mnt), dir, dentry, uni,
mode, 0, NULL, 0, fnd);
err = IS_ERR(inode) ? PTR_ERR(inode) :
finish_open(file, dentry, ntfs_file_open);
dput(d);
out2:
fnd_put(fnd);
out1:
if (locked)
ni_unlock(ni);
out:
__putname(uni);
return err;
}
struct dentry *ntfs3_get_parent(struct dentry *child)
{
struct inode *inode = d_inode(child);
struct ntfs_inode *ni = ntfs_i(inode);
struct ATTR_LIST_ENTRY *le = NULL;
struct ATTRIB *attr = NULL;
struct ATTR_FILE_NAME *fname;
while ((attr = ni_find_attr(ni, attr, &le, ATTR_NAME, NULL, 0, NULL,
NULL))) {
fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
if (!fname)
continue;
return d_obtain_alias(
ntfs_iget5(inode->i_sb, &fname->home, NULL));
}
return ERR_PTR(-ENOENT);
}
/*
* dentry_operations::d_hash
*/
static int ntfs_d_hash(const struct dentry *dentry, struct qstr *name)
{
struct ntfs_sb_info *sbi;
const char *n = name->name;
unsigned int len = name->len;
unsigned long hash;
struct cpu_str *uni;
unsigned int c;
int err;
/* First try fast implementation. */
hash = init_name_hash(dentry);
for (;;) {
if (!len--) {
name->hash = end_name_hash(hash);
return 0;
}
c = *n++;
if (c >= 0x80)
break;
hash = partial_name_hash(toupper(c), hash);
}
/*
* Try slow way with current upcase table
*/
uni = __getname();
if (!uni)
return -ENOMEM;
sbi = dentry->d_sb->s_fs_info;
err = ntfs_nls_to_utf16(sbi, name->name, name->len, uni, NTFS_NAME_LEN,
UTF16_HOST_ENDIAN);
if (err < 0)
goto out;
if (!err) {
err = -EINVAL;
goto out;
}
hash = ntfs_names_hash(uni->name, uni->len, sbi->upcase,
init_name_hash(dentry));
name->hash = end_name_hash(hash);
err = 0;
out:
__putname(uni);
return err;
}
/*
* dentry_operations::d_compare
*/
static int ntfs_d_compare(const struct dentry *dentry, unsigned int len1,
const char *str, const struct qstr *name)
{
struct ntfs_sb_info *sbi;
int ret;
const char *n1 = str;
const char *n2 = name->name;
unsigned int len2 = name->len;
unsigned int lm = min(len1, len2);
unsigned char c1, c2;
struct cpu_str *uni1;
struct le_str *uni2;
/* First try fast implementation. */
for (;;) {
if (!lm--)
return len1 != len2;
if ((c1 = *n1++) == (c2 = *n2++))
continue;
if (c1 >= 0x80 || c2 >= 0x80)
break;
if (toupper(c1) != toupper(c2))
return 1;
}
/*
* Try slow way with current upcase table
*/
sbi = dentry->d_sb->s_fs_info;
uni1 = __getname();
if (!uni1)
return -ENOMEM;
ret = ntfs_nls_to_utf16(sbi, str, len1, uni1, NTFS_NAME_LEN,
UTF16_HOST_ENDIAN);
if (ret < 0)
goto out;
if (!ret) {
ret = -EINVAL;
goto out;
}
uni2 = Add2Ptr(uni1, 2048);
ret = ntfs_nls_to_utf16(sbi, name->name, name->len,
(struct cpu_str *)uni2, NTFS_NAME_LEN,
UTF16_LITTLE_ENDIAN);
if (ret < 0)
goto out;
if (!ret) {
ret = -EINVAL;
goto out;
}
ret = !ntfs_cmp_names_cpu(uni1, uni2, sbi->upcase, false) ? 0 : 1;
out:
__putname(uni1);
return ret;
}
// clang-format off
const struct inode_operations ntfs_dir_inode_operations = {
.lookup = ntfs_lookup,
.create = ntfs_create,
.link = ntfs_link,
.unlink = ntfs_unlink,
.symlink = ntfs_symlink,
.mkdir = ntfs_mkdir,
.rmdir = ntfs_rmdir,
.mknod = ntfs_mknod,
.rename = ntfs_rename,
.get_acl = ntfs_get_acl,
.set_acl = ntfs_set_acl,
.setattr = ntfs3_setattr,
.getattr = ntfs_getattr,
.listxattr = ntfs_listxattr,
.atomic_open = ntfs_atomic_open,
.fiemap = ntfs_fiemap,
};
const struct inode_operations ntfs_special_inode_operations = {
.setattr = ntfs3_setattr,
.getattr = ntfs_getattr,
.listxattr = ntfs_listxattr,
.get_acl = ntfs_get_acl,
.set_acl = ntfs_set_acl,
};
const struct dentry_operations ntfs_dentry_ops = {
.d_hash = ntfs_d_hash,
.d_compare = ntfs_d_compare,
};
// clang-format on
| linux-master | fs/ntfs3/namei.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/fiemap.h>
#include <linux/fs.h>
#include <linux/minmax.h>
#include <linux/vmalloc.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
#ifdef CONFIG_NTFS3_LZX_XPRESS
#include "lib/lib.h"
#endif
static struct mft_inode *ni_ins_mi(struct ntfs_inode *ni, struct rb_root *tree,
CLST ino, struct rb_node *ins)
{
struct rb_node **p = &tree->rb_node;
struct rb_node *pr = NULL;
while (*p) {
struct mft_inode *mi;
pr = *p;
mi = rb_entry(pr, struct mft_inode, node);
if (mi->rno > ino)
p = &pr->rb_left;
else if (mi->rno < ino)
p = &pr->rb_right;
else
return mi;
}
if (!ins)
return NULL;
rb_link_node(ins, pr, p);
rb_insert_color(ins, tree);
return rb_entry(ins, struct mft_inode, node);
}
/*
* ni_find_mi - Find mft_inode by record number.
*/
static struct mft_inode *ni_find_mi(struct ntfs_inode *ni, CLST rno)
{
return ni_ins_mi(ni, &ni->mi_tree, rno, NULL);
}
/*
* ni_add_mi - Add new mft_inode into ntfs_inode.
*/
static void ni_add_mi(struct ntfs_inode *ni, struct mft_inode *mi)
{
ni_ins_mi(ni, &ni->mi_tree, mi->rno, &mi->node);
}
/*
* ni_remove_mi - Remove mft_inode from ntfs_inode.
*/
void ni_remove_mi(struct ntfs_inode *ni, struct mft_inode *mi)
{
rb_erase(&mi->node, &ni->mi_tree);
}
/*
* ni_std - Return: Pointer into std_info from primary record.
*/
struct ATTR_STD_INFO *ni_std(struct ntfs_inode *ni)
{
const struct ATTRIB *attr;
attr = mi_find_attr(&ni->mi, NULL, ATTR_STD, NULL, 0, NULL);
return attr ? resident_data_ex(attr, sizeof(struct ATTR_STD_INFO)) :
NULL;
}
/*
* ni_std5
*
* Return: Pointer into std_info from primary record.
*/
struct ATTR_STD_INFO5 *ni_std5(struct ntfs_inode *ni)
{
const struct ATTRIB *attr;
attr = mi_find_attr(&ni->mi, NULL, ATTR_STD, NULL, 0, NULL);
return attr ? resident_data_ex(attr, sizeof(struct ATTR_STD_INFO5)) :
NULL;
}
/*
* ni_clear - Clear resources allocated by ntfs_inode.
*/
void ni_clear(struct ntfs_inode *ni)
{
struct rb_node *node;
if (!ni->vfs_inode.i_nlink && ni->mi.mrec && is_rec_inuse(ni->mi.mrec))
ni_delete_all(ni);
al_destroy(ni);
for (node = rb_first(&ni->mi_tree); node;) {
struct rb_node *next = rb_next(node);
struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
rb_erase(node, &ni->mi_tree);
mi_put(mi);
node = next;
}
/* Bad inode always has mode == S_IFREG. */
if (ni->ni_flags & NI_FLAG_DIR)
indx_clear(&ni->dir);
else {
run_close(&ni->file.run);
#ifdef CONFIG_NTFS3_LZX_XPRESS
if (ni->file.offs_page) {
/* On-demand allocated page for offsets. */
put_page(ni->file.offs_page);
ni->file.offs_page = NULL;
}
#endif
}
mi_clear(&ni->mi);
}
/*
* ni_load_mi_ex - Find mft_inode by record number.
*/
int ni_load_mi_ex(struct ntfs_inode *ni, CLST rno, struct mft_inode **mi)
{
int err;
struct mft_inode *r;
r = ni_find_mi(ni, rno);
if (r)
goto out;
err = mi_get(ni->mi.sbi, rno, &r);
if (err)
return err;
ni_add_mi(ni, r);
out:
if (mi)
*mi = r;
return 0;
}
/*
* ni_load_mi - Load mft_inode corresponded list_entry.
*/
int ni_load_mi(struct ntfs_inode *ni, const struct ATTR_LIST_ENTRY *le,
struct mft_inode **mi)
{
CLST rno;
if (!le) {
*mi = &ni->mi;
return 0;
}
rno = ino_get(&le->ref);
if (rno == ni->mi.rno) {
*mi = &ni->mi;
return 0;
}
return ni_load_mi_ex(ni, rno, mi);
}
/*
* ni_find_attr
*
* Return: Attribute and record this attribute belongs to.
*/
struct ATTRIB *ni_find_attr(struct ntfs_inode *ni, struct ATTRIB *attr,
struct ATTR_LIST_ENTRY **le_o, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, const CLST *vcn,
struct mft_inode **mi)
{
struct ATTR_LIST_ENTRY *le;
struct mft_inode *m;
if (!ni->attr_list.size ||
(!name_len && (type == ATTR_LIST || type == ATTR_STD))) {
if (le_o)
*le_o = NULL;
if (mi)
*mi = &ni->mi;
/* Look for required attribute in primary record. */
return mi_find_attr(&ni->mi, attr, type, name, name_len, NULL);
}
/* First look for list entry of required type. */
le = al_find_ex(ni, le_o ? *le_o : NULL, type, name, name_len, vcn);
if (!le)
return NULL;
if (le_o)
*le_o = le;
/* Load record that contains this attribute. */
if (ni_load_mi(ni, le, &m))
return NULL;
/* Look for required attribute. */
attr = mi_find_attr(m, NULL, type, name, name_len, &le->id);
if (!attr)
goto out;
if (!attr->non_res) {
if (vcn && *vcn)
goto out;
} else if (!vcn) {
if (attr->nres.svcn)
goto out;
} else if (le64_to_cpu(attr->nres.svcn) > *vcn ||
*vcn > le64_to_cpu(attr->nres.evcn)) {
goto out;
}
if (mi)
*mi = m;
return attr;
out:
ntfs_inode_err(&ni->vfs_inode, "failed to parse mft record");
ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_ERROR);
return NULL;
}
/*
* ni_enum_attr_ex - Enumerates attributes in ntfs_inode.
*/
struct ATTRIB *ni_enum_attr_ex(struct ntfs_inode *ni, struct ATTRIB *attr,
struct ATTR_LIST_ENTRY **le,
struct mft_inode **mi)
{
struct mft_inode *mi2;
struct ATTR_LIST_ENTRY *le2;
/* Do we have an attribute list? */
if (!ni->attr_list.size) {
*le = NULL;
if (mi)
*mi = &ni->mi;
/* Enum attributes in primary record. */
return mi_enum_attr(&ni->mi, attr);
}
/* Get next list entry. */
le2 = *le = al_enumerate(ni, attr ? *le : NULL);
if (!le2)
return NULL;
/* Load record that contains the required attribute. */
if (ni_load_mi(ni, le2, &mi2))
return NULL;
if (mi)
*mi = mi2;
/* Find attribute in loaded record. */
return rec_find_attr_le(mi2, le2);
}
/*
* ni_load_attr - Load attribute that contains given VCN.
*/
struct ATTRIB *ni_load_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, CLST vcn,
struct mft_inode **pmi)
{
struct ATTR_LIST_ENTRY *le;
struct ATTRIB *attr;
struct mft_inode *mi;
struct ATTR_LIST_ENTRY *next;
if (!ni->attr_list.size) {
if (pmi)
*pmi = &ni->mi;
return mi_find_attr(&ni->mi, NULL, type, name, name_len, NULL);
}
le = al_find_ex(ni, NULL, type, name, name_len, NULL);
if (!le)
return NULL;
/*
* Unfortunately ATTR_LIST_ENTRY contains only start VCN.
* So to find the ATTRIB segment that contains 'vcn' we should
* enumerate some entries.
*/
if (vcn) {
for (;; le = next) {
next = al_find_ex(ni, le, type, name, name_len, NULL);
if (!next || le64_to_cpu(next->vcn) > vcn)
break;
}
}
if (ni_load_mi(ni, le, &mi))
return NULL;
if (pmi)
*pmi = mi;
attr = mi_find_attr(mi, NULL, type, name, name_len, &le->id);
if (!attr)
return NULL;
if (!attr->non_res)
return attr;
if (le64_to_cpu(attr->nres.svcn) <= vcn &&
vcn <= le64_to_cpu(attr->nres.evcn))
return attr;
return NULL;
}
/*
* ni_load_all_mi - Load all subrecords.
*/
int ni_load_all_mi(struct ntfs_inode *ni)
{
int err;
struct ATTR_LIST_ENTRY *le;
if (!ni->attr_list.size)
return 0;
le = NULL;
while ((le = al_enumerate(ni, le))) {
CLST rno = ino_get(&le->ref);
if (rno == ni->mi.rno)
continue;
err = ni_load_mi_ex(ni, rno, NULL);
if (err)
return err;
}
return 0;
}
/*
* ni_add_subrecord - Allocate + format + attach a new subrecord.
*/
bool ni_add_subrecord(struct ntfs_inode *ni, CLST rno, struct mft_inode **mi)
{
struct mft_inode *m;
m = kzalloc(sizeof(struct mft_inode), GFP_NOFS);
if (!m)
return false;
if (mi_format_new(m, ni->mi.sbi, rno, 0, ni->mi.rno == MFT_REC_MFT)) {
mi_put(m);
return false;
}
mi_get_ref(&ni->mi, &m->mrec->parent_ref);
ni_add_mi(ni, m);
*mi = m;
return true;
}
/*
* ni_remove_attr - Remove all attributes for the given type/name/id.
*/
int ni_remove_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, bool base_only,
const __le16 *id)
{
int err;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
struct mft_inode *mi;
u32 type_in;
int diff;
if (base_only || type == ATTR_LIST || !ni->attr_list.size) {
attr = mi_find_attr(&ni->mi, NULL, type, name, name_len, id);
if (!attr)
return -ENOENT;
mi_remove_attr(ni, &ni->mi, attr);
return 0;
}
type_in = le32_to_cpu(type);
le = NULL;
for (;;) {
le = al_enumerate(ni, le);
if (!le)
return 0;
next_le2:
diff = le32_to_cpu(le->type) - type_in;
if (diff < 0)
continue;
if (diff > 0)
return 0;
if (le->name_len != name_len)
continue;
if (name_len &&
memcmp(le_name(le), name, name_len * sizeof(short)))
continue;
if (id && le->id != *id)
continue;
err = ni_load_mi(ni, le, &mi);
if (err)
return err;
al_remove_le(ni, le);
attr = mi_find_attr(mi, NULL, type, name, name_len, id);
if (!attr)
return -ENOENT;
mi_remove_attr(ni, mi, attr);
if (PtrOffset(ni->attr_list.le, le) >= ni->attr_list.size)
return 0;
goto next_le2;
}
}
/*
* ni_ins_new_attr - Insert the attribute into record.
*
* Return: Not full constructed attribute or NULL if not possible to create.
*/
static struct ATTRIB *
ni_ins_new_attr(struct ntfs_inode *ni, struct mft_inode *mi,
struct ATTR_LIST_ENTRY *le, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, u32 asize, u16 name_off,
CLST svcn, struct ATTR_LIST_ENTRY **ins_le)
{
int err;
struct ATTRIB *attr;
bool le_added = false;
struct MFT_REF ref;
mi_get_ref(mi, &ref);
if (type != ATTR_LIST && !le && ni->attr_list.size) {
err = al_add_le(ni, type, name, name_len, svcn, cpu_to_le16(-1),
&ref, &le);
if (err) {
/* No memory or no space. */
return ERR_PTR(err);
}
le_added = true;
/*
* al_add_le -> attr_set_size (list) -> ni_expand_list
* which moves some attributes out of primary record
* this means that name may point into moved memory
* reinit 'name' from le.
*/
name = le->name;
}
attr = mi_insert_attr(mi, type, name, name_len, asize, name_off);
if (!attr) {
if (le_added)
al_remove_le(ni, le);
return NULL;
}
if (type == ATTR_LIST) {
/* Attr list is not in list entry array. */
goto out;
}
if (!le)
goto out;
/* Update ATTRIB Id and record reference. */
le->id = attr->id;
ni->attr_list.dirty = true;
le->ref = ref;
out:
if (ins_le)
*ins_le = le;
return attr;
}
/*
* ni_repack
*
* Random write access to sparsed or compressed file may result to
* not optimized packed runs.
* Here is the place to optimize it.
*/
static int ni_repack(struct ntfs_inode *ni)
{
#if 1
return 0;
#else
int err = 0;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct mft_inode *mi, *mi_p = NULL;
struct ATTRIB *attr = NULL, *attr_p;
struct ATTR_LIST_ENTRY *le = NULL, *le_p;
CLST alloc = 0;
u8 cluster_bits = sbi->cluster_bits;
CLST svcn, evcn = 0, svcn_p, evcn_p, next_svcn;
u32 roff, rs = sbi->record_size;
struct runs_tree run;
run_init(&run);
while ((attr = ni_enum_attr_ex(ni, attr, &le, &mi))) {
if (!attr->non_res)
continue;
svcn = le64_to_cpu(attr->nres.svcn);
if (svcn != le64_to_cpu(le->vcn)) {
err = -EINVAL;
break;
}
if (!svcn) {
alloc = le64_to_cpu(attr->nres.alloc_size) >>
cluster_bits;
mi_p = NULL;
} else if (svcn != evcn + 1) {
err = -EINVAL;
break;
}
evcn = le64_to_cpu(attr->nres.evcn);
if (svcn > evcn + 1) {
err = -EINVAL;
break;
}
if (!mi_p) {
/* Do not try if not enough free space. */
if (le32_to_cpu(mi->mrec->used) + 8 >= rs)
continue;
/* Do not try if last attribute segment. */
if (evcn + 1 == alloc)
continue;
run_close(&run);
}
roff = le16_to_cpu(attr->nres.run_off);
if (roff > le32_to_cpu(attr->size)) {
err = -EINVAL;
break;
}
err = run_unpack(&run, sbi, ni->mi.rno, svcn, evcn, svcn,
Add2Ptr(attr, roff),
le32_to_cpu(attr->size) - roff);
if (err < 0)
break;
if (!mi_p) {
mi_p = mi;
attr_p = attr;
svcn_p = svcn;
evcn_p = evcn;
le_p = le;
err = 0;
continue;
}
/*
* Run contains data from two records: mi_p and mi
* Try to pack in one.
*/
err = mi_pack_runs(mi_p, attr_p, &run, evcn + 1 - svcn_p);
if (err)
break;
next_svcn = le64_to_cpu(attr_p->nres.evcn) + 1;
if (next_svcn >= evcn + 1) {
/* We can remove this attribute segment. */
al_remove_le(ni, le);
mi_remove_attr(NULL, mi, attr);
le = le_p;
continue;
}
attr->nres.svcn = le->vcn = cpu_to_le64(next_svcn);
mi->dirty = true;
ni->attr_list.dirty = true;
if (evcn + 1 == alloc) {
err = mi_pack_runs(mi, attr, &run,
evcn + 1 - next_svcn);
if (err)
break;
mi_p = NULL;
} else {
mi_p = mi;
attr_p = attr;
svcn_p = next_svcn;
evcn_p = evcn;
le_p = le;
run_truncate_head(&run, next_svcn);
}
}
if (err) {
ntfs_inode_warn(&ni->vfs_inode, "repack problem");
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
/* Pack loaded but not packed runs. */
if (mi_p)
mi_pack_runs(mi_p, attr_p, &run, evcn_p + 1 - svcn_p);
}
run_close(&run);
return err;
#endif
}
/*
* ni_try_remove_attr_list
*
* Can we remove attribute list?
* Check the case when primary record contains enough space for all attributes.
*/
static int ni_try_remove_attr_list(struct ntfs_inode *ni)
{
int err = 0;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr, *attr_list, *attr_ins;
struct ATTR_LIST_ENTRY *le;
struct mft_inode *mi;
u32 asize, free;
struct MFT_REF ref;
struct MFT_REC *mrec;
__le16 id;
if (!ni->attr_list.dirty)
return 0;
err = ni_repack(ni);
if (err)
return err;
attr_list = mi_find_attr(&ni->mi, NULL, ATTR_LIST, NULL, 0, NULL);
if (!attr_list)
return 0;
asize = le32_to_cpu(attr_list->size);
/* Free space in primary record without attribute list. */
free = sbi->record_size - le32_to_cpu(ni->mi.mrec->used) + asize;
mi_get_ref(&ni->mi, &ref);
le = NULL;
while ((le = al_enumerate(ni, le))) {
if (!memcmp(&le->ref, &ref, sizeof(ref)))
continue;
if (le->vcn)
return 0;
mi = ni_find_mi(ni, ino_get(&le->ref));
if (!mi)
return 0;
attr = mi_find_attr(mi, NULL, le->type, le_name(le),
le->name_len, &le->id);
if (!attr)
return 0;
asize = le32_to_cpu(attr->size);
if (asize > free)
return 0;
free -= asize;
}
/* Make a copy of primary record to restore if error. */
mrec = kmemdup(ni->mi.mrec, sbi->record_size, GFP_NOFS);
if (!mrec)
return 0; /* Not critical. */
/* It seems that attribute list can be removed from primary record. */
mi_remove_attr(NULL, &ni->mi, attr_list);
/*
* Repeat the cycle above and copy all attributes to primary record.
* Do not remove original attributes from subrecords!
* It should be success!
*/
le = NULL;
while ((le = al_enumerate(ni, le))) {
if (!memcmp(&le->ref, &ref, sizeof(ref)))
continue;
mi = ni_find_mi(ni, ino_get(&le->ref));
if (!mi) {
/* Should never happened, 'cause already checked. */
goto out;
}
attr = mi_find_attr(mi, NULL, le->type, le_name(le),
le->name_len, &le->id);
if (!attr) {
/* Should never happened, 'cause already checked. */
goto out;
}
asize = le32_to_cpu(attr->size);
/* Insert into primary record. */
attr_ins = mi_insert_attr(&ni->mi, le->type, le_name(le),
le->name_len, asize,
le16_to_cpu(attr->name_off));
if (!attr_ins) {
/*
* No space in primary record (already checked).
*/
goto out;
}
/* Copy all except id. */
id = attr_ins->id;
memcpy(attr_ins, attr, asize);
attr_ins->id = id;
}
/*
* Repeat the cycle above and remove all attributes from subrecords.
*/
le = NULL;
while ((le = al_enumerate(ni, le))) {
if (!memcmp(&le->ref, &ref, sizeof(ref)))
continue;
mi = ni_find_mi(ni, ino_get(&le->ref));
if (!mi)
continue;
attr = mi_find_attr(mi, NULL, le->type, le_name(le),
le->name_len, &le->id);
if (!attr)
continue;
/* Remove from original record. */
mi_remove_attr(NULL, mi, attr);
}
run_deallocate(sbi, &ni->attr_list.run, true);
run_close(&ni->attr_list.run);
ni->attr_list.size = 0;
kfree(ni->attr_list.le);
ni->attr_list.le = NULL;
ni->attr_list.dirty = false;
kfree(mrec);
return 0;
out:
/* Restore primary record. */
swap(mrec, ni->mi.mrec);
kfree(mrec);
return 0;
}
/*
* ni_create_attr_list - Generates an attribute list for this primary record.
*/
int ni_create_attr_list(struct ntfs_inode *ni)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
int err;
u32 lsize;
struct ATTRIB *attr;
struct ATTRIB *arr_move[7];
struct ATTR_LIST_ENTRY *le, *le_b[7];
struct MFT_REC *rec;
bool is_mft;
CLST rno = 0;
struct mft_inode *mi;
u32 free_b, nb, to_free, rs;
u16 sz;
is_mft = ni->mi.rno == MFT_REC_MFT;
rec = ni->mi.mrec;
rs = sbi->record_size;
/*
* Skip estimating exact memory requirement.
* Looks like one record_size is always enough.
*/
le = kmalloc(al_aligned(rs), GFP_NOFS);
if (!le)
return -ENOMEM;
mi_get_ref(&ni->mi, &le->ref);
ni->attr_list.le = le;
attr = NULL;
nb = 0;
free_b = 0;
attr = NULL;
for (; (attr = mi_enum_attr(&ni->mi, attr)); le = Add2Ptr(le, sz)) {
sz = le_size(attr->name_len);
le->type = attr->type;
le->size = cpu_to_le16(sz);
le->name_len = attr->name_len;
le->name_off = offsetof(struct ATTR_LIST_ENTRY, name);
le->vcn = 0;
if (le != ni->attr_list.le)
le->ref = ni->attr_list.le->ref;
le->id = attr->id;
if (attr->name_len)
memcpy(le->name, attr_name(attr),
sizeof(short) * attr->name_len);
else if (attr->type == ATTR_STD)
continue;
else if (attr->type == ATTR_LIST)
continue;
else if (is_mft && attr->type == ATTR_DATA)
continue;
if (!nb || nb < ARRAY_SIZE(arr_move)) {
le_b[nb] = le;
arr_move[nb++] = attr;
free_b += le32_to_cpu(attr->size);
}
}
lsize = PtrOffset(ni->attr_list.le, le);
ni->attr_list.size = lsize;
to_free = le32_to_cpu(rec->used) + lsize + SIZEOF_RESIDENT;
if (to_free <= rs) {
to_free = 0;
} else {
to_free -= rs;
if (to_free > free_b) {
err = -EINVAL;
goto out;
}
}
/* Allocate child MFT. */
err = ntfs_look_free_mft(sbi, &rno, is_mft, ni, &mi);
if (err)
goto out;
err = -EINVAL;
/* Call mi_remove_attr() in reverse order to keep pointers 'arr_move' valid. */
while (to_free > 0) {
struct ATTRIB *b = arr_move[--nb];
u32 asize = le32_to_cpu(b->size);
u16 name_off = le16_to_cpu(b->name_off);
attr = mi_insert_attr(mi, b->type, Add2Ptr(b, name_off),
b->name_len, asize, name_off);
if (!attr)
goto out;
mi_get_ref(mi, &le_b[nb]->ref);
le_b[nb]->id = attr->id;
/* Copy all except id. */
memcpy(attr, b, asize);
attr->id = le_b[nb]->id;
/* Remove from primary record. */
if (!mi_remove_attr(NULL, &ni->mi, b))
goto out;
if (to_free <= asize)
break;
to_free -= asize;
if (!nb)
goto out;
}
attr = mi_insert_attr(&ni->mi, ATTR_LIST, NULL, 0,
lsize + SIZEOF_RESIDENT, SIZEOF_RESIDENT);
if (!attr)
goto out;
attr->non_res = 0;
attr->flags = 0;
attr->res.data_size = cpu_to_le32(lsize);
attr->res.data_off = SIZEOF_RESIDENT_LE;
attr->res.flags = 0;
attr->res.res = 0;
memcpy(resident_data_ex(attr, lsize), ni->attr_list.le, lsize);
ni->attr_list.dirty = false;
mark_inode_dirty(&ni->vfs_inode);
return 0;
out:
kfree(ni->attr_list.le);
ni->attr_list.le = NULL;
ni->attr_list.size = 0;
return err;
}
/*
* ni_ins_attr_ext - Add an external attribute to the ntfs_inode.
*/
static int ni_ins_attr_ext(struct ntfs_inode *ni, struct ATTR_LIST_ENTRY *le,
enum ATTR_TYPE type, const __le16 *name, u8 name_len,
u32 asize, CLST svcn, u16 name_off, bool force_ext,
struct ATTRIB **ins_attr, struct mft_inode **ins_mi,
struct ATTR_LIST_ENTRY **ins_le)
{
struct ATTRIB *attr;
struct mft_inode *mi;
CLST rno;
u64 vbo;
struct rb_node *node;
int err;
bool is_mft, is_mft_data;
struct ntfs_sb_info *sbi = ni->mi.sbi;
is_mft = ni->mi.rno == MFT_REC_MFT;
is_mft_data = is_mft && type == ATTR_DATA && !name_len;
if (asize > sbi->max_bytes_per_attr) {
err = -EINVAL;
goto out;
}
/*
* Standard information and attr_list cannot be made external.
* The Log File cannot have any external attributes.
*/
if (type == ATTR_STD || type == ATTR_LIST ||
ni->mi.rno == MFT_REC_LOG) {
err = -EINVAL;
goto out;
}
/* Create attribute list if it is not already existed. */
if (!ni->attr_list.size) {
err = ni_create_attr_list(ni);
if (err)
goto out;
}
vbo = is_mft_data ? ((u64)svcn << sbi->cluster_bits) : 0;
if (force_ext)
goto insert_ext;
/* Load all subrecords into memory. */
err = ni_load_all_mi(ni);
if (err)
goto out;
/* Check each of loaded subrecord. */
for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
mi = rb_entry(node, struct mft_inode, node);
if (is_mft_data &&
(mi_enum_attr(mi, NULL) ||
vbo <= ((u64)mi->rno << sbi->record_bits))) {
/* We can't accept this record 'cause MFT's bootstrapping. */
continue;
}
if (is_mft &&
mi_find_attr(mi, NULL, ATTR_DATA, NULL, 0, NULL)) {
/*
* This child record already has a ATTR_DATA.
* So it can't accept any other records.
*/
continue;
}
if ((type != ATTR_NAME || name_len) &&
mi_find_attr(mi, NULL, type, name, name_len, NULL)) {
/* Only indexed attributes can share same record. */
continue;
}
/*
* Do not try to insert this attribute
* if there is no room in record.
*/
if (le32_to_cpu(mi->mrec->used) + asize > sbi->record_size)
continue;
/* Try to insert attribute into this subrecord. */
attr = ni_ins_new_attr(ni, mi, le, type, name, name_len, asize,
name_off, svcn, ins_le);
if (!attr)
continue;
if (IS_ERR(attr))
return PTR_ERR(attr);
if (ins_attr)
*ins_attr = attr;
if (ins_mi)
*ins_mi = mi;
return 0;
}
insert_ext:
/* We have to allocate a new child subrecord. */
err = ntfs_look_free_mft(sbi, &rno, is_mft_data, ni, &mi);
if (err)
goto out;
if (is_mft_data && vbo <= ((u64)rno << sbi->record_bits)) {
err = -EINVAL;
goto out1;
}
attr = ni_ins_new_attr(ni, mi, le, type, name, name_len, asize,
name_off, svcn, ins_le);
if (!attr) {
err = -EINVAL;
goto out2;
}
if (IS_ERR(attr)) {
err = PTR_ERR(attr);
goto out2;
}
if (ins_attr)
*ins_attr = attr;
if (ins_mi)
*ins_mi = mi;
return 0;
out2:
ni_remove_mi(ni, mi);
mi_put(mi);
out1:
ntfs_mark_rec_free(sbi, rno, is_mft);
out:
return err;
}
/*
* ni_insert_attr - Insert an attribute into the file.
*
* If the primary record has room, it will just insert the attribute.
* If not, it may make the attribute external.
* For $MFT::Data it may make room for the attribute by
* making other attributes external.
*
* NOTE:
* The ATTR_LIST and ATTR_STD cannot be made external.
* This function does not fill new attribute full.
* It only fills 'size'/'type'/'id'/'name_len' fields.
*/
static int ni_insert_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, u32 asize,
u16 name_off, CLST svcn, struct ATTRIB **ins_attr,
struct mft_inode **ins_mi,
struct ATTR_LIST_ENTRY **ins_le)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
int err;
struct ATTRIB *attr, *eattr;
struct MFT_REC *rec;
bool is_mft;
struct ATTR_LIST_ENTRY *le;
u32 list_reserve, max_free, free, used, t32;
__le16 id;
u16 t16;
is_mft = ni->mi.rno == MFT_REC_MFT;
rec = ni->mi.mrec;
list_reserve = SIZEOF_NONRESIDENT + 3 * (1 + 2 * sizeof(u32));
used = le32_to_cpu(rec->used);
free = sbi->record_size - used;
if (is_mft && type != ATTR_LIST) {
/* Reserve space for the ATTRIB list. */
if (free < list_reserve)
free = 0;
else
free -= list_reserve;
}
if (asize <= free) {
attr = ni_ins_new_attr(ni, &ni->mi, NULL, type, name, name_len,
asize, name_off, svcn, ins_le);
if (IS_ERR(attr)) {
err = PTR_ERR(attr);
goto out;
}
if (attr) {
if (ins_attr)
*ins_attr = attr;
if (ins_mi)
*ins_mi = &ni->mi;
err = 0;
goto out;
}
}
if (!is_mft || type != ATTR_DATA || svcn) {
/* This ATTRIB will be external. */
err = ni_ins_attr_ext(ni, NULL, type, name, name_len, asize,
svcn, name_off, false, ins_attr, ins_mi,
ins_le);
goto out;
}
/*
* Here we have: "is_mft && type == ATTR_DATA && !svcn"
*
* The first chunk of the $MFT::Data ATTRIB must be the base record.
* Evict as many other attributes as possible.
*/
max_free = free;
/* Estimate the result of moving all possible attributes away. */
attr = NULL;
while ((attr = mi_enum_attr(&ni->mi, attr))) {
if (attr->type == ATTR_STD)
continue;
if (attr->type == ATTR_LIST)
continue;
max_free += le32_to_cpu(attr->size);
}
if (max_free < asize + list_reserve) {
/* Impossible to insert this attribute into primary record. */
err = -EINVAL;
goto out;
}
/* Start real attribute moving. */
attr = NULL;
for (;;) {
attr = mi_enum_attr(&ni->mi, attr);
if (!attr) {
/* We should never be here 'cause we have already check this case. */
err = -EINVAL;
goto out;
}
/* Skip attributes that MUST be primary record. */
if (attr->type == ATTR_STD || attr->type == ATTR_LIST)
continue;
le = NULL;
if (ni->attr_list.size) {
le = al_find_le(ni, NULL, attr);
if (!le) {
/* Really this is a serious bug. */
err = -EINVAL;
goto out;
}
}
t32 = le32_to_cpu(attr->size);
t16 = le16_to_cpu(attr->name_off);
err = ni_ins_attr_ext(ni, le, attr->type, Add2Ptr(attr, t16),
attr->name_len, t32, attr_svcn(attr), t16,
false, &eattr, NULL, NULL);
if (err)
return err;
id = eattr->id;
memcpy(eattr, attr, t32);
eattr->id = id;
/* Remove from primary record. */
mi_remove_attr(NULL, &ni->mi, attr);
/* attr now points to next attribute. */
if (attr->type == ATTR_END)
goto out;
}
while (asize + list_reserve > sbi->record_size - le32_to_cpu(rec->used))
;
attr = ni_ins_new_attr(ni, &ni->mi, NULL, type, name, name_len, asize,
name_off, svcn, ins_le);
if (!attr) {
err = -EINVAL;
goto out;
}
if (IS_ERR(attr)) {
err = PTR_ERR(attr);
goto out;
}
if (ins_attr)
*ins_attr = attr;
if (ins_mi)
*ins_mi = &ni->mi;
out:
return err;
}
/* ni_expand_mft_list - Split ATTR_DATA of $MFT. */
static int ni_expand_mft_list(struct ntfs_inode *ni)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
u32 asize, run_size, done = 0;
struct ATTRIB *attr;
struct rb_node *node;
CLST mft_min, mft_new, svcn, evcn, plen;
struct mft_inode *mi, *mi_min, *mi_new;
struct ntfs_sb_info *sbi = ni->mi.sbi;
/* Find the nearest MFT. */
mft_min = 0;
mft_new = 0;
mi_min = NULL;
for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
mi = rb_entry(node, struct mft_inode, node);
attr = mi_enum_attr(mi, NULL);
if (!attr) {
mft_min = mi->rno;
mi_min = mi;
break;
}
}
if (ntfs_look_free_mft(sbi, &mft_new, true, ni, &mi_new)) {
mft_new = 0;
/* Really this is not critical. */
} else if (mft_min > mft_new) {
mft_min = mft_new;
mi_min = mi_new;
} else {
ntfs_mark_rec_free(sbi, mft_new, true);
mft_new = 0;
ni_remove_mi(ni, mi_new);
}
attr = mi_find_attr(&ni->mi, NULL, ATTR_DATA, NULL, 0, NULL);
if (!attr) {
err = -EINVAL;
goto out;
}
asize = le32_to_cpu(attr->size);
evcn = le64_to_cpu(attr->nres.evcn);
svcn = bytes_to_cluster(sbi, (u64)(mft_min + 1) << sbi->record_bits);
if (evcn + 1 >= svcn) {
err = -EINVAL;
goto out;
}
/*
* Split primary attribute [0 evcn] in two parts [0 svcn) + [svcn evcn].
*
* Update first part of ATTR_DATA in 'primary MFT.
*/
err = run_pack(run, 0, svcn, Add2Ptr(attr, SIZEOF_NONRESIDENT),
asize - SIZEOF_NONRESIDENT, &plen);
if (err < 0)
goto out;
run_size = ALIGN(err, 8);
err = 0;
if (plen < svcn) {
err = -EINVAL;
goto out;
}
attr->nres.evcn = cpu_to_le64(svcn - 1);
attr->size = cpu_to_le32(run_size + SIZEOF_NONRESIDENT);
/* 'done' - How many bytes of primary MFT becomes free. */
done = asize - run_size - SIZEOF_NONRESIDENT;
le32_sub_cpu(&ni->mi.mrec->used, done);
/* Estimate packed size (run_buf=NULL). */
err = run_pack(run, svcn, evcn + 1 - svcn, NULL, sbi->record_size,
&plen);
if (err < 0)
goto out;
run_size = ALIGN(err, 8);
err = 0;
if (plen < evcn + 1 - svcn) {
err = -EINVAL;
goto out;
}
/*
* This function may implicitly call expand attr_list.
* Insert second part of ATTR_DATA in 'mi_min'.
*/
attr = ni_ins_new_attr(ni, mi_min, NULL, ATTR_DATA, NULL, 0,
SIZEOF_NONRESIDENT + run_size,
SIZEOF_NONRESIDENT, svcn, NULL);
if (!attr) {
err = -EINVAL;
goto out;
}
if (IS_ERR(attr)) {
err = PTR_ERR(attr);
goto out;
}
attr->non_res = 1;
attr->name_off = SIZEOF_NONRESIDENT_LE;
attr->flags = 0;
/* This function can't fail - cause already checked above. */
run_pack(run, svcn, evcn + 1 - svcn, Add2Ptr(attr, SIZEOF_NONRESIDENT),
run_size, &plen);
attr->nres.svcn = cpu_to_le64(svcn);
attr->nres.evcn = cpu_to_le64(evcn);
attr->nres.run_off = cpu_to_le16(SIZEOF_NONRESIDENT);
out:
if (mft_new) {
ntfs_mark_rec_free(sbi, mft_new, true);
ni_remove_mi(ni, mi_new);
}
return !err && !done ? -EOPNOTSUPP : err;
}
/*
* ni_expand_list - Move all possible attributes out of primary record.
*/
int ni_expand_list(struct ntfs_inode *ni)
{
int err = 0;
u32 asize, done = 0;
struct ATTRIB *attr, *ins_attr;
struct ATTR_LIST_ENTRY *le;
bool is_mft = ni->mi.rno == MFT_REC_MFT;
struct MFT_REF ref;
mi_get_ref(&ni->mi, &ref);
le = NULL;
while ((le = al_enumerate(ni, le))) {
if (le->type == ATTR_STD)
continue;
if (memcmp(&ref, &le->ref, sizeof(struct MFT_REF)))
continue;
if (is_mft && le->type == ATTR_DATA)
continue;
/* Find attribute in primary record. */
attr = rec_find_attr_le(&ni->mi, le);
if (!attr) {
err = -EINVAL;
goto out;
}
asize = le32_to_cpu(attr->size);
/* Always insert into new record to avoid collisions (deep recursive). */
err = ni_ins_attr_ext(ni, le, attr->type, attr_name(attr),
attr->name_len, asize, attr_svcn(attr),
le16_to_cpu(attr->name_off), true,
&ins_attr, NULL, NULL);
if (err)
goto out;
memcpy(ins_attr, attr, asize);
ins_attr->id = le->id;
/* Remove from primary record. */
mi_remove_attr(NULL, &ni->mi, attr);
done += asize;
goto out;
}
if (!is_mft) {
err = -EFBIG; /* Attr list is too big(?) */
goto out;
}
/* Split MFT data as much as possible. */
err = ni_expand_mft_list(ni);
out:
return !err && !done ? -EOPNOTSUPP : err;
}
/*
* ni_insert_nonresident - Insert new nonresident attribute.
*/
int ni_insert_nonresident(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len,
const struct runs_tree *run, CLST svcn, CLST len,
__le16 flags, struct ATTRIB **new_attr,
struct mft_inode **mi, struct ATTR_LIST_ENTRY **le)
{
int err;
CLST plen;
struct ATTRIB *attr;
bool is_ext = (flags & (ATTR_FLAG_SPARSED | ATTR_FLAG_COMPRESSED)) &&
!svcn;
u32 name_size = ALIGN(name_len * sizeof(short), 8);
u32 name_off = is_ext ? SIZEOF_NONRESIDENT_EX : SIZEOF_NONRESIDENT;
u32 run_off = name_off + name_size;
u32 run_size, asize;
struct ntfs_sb_info *sbi = ni->mi.sbi;
/* Estimate packed size (run_buf=NULL). */
err = run_pack(run, svcn, len, NULL, sbi->max_bytes_per_attr - run_off,
&plen);
if (err < 0)
goto out;
run_size = ALIGN(err, 8);
if (plen < len) {
err = -EINVAL;
goto out;
}
asize = run_off + run_size;
if (asize > sbi->max_bytes_per_attr) {
err = -EINVAL;
goto out;
}
err = ni_insert_attr(ni, type, name, name_len, asize, name_off, svcn,
&attr, mi, le);
if (err)
goto out;
attr->non_res = 1;
attr->name_off = cpu_to_le16(name_off);
attr->flags = flags;
/* This function can't fail - cause already checked above. */
run_pack(run, svcn, len, Add2Ptr(attr, run_off), run_size, &plen);
attr->nres.svcn = cpu_to_le64(svcn);
attr->nres.evcn = cpu_to_le64((u64)svcn + len - 1);
if (new_attr)
*new_attr = attr;
*(__le64 *)&attr->nres.run_off = cpu_to_le64(run_off);
attr->nres.alloc_size =
svcn ? 0 : cpu_to_le64((u64)len << ni->mi.sbi->cluster_bits);
attr->nres.data_size = attr->nres.alloc_size;
attr->nres.valid_size = attr->nres.alloc_size;
if (is_ext) {
if (flags & ATTR_FLAG_COMPRESSED)
attr->nres.c_unit = COMPRESSION_UNIT;
attr->nres.total_size = attr->nres.alloc_size;
}
out:
return err;
}
/*
* ni_insert_resident - Inserts new resident attribute.
*/
int ni_insert_resident(struct ntfs_inode *ni, u32 data_size,
enum ATTR_TYPE type, const __le16 *name, u8 name_len,
struct ATTRIB **new_attr, struct mft_inode **mi,
struct ATTR_LIST_ENTRY **le)
{
int err;
u32 name_size = ALIGN(name_len * sizeof(short), 8);
u32 asize = SIZEOF_RESIDENT + name_size + ALIGN(data_size, 8);
struct ATTRIB *attr;
err = ni_insert_attr(ni, type, name, name_len, asize, SIZEOF_RESIDENT,
0, &attr, mi, le);
if (err)
return err;
attr->non_res = 0;
attr->flags = 0;
attr->res.data_size = cpu_to_le32(data_size);
attr->res.data_off = cpu_to_le16(SIZEOF_RESIDENT + name_size);
if (type == ATTR_NAME) {
attr->res.flags = RESIDENT_FLAG_INDEXED;
/* is_attr_indexed(attr)) == true */
le16_add_cpu(&ni->mi.mrec->hard_links, 1);
ni->mi.dirty = true;
}
attr->res.res = 0;
if (new_attr)
*new_attr = attr;
return 0;
}
/*
* ni_remove_attr_le - Remove attribute from record.
*/
void ni_remove_attr_le(struct ntfs_inode *ni, struct ATTRIB *attr,
struct mft_inode *mi, struct ATTR_LIST_ENTRY *le)
{
mi_remove_attr(ni, mi, attr);
if (le)
al_remove_le(ni, le);
}
/*
* ni_delete_all - Remove all attributes and frees allocates space.
*
* ntfs_evict_inode->ntfs_clear_inode->ni_delete_all (if no links).
*/
int ni_delete_all(struct ntfs_inode *ni)
{
int err;
struct ATTR_LIST_ENTRY *le = NULL;
struct ATTRIB *attr = NULL;
struct rb_node *node;
u16 roff;
u32 asize;
CLST svcn, evcn;
struct ntfs_sb_info *sbi = ni->mi.sbi;
bool nt3 = is_ntfs3(sbi);
struct MFT_REF ref;
while ((attr = ni_enum_attr_ex(ni, attr, &le, NULL))) {
if (!nt3 || attr->name_len) {
;
} else if (attr->type == ATTR_REPARSE) {
mi_get_ref(&ni->mi, &ref);
ntfs_remove_reparse(sbi, 0, &ref);
} else if (attr->type == ATTR_ID && !attr->non_res &&
le32_to_cpu(attr->res.data_size) >=
sizeof(struct GUID)) {
ntfs_objid_remove(sbi, resident_data(attr));
}
if (!attr->non_res)
continue;
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
if (evcn + 1 <= svcn)
continue;
asize = le32_to_cpu(attr->size);
roff = le16_to_cpu(attr->nres.run_off);
if (roff > asize)
return -EINVAL;
/* run==1 means unpack and deallocate. */
run_unpack_ex(RUN_DEALLOCATE, sbi, ni->mi.rno, svcn, evcn, svcn,
Add2Ptr(attr, roff), asize - roff);
}
if (ni->attr_list.size) {
run_deallocate(ni->mi.sbi, &ni->attr_list.run, true);
al_destroy(ni);
}
/* Free all subrecords. */
for (node = rb_first(&ni->mi_tree); node;) {
struct rb_node *next = rb_next(node);
struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
clear_rec_inuse(mi->mrec);
mi->dirty = true;
mi_write(mi, 0);
ntfs_mark_rec_free(sbi, mi->rno, false);
ni_remove_mi(ni, mi);
mi_put(mi);
node = next;
}
/* Free base record. */
clear_rec_inuse(ni->mi.mrec);
ni->mi.dirty = true;
err = mi_write(&ni->mi, 0);
ntfs_mark_rec_free(sbi, ni->mi.rno, false);
return err;
}
/* ni_fname_name
*
* Return: File name attribute by its value.
*/
struct ATTR_FILE_NAME *ni_fname_name(struct ntfs_inode *ni,
const struct le_str *uni,
const struct MFT_REF *home_dir,
struct mft_inode **mi,
struct ATTR_LIST_ENTRY **le)
{
struct ATTRIB *attr = NULL;
struct ATTR_FILE_NAME *fname;
if (le)
*le = NULL;
/* Enumerate all names. */
next:
attr = ni_find_attr(ni, attr, le, ATTR_NAME, NULL, 0, NULL, mi);
if (!attr)
return NULL;
fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
if (!fname)
goto next;
if (home_dir && memcmp(home_dir, &fname->home, sizeof(*home_dir)))
goto next;
if (!uni)
return fname;
if (uni->len != fname->name_len)
goto next;
if (ntfs_cmp_names(uni->name, uni->len, fname->name, uni->len, NULL,
false))
goto next;
return fname;
}
/*
* ni_fname_type
*
* Return: File name attribute with given type.
*/
struct ATTR_FILE_NAME *ni_fname_type(struct ntfs_inode *ni, u8 name_type,
struct mft_inode **mi,
struct ATTR_LIST_ENTRY **le)
{
struct ATTRIB *attr = NULL;
struct ATTR_FILE_NAME *fname;
*le = NULL;
if (name_type == FILE_NAME_POSIX)
return NULL;
/* Enumerate all names. */
for (;;) {
attr = ni_find_attr(ni, attr, le, ATTR_NAME, NULL, 0, NULL, mi);
if (!attr)
return NULL;
fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
if (fname && name_type == fname->type)
return fname;
}
}
/*
* ni_new_attr_flags
*
* Process compressed/sparsed in special way.
* NOTE: You need to set ni->std_fa = new_fa
* after this function to keep internal structures in consistency.
*/
int ni_new_attr_flags(struct ntfs_inode *ni, enum FILE_ATTRIBUTE new_fa)
{
struct ATTRIB *attr;
struct mft_inode *mi;
__le16 new_aflags;
u32 new_asize;
attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, &mi);
if (!attr)
return -EINVAL;
new_aflags = attr->flags;
if (new_fa & FILE_ATTRIBUTE_SPARSE_FILE)
new_aflags |= ATTR_FLAG_SPARSED;
else
new_aflags &= ~ATTR_FLAG_SPARSED;
if (new_fa & FILE_ATTRIBUTE_COMPRESSED)
new_aflags |= ATTR_FLAG_COMPRESSED;
else
new_aflags &= ~ATTR_FLAG_COMPRESSED;
if (new_aflags == attr->flags)
return 0;
if ((new_aflags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) ==
(ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) {
ntfs_inode_warn(&ni->vfs_inode,
"file can't be sparsed and compressed");
return -EOPNOTSUPP;
}
if (!attr->non_res)
goto out;
if (attr->nres.data_size) {
ntfs_inode_warn(
&ni->vfs_inode,
"one can change sparsed/compressed only for empty files");
return -EOPNOTSUPP;
}
/* Resize nonresident empty attribute in-place only. */
new_asize = (new_aflags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) ?
(SIZEOF_NONRESIDENT_EX + 8) :
(SIZEOF_NONRESIDENT + 8);
if (!mi_resize_attr(mi, attr, new_asize - le32_to_cpu(attr->size)))
return -EOPNOTSUPP;
if (new_aflags & ATTR_FLAG_SPARSED) {
attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
/* Windows uses 16 clusters per frame but supports one cluster per frame too. */
attr->nres.c_unit = 0;
ni->vfs_inode.i_mapping->a_ops = &ntfs_aops;
} else if (new_aflags & ATTR_FLAG_COMPRESSED) {
attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
/* The only allowed: 16 clusters per frame. */
attr->nres.c_unit = NTFS_LZNT_CUNIT;
ni->vfs_inode.i_mapping->a_ops = &ntfs_aops_cmpr;
} else {
attr->name_off = SIZEOF_NONRESIDENT_LE;
/* Normal files. */
attr->nres.c_unit = 0;
ni->vfs_inode.i_mapping->a_ops = &ntfs_aops;
}
attr->nres.run_off = attr->name_off;
out:
attr->flags = new_aflags;
mi->dirty = true;
return 0;
}
/*
* ni_parse_reparse
*
* buffer - memory for reparse buffer header
*/
enum REPARSE_SIGN ni_parse_reparse(struct ntfs_inode *ni, struct ATTRIB *attr,
struct REPARSE_DATA_BUFFER *buffer)
{
const struct REPARSE_DATA_BUFFER *rp = NULL;
u8 bits;
u16 len;
typeof(rp->CompressReparseBuffer) *cmpr;
/* Try to estimate reparse point. */
if (!attr->non_res) {
rp = resident_data_ex(attr, sizeof(struct REPARSE_DATA_BUFFER));
} else if (le64_to_cpu(attr->nres.data_size) >=
sizeof(struct REPARSE_DATA_BUFFER)) {
struct runs_tree run;
run_init(&run);
if (!attr_load_runs_vcn(ni, ATTR_REPARSE, NULL, 0, &run, 0) &&
!ntfs_read_run_nb(ni->mi.sbi, &run, 0, buffer,
sizeof(struct REPARSE_DATA_BUFFER),
NULL)) {
rp = buffer;
}
run_close(&run);
}
if (!rp)
return REPARSE_NONE;
len = le16_to_cpu(rp->ReparseDataLength);
switch (rp->ReparseTag) {
case (IO_REPARSE_TAG_MICROSOFT | IO_REPARSE_TAG_SYMBOLIC_LINK):
break; /* Symbolic link. */
case IO_REPARSE_TAG_MOUNT_POINT:
break; /* Mount points and junctions. */
case IO_REPARSE_TAG_SYMLINK:
break;
case IO_REPARSE_TAG_COMPRESS:
/*
* WOF - Windows Overlay Filter - Used to compress files with
* LZX/Xpress.
*
* Unlike native NTFS file compression, the Windows
* Overlay Filter supports only read operations. This means
* that it doesn't need to sector-align each compressed chunk,
* so the compressed data can be packed more tightly together.
* If you open the file for writing, the WOF just decompresses
* the entire file, turning it back into a plain file.
*
* Ntfs3 driver decompresses the entire file only on write or
* change size requests.
*/
cmpr = &rp->CompressReparseBuffer;
if (len < sizeof(*cmpr) ||
cmpr->WofVersion != WOF_CURRENT_VERSION ||
cmpr->WofProvider != WOF_PROVIDER_SYSTEM ||
cmpr->ProviderVer != WOF_PROVIDER_CURRENT_VERSION) {
return REPARSE_NONE;
}
switch (cmpr->CompressionFormat) {
case WOF_COMPRESSION_XPRESS4K:
bits = 0xc; // 4k
break;
case WOF_COMPRESSION_XPRESS8K:
bits = 0xd; // 8k
break;
case WOF_COMPRESSION_XPRESS16K:
bits = 0xe; // 16k
break;
case WOF_COMPRESSION_LZX32K:
bits = 0xf; // 32k
break;
default:
bits = 0x10; // 64k
break;
}
ni_set_ext_compress_bits(ni, bits);
return REPARSE_COMPRESSED;
case IO_REPARSE_TAG_DEDUP:
ni->ni_flags |= NI_FLAG_DEDUPLICATED;
return REPARSE_DEDUPLICATED;
default:
if (rp->ReparseTag & IO_REPARSE_TAG_NAME_SURROGATE)
break;
return REPARSE_NONE;
}
if (buffer != rp)
memcpy(buffer, rp, sizeof(struct REPARSE_DATA_BUFFER));
/* Looks like normal symlink. */
return REPARSE_LINK;
}
/*
* ni_fiemap - Helper for file_fiemap().
*
* Assumed ni_lock.
* TODO: Less aggressive locks.
*/
int ni_fiemap(struct ntfs_inode *ni, struct fiemap_extent_info *fieinfo,
__u64 vbo, __u64 len)
{
int err = 0;
struct ntfs_sb_info *sbi = ni->mi.sbi;
u8 cluster_bits = sbi->cluster_bits;
struct runs_tree *run;
struct rw_semaphore *run_lock;
struct ATTRIB *attr;
CLST vcn = vbo >> cluster_bits;
CLST lcn, clen;
u64 valid = ni->i_valid;
u64 lbo, bytes;
u64 end, alloc_size;
size_t idx = -1;
u32 flags;
bool ok;
if (S_ISDIR(ni->vfs_inode.i_mode)) {
run = &ni->dir.alloc_run;
attr = ni_find_attr(ni, NULL, NULL, ATTR_ALLOC, I30_NAME,
ARRAY_SIZE(I30_NAME), NULL, NULL);
run_lock = &ni->dir.run_lock;
} else {
run = &ni->file.run;
attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL,
NULL);
if (!attr) {
err = -EINVAL;
goto out;
}
if (is_attr_compressed(attr)) {
/* Unfortunately cp -r incorrectly treats compressed clusters. */
err = -EOPNOTSUPP;
ntfs_inode_warn(
&ni->vfs_inode,
"fiemap is not supported for compressed file (cp -r)");
goto out;
}
run_lock = &ni->file.run_lock;
}
if (!attr || !attr->non_res) {
err = fiemap_fill_next_extent(
fieinfo, 0, 0,
attr ? le32_to_cpu(attr->res.data_size) : 0,
FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_LAST |
FIEMAP_EXTENT_MERGED);
goto out;
}
end = vbo + len;
alloc_size = le64_to_cpu(attr->nres.alloc_size);
if (end > alloc_size)
end = alloc_size;
down_read(run_lock);
while (vbo < end) {
if (idx == -1) {
ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
} else {
CLST vcn_next = vcn;
ok = run_get_entry(run, ++idx, &vcn, &lcn, &clen) &&
vcn == vcn_next;
if (!ok)
vcn = vcn_next;
}
if (!ok) {
up_read(run_lock);
down_write(run_lock);
err = attr_load_runs_vcn(ni, attr->type,
attr_name(attr),
attr->name_len, run, vcn);
up_write(run_lock);
down_read(run_lock);
if (err)
break;
ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
if (!ok) {
err = -EINVAL;
break;
}
}
if (!clen) {
err = -EINVAL; // ?
break;
}
if (lcn == SPARSE_LCN) {
vcn += clen;
vbo = (u64)vcn << cluster_bits;
continue;
}
flags = FIEMAP_EXTENT_MERGED;
if (S_ISDIR(ni->vfs_inode.i_mode)) {
;
} else if (is_attr_compressed(attr)) {
CLST clst_data;
err = attr_is_frame_compressed(
ni, attr, vcn >> attr->nres.c_unit, &clst_data);
if (err)
break;
if (clst_data < NTFS_LZNT_CLUSTERS)
flags |= FIEMAP_EXTENT_ENCODED;
} else if (is_attr_encrypted(attr)) {
flags |= FIEMAP_EXTENT_DATA_ENCRYPTED;
}
vbo = (u64)vcn << cluster_bits;
bytes = (u64)clen << cluster_bits;
lbo = (u64)lcn << cluster_bits;
vcn += clen;
if (vbo + bytes >= end)
bytes = end - vbo;
if (vbo + bytes <= valid) {
;
} else if (vbo >= valid) {
flags |= FIEMAP_EXTENT_UNWRITTEN;
} else {
/* vbo < valid && valid < vbo + bytes */
u64 dlen = valid - vbo;
if (vbo + dlen >= end)
flags |= FIEMAP_EXTENT_LAST;
err = fiemap_fill_next_extent(fieinfo, vbo, lbo, dlen,
flags);
if (err < 0)
break;
if (err == 1) {
err = 0;
break;
}
vbo = valid;
bytes -= dlen;
if (!bytes)
continue;
lbo += dlen;
flags |= FIEMAP_EXTENT_UNWRITTEN;
}
if (vbo + bytes >= end)
flags |= FIEMAP_EXTENT_LAST;
err = fiemap_fill_next_extent(fieinfo, vbo, lbo, bytes, flags);
if (err < 0)
break;
if (err == 1) {
err = 0;
break;
}
vbo += bytes;
}
up_read(run_lock);
out:
return err;
}
/*
* ni_readpage_cmpr
*
* When decompressing, we typically obtain more than one page per reference.
* We inject the additional pages into the page cache.
*/
int ni_readpage_cmpr(struct ntfs_inode *ni, struct page *page)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct address_space *mapping = page->mapping;
pgoff_t index = page->index;
u64 frame_vbo, vbo = (u64)index << PAGE_SHIFT;
struct page **pages = NULL; /* Array of at most 16 pages. stack? */
u8 frame_bits;
CLST frame;
u32 i, idx, frame_size, pages_per_frame;
gfp_t gfp_mask;
struct page *pg;
if (vbo >= ni->vfs_inode.i_size) {
SetPageUptodate(page);
err = 0;
goto out;
}
if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
/* Xpress or LZX. */
frame_bits = ni_ext_compress_bits(ni);
} else {
/* LZNT compression. */
frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
}
frame_size = 1u << frame_bits;
frame = vbo >> frame_bits;
frame_vbo = (u64)frame << frame_bits;
idx = (vbo - frame_vbo) >> PAGE_SHIFT;
pages_per_frame = frame_size >> PAGE_SHIFT;
pages = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
if (!pages) {
err = -ENOMEM;
goto out;
}
pages[idx] = page;
index = frame_vbo >> PAGE_SHIFT;
gfp_mask = mapping_gfp_mask(mapping);
for (i = 0; i < pages_per_frame; i++, index++) {
if (i == idx)
continue;
pg = find_or_create_page(mapping, index, gfp_mask);
if (!pg) {
err = -ENOMEM;
goto out1;
}
pages[i] = pg;
}
err = ni_read_frame(ni, frame_vbo, pages, pages_per_frame);
out1:
if (err)
SetPageError(page);
for (i = 0; i < pages_per_frame; i++) {
pg = pages[i];
if (i == idx)
continue;
unlock_page(pg);
put_page(pg);
}
out:
/* At this point, err contains 0 or -EIO depending on the "critical" page. */
kfree(pages);
unlock_page(page);
return err;
}
#ifdef CONFIG_NTFS3_LZX_XPRESS
/*
* ni_decompress_file - Decompress LZX/Xpress compressed file.
*
* Remove ATTR_DATA::WofCompressedData.
* Remove ATTR_REPARSE.
*/
int ni_decompress_file(struct ntfs_inode *ni)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct inode *inode = &ni->vfs_inode;
loff_t i_size = inode->i_size;
struct address_space *mapping = inode->i_mapping;
gfp_t gfp_mask = mapping_gfp_mask(mapping);
struct page **pages = NULL;
struct ATTR_LIST_ENTRY *le;
struct ATTRIB *attr;
CLST vcn, cend, lcn, clen, end;
pgoff_t index;
u64 vbo;
u8 frame_bits;
u32 i, frame_size, pages_per_frame, bytes;
struct mft_inode *mi;
int err;
/* Clusters for decompressed data. */
cend = bytes_to_cluster(sbi, i_size);
if (!i_size)
goto remove_wof;
/* Check in advance. */
if (cend > wnd_zeroes(&sbi->used.bitmap)) {
err = -ENOSPC;
goto out;
}
frame_bits = ni_ext_compress_bits(ni);
frame_size = 1u << frame_bits;
pages_per_frame = frame_size >> PAGE_SHIFT;
pages = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
if (!pages) {
err = -ENOMEM;
goto out;
}
/*
* Step 1: Decompress data and copy to new allocated clusters.
*/
index = 0;
for (vbo = 0; vbo < i_size; vbo += bytes) {
u32 nr_pages;
bool new;
if (vbo + frame_size > i_size) {
bytes = i_size - vbo;
nr_pages = (bytes + PAGE_SIZE - 1) >> PAGE_SHIFT;
} else {
nr_pages = pages_per_frame;
bytes = frame_size;
}
end = bytes_to_cluster(sbi, vbo + bytes);
for (vcn = vbo >> sbi->cluster_bits; vcn < end; vcn += clen) {
err = attr_data_get_block(ni, vcn, cend - vcn, &lcn,
&clen, &new, false);
if (err)
goto out;
}
for (i = 0; i < pages_per_frame; i++, index++) {
struct page *pg;
pg = find_or_create_page(mapping, index, gfp_mask);
if (!pg) {
while (i--) {
unlock_page(pages[i]);
put_page(pages[i]);
}
err = -ENOMEM;
goto out;
}
pages[i] = pg;
}
err = ni_read_frame(ni, vbo, pages, pages_per_frame);
if (!err) {
down_read(&ni->file.run_lock);
err = ntfs_bio_pages(sbi, &ni->file.run, pages,
nr_pages, vbo, bytes,
REQ_OP_WRITE);
up_read(&ni->file.run_lock);
}
for (i = 0; i < pages_per_frame; i++) {
unlock_page(pages[i]);
put_page(pages[i]);
}
if (err)
goto out;
cond_resched();
}
remove_wof:
/*
* Step 2: Deallocate attributes ATTR_DATA::WofCompressedData
* and ATTR_REPARSE.
*/
attr = NULL;
le = NULL;
while ((attr = ni_enum_attr_ex(ni, attr, &le, NULL))) {
CLST svcn, evcn;
u32 asize, roff;
if (attr->type == ATTR_REPARSE) {
struct MFT_REF ref;
mi_get_ref(&ni->mi, &ref);
ntfs_remove_reparse(sbi, 0, &ref);
}
if (!attr->non_res)
continue;
if (attr->type != ATTR_REPARSE &&
(attr->type != ATTR_DATA ||
attr->name_len != ARRAY_SIZE(WOF_NAME) ||
memcmp(attr_name(attr), WOF_NAME, sizeof(WOF_NAME))))
continue;
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
if (evcn + 1 <= svcn)
continue;
asize = le32_to_cpu(attr->size);
roff = le16_to_cpu(attr->nres.run_off);
if (roff > asize) {
err = -EINVAL;
goto out;
}
/*run==1 Means unpack and deallocate. */
run_unpack_ex(RUN_DEALLOCATE, sbi, ni->mi.rno, svcn, evcn, svcn,
Add2Ptr(attr, roff), asize - roff);
}
/*
* Step 3: Remove attribute ATTR_DATA::WofCompressedData.
*/
err = ni_remove_attr(ni, ATTR_DATA, WOF_NAME, ARRAY_SIZE(WOF_NAME),
false, NULL);
if (err)
goto out;
/*
* Step 4: Remove ATTR_REPARSE.
*/
err = ni_remove_attr(ni, ATTR_REPARSE, NULL, 0, false, NULL);
if (err)
goto out;
/*
* Step 5: Remove sparse flag from data attribute.
*/
attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
if (attr->non_res && is_attr_sparsed(attr)) {
/* Sparsed attribute header is 8 bytes bigger than normal. */
struct MFT_REC *rec = mi->mrec;
u32 used = le32_to_cpu(rec->used);
u32 asize = le32_to_cpu(attr->size);
u16 roff = le16_to_cpu(attr->nres.run_off);
char *rbuf = Add2Ptr(attr, roff);
memmove(rbuf - 8, rbuf, used - PtrOffset(rec, rbuf));
attr->size = cpu_to_le32(asize - 8);
attr->flags &= ~ATTR_FLAG_SPARSED;
attr->nres.run_off = cpu_to_le16(roff - 8);
attr->nres.c_unit = 0;
rec->used = cpu_to_le32(used - 8);
mi->dirty = true;
ni->std_fa &= ~(FILE_ATTRIBUTE_SPARSE_FILE |
FILE_ATTRIBUTE_REPARSE_POINT);
mark_inode_dirty(inode);
}
/* Clear cached flag. */
ni->ni_flags &= ~NI_FLAG_COMPRESSED_MASK;
if (ni->file.offs_page) {
put_page(ni->file.offs_page);
ni->file.offs_page = NULL;
}
mapping->a_ops = &ntfs_aops;
out:
kfree(pages);
if (err)
_ntfs_bad_inode(inode);
return err;
}
/*
* decompress_lzx_xpress - External compression LZX/Xpress.
*/
static int decompress_lzx_xpress(struct ntfs_sb_info *sbi, const char *cmpr,
size_t cmpr_size, void *unc, size_t unc_size,
u32 frame_size)
{
int err;
void *ctx;
if (cmpr_size == unc_size) {
/* Frame not compressed. */
memcpy(unc, cmpr, unc_size);
return 0;
}
err = 0;
if (frame_size == 0x8000) {
mutex_lock(&sbi->compress.mtx_lzx);
/* LZX: Frame compressed. */
ctx = sbi->compress.lzx;
if (!ctx) {
/* Lazy initialize LZX decompress context. */
ctx = lzx_allocate_decompressor();
if (!ctx) {
err = -ENOMEM;
goto out1;
}
sbi->compress.lzx = ctx;
}
if (lzx_decompress(ctx, cmpr, cmpr_size, unc, unc_size)) {
/* Treat all errors as "invalid argument". */
err = -EINVAL;
}
out1:
mutex_unlock(&sbi->compress.mtx_lzx);
} else {
/* XPRESS: Frame compressed. */
mutex_lock(&sbi->compress.mtx_xpress);
ctx = sbi->compress.xpress;
if (!ctx) {
/* Lazy initialize Xpress decompress context. */
ctx = xpress_allocate_decompressor();
if (!ctx) {
err = -ENOMEM;
goto out2;
}
sbi->compress.xpress = ctx;
}
if (xpress_decompress(ctx, cmpr, cmpr_size, unc, unc_size)) {
/* Treat all errors as "invalid argument". */
err = -EINVAL;
}
out2:
mutex_unlock(&sbi->compress.mtx_xpress);
}
return err;
}
#endif
/*
* ni_read_frame
*
* Pages - Array of locked pages.
*/
int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
u32 pages_per_frame)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
u8 cluster_bits = sbi->cluster_bits;
char *frame_ondisk = NULL;
char *frame_mem = NULL;
struct page **pages_disk = NULL;
struct ATTR_LIST_ENTRY *le = NULL;
struct runs_tree *run = &ni->file.run;
u64 valid_size = ni->i_valid;
u64 vbo_disk;
size_t unc_size;
u32 frame_size, i, npages_disk, ondisk_size;
struct page *pg;
struct ATTRIB *attr;
CLST frame, clst_data;
/*
* To simplify decompress algorithm do vmap for source
* and target pages.
*/
for (i = 0; i < pages_per_frame; i++)
kmap(pages[i]);
frame_size = pages_per_frame << PAGE_SHIFT;
frame_mem = vmap(pages, pages_per_frame, VM_MAP, PAGE_KERNEL);
if (!frame_mem) {
err = -ENOMEM;
goto out;
}
attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL, NULL);
if (!attr) {
err = -ENOENT;
goto out1;
}
if (!attr->non_res) {
u32 data_size = le32_to_cpu(attr->res.data_size);
memset(frame_mem, 0, frame_size);
if (frame_vbo < data_size) {
ondisk_size = data_size - frame_vbo;
memcpy(frame_mem, resident_data(attr) + frame_vbo,
min(ondisk_size, frame_size));
}
err = 0;
goto out1;
}
if (frame_vbo >= valid_size) {
memset(frame_mem, 0, frame_size);
err = 0;
goto out1;
}
if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
#ifndef CONFIG_NTFS3_LZX_XPRESS
err = -EOPNOTSUPP;
goto out1;
#else
u32 frame_bits = ni_ext_compress_bits(ni);
u64 frame64 = frame_vbo >> frame_bits;
u64 frames, vbo_data;
if (frame_size != (1u << frame_bits)) {
err = -EINVAL;
goto out1;
}
switch (frame_size) {
case 0x1000:
case 0x2000:
case 0x4000:
case 0x8000:
break;
default:
/* Unknown compression. */
err = -EOPNOTSUPP;
goto out1;
}
attr = ni_find_attr(ni, attr, &le, ATTR_DATA, WOF_NAME,
ARRAY_SIZE(WOF_NAME), NULL, NULL);
if (!attr) {
ntfs_inode_err(
&ni->vfs_inode,
"external compressed file should contains data attribute \"WofCompressedData\"");
err = -EINVAL;
goto out1;
}
if (!attr->non_res) {
run = NULL;
} else {
run = run_alloc();
if (!run) {
err = -ENOMEM;
goto out1;
}
}
frames = (ni->vfs_inode.i_size - 1) >> frame_bits;
err = attr_wof_frame_info(ni, attr, run, frame64, frames,
frame_bits, &ondisk_size, &vbo_data);
if (err)
goto out2;
if (frame64 == frames) {
unc_size = 1 + ((ni->vfs_inode.i_size - 1) &
(frame_size - 1));
ondisk_size = attr_size(attr) - vbo_data;
} else {
unc_size = frame_size;
}
if (ondisk_size > frame_size) {
err = -EINVAL;
goto out2;
}
if (!attr->non_res) {
if (vbo_data + ondisk_size >
le32_to_cpu(attr->res.data_size)) {
err = -EINVAL;
goto out1;
}
err = decompress_lzx_xpress(
sbi, Add2Ptr(resident_data(attr), vbo_data),
ondisk_size, frame_mem, unc_size, frame_size);
goto out1;
}
vbo_disk = vbo_data;
/* Load all runs to read [vbo_disk-vbo_to). */
err = attr_load_runs_range(ni, ATTR_DATA, WOF_NAME,
ARRAY_SIZE(WOF_NAME), run, vbo_disk,
vbo_data + ondisk_size);
if (err)
goto out2;
npages_disk = (ondisk_size + (vbo_disk & (PAGE_SIZE - 1)) +
PAGE_SIZE - 1) >>
PAGE_SHIFT;
#endif
} else if (is_attr_compressed(attr)) {
/* LZNT compression. */
if (sbi->cluster_size > NTFS_LZNT_MAX_CLUSTER) {
err = -EOPNOTSUPP;
goto out1;
}
if (attr->nres.c_unit != NTFS_LZNT_CUNIT) {
err = -EOPNOTSUPP;
goto out1;
}
down_write(&ni->file.run_lock);
run_truncate_around(run, le64_to_cpu(attr->nres.svcn));
frame = frame_vbo >> (cluster_bits + NTFS_LZNT_CUNIT);
err = attr_is_frame_compressed(ni, attr, frame, &clst_data);
up_write(&ni->file.run_lock);
if (err)
goto out1;
if (!clst_data) {
memset(frame_mem, 0, frame_size);
goto out1;
}
frame_size = sbi->cluster_size << NTFS_LZNT_CUNIT;
ondisk_size = clst_data << cluster_bits;
if (clst_data >= NTFS_LZNT_CLUSTERS) {
/* Frame is not compressed. */
down_read(&ni->file.run_lock);
err = ntfs_bio_pages(sbi, run, pages, pages_per_frame,
frame_vbo, ondisk_size,
REQ_OP_READ);
up_read(&ni->file.run_lock);
goto out1;
}
vbo_disk = frame_vbo;
npages_disk = (ondisk_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
} else {
__builtin_unreachable();
err = -EINVAL;
goto out1;
}
pages_disk = kzalloc(npages_disk * sizeof(struct page *), GFP_NOFS);
if (!pages_disk) {
err = -ENOMEM;
goto out2;
}
for (i = 0; i < npages_disk; i++) {
pg = alloc_page(GFP_KERNEL);
if (!pg) {
err = -ENOMEM;
goto out3;
}
pages_disk[i] = pg;
lock_page(pg);
kmap(pg);
}
/* Read 'ondisk_size' bytes from disk. */
down_read(&ni->file.run_lock);
err = ntfs_bio_pages(sbi, run, pages_disk, npages_disk, vbo_disk,
ondisk_size, REQ_OP_READ);
up_read(&ni->file.run_lock);
if (err)
goto out3;
/*
* To simplify decompress algorithm do vmap for source and target pages.
*/
frame_ondisk = vmap(pages_disk, npages_disk, VM_MAP, PAGE_KERNEL_RO);
if (!frame_ondisk) {
err = -ENOMEM;
goto out3;
}
/* Decompress: Frame_ondisk -> frame_mem. */
#ifdef CONFIG_NTFS3_LZX_XPRESS
if (run != &ni->file.run) {
/* LZX or XPRESS */
err = decompress_lzx_xpress(
sbi, frame_ondisk + (vbo_disk & (PAGE_SIZE - 1)),
ondisk_size, frame_mem, unc_size, frame_size);
} else
#endif
{
/* LZNT - Native NTFS compression. */
unc_size = decompress_lznt(frame_ondisk, ondisk_size, frame_mem,
frame_size);
if ((ssize_t)unc_size < 0)
err = unc_size;
else if (!unc_size || unc_size > frame_size)
err = -EINVAL;
}
if (!err && valid_size < frame_vbo + frame_size) {
size_t ok = valid_size - frame_vbo;
memset(frame_mem + ok, 0, frame_size - ok);
}
vunmap(frame_ondisk);
out3:
for (i = 0; i < npages_disk; i++) {
pg = pages_disk[i];
if (pg) {
kunmap(pg);
unlock_page(pg);
put_page(pg);
}
}
kfree(pages_disk);
out2:
#ifdef CONFIG_NTFS3_LZX_XPRESS
if (run != &ni->file.run)
run_free(run);
#endif
out1:
vunmap(frame_mem);
out:
for (i = 0; i < pages_per_frame; i++) {
pg = pages[i];
kunmap(pg);
ClearPageError(pg);
SetPageUptodate(pg);
}
return err;
}
/*
* ni_write_frame
*
* Pages - Array of locked pages.
*/
int ni_write_frame(struct ntfs_inode *ni, struct page **pages,
u32 pages_per_frame)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
u8 frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
u32 frame_size = sbi->cluster_size << NTFS_LZNT_CUNIT;
u64 frame_vbo = (u64)pages[0]->index << PAGE_SHIFT;
CLST frame = frame_vbo >> frame_bits;
char *frame_ondisk = NULL;
struct page **pages_disk = NULL;
struct ATTR_LIST_ENTRY *le = NULL;
char *frame_mem;
struct ATTRIB *attr;
struct mft_inode *mi;
u32 i;
struct page *pg;
size_t compr_size, ondisk_size;
struct lznt *lznt;
attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL, &mi);
if (!attr) {
err = -ENOENT;
goto out;
}
if (WARN_ON(!is_attr_compressed(attr))) {
err = -EINVAL;
goto out;
}
if (sbi->cluster_size > NTFS_LZNT_MAX_CLUSTER) {
err = -EOPNOTSUPP;
goto out;
}
if (!attr->non_res) {
down_write(&ni->file.run_lock);
err = attr_make_nonresident(ni, attr, le, mi,
le32_to_cpu(attr->res.data_size),
&ni->file.run, &attr, pages[0]);
up_write(&ni->file.run_lock);
if (err)
goto out;
}
if (attr->nres.c_unit != NTFS_LZNT_CUNIT) {
err = -EOPNOTSUPP;
goto out;
}
pages_disk = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
if (!pages_disk) {
err = -ENOMEM;
goto out;
}
for (i = 0; i < pages_per_frame; i++) {
pg = alloc_page(GFP_KERNEL);
if (!pg) {
err = -ENOMEM;
goto out1;
}
pages_disk[i] = pg;
lock_page(pg);
kmap(pg);
}
/* To simplify compress algorithm do vmap for source and target pages. */
frame_ondisk = vmap(pages_disk, pages_per_frame, VM_MAP, PAGE_KERNEL);
if (!frame_ondisk) {
err = -ENOMEM;
goto out1;
}
for (i = 0; i < pages_per_frame; i++)
kmap(pages[i]);
/* Map in-memory frame for read-only. */
frame_mem = vmap(pages, pages_per_frame, VM_MAP, PAGE_KERNEL_RO);
if (!frame_mem) {
err = -ENOMEM;
goto out2;
}
mutex_lock(&sbi->compress.mtx_lznt);
lznt = NULL;
if (!sbi->compress.lznt) {
/*
* LZNT implements two levels of compression:
* 0 - Standard compression
* 1 - Best compression, requires a lot of cpu
* use mount option?
*/
lznt = get_lznt_ctx(0);
if (!lznt) {
mutex_unlock(&sbi->compress.mtx_lznt);
err = -ENOMEM;
goto out3;
}
sbi->compress.lznt = lznt;
lznt = NULL;
}
/* Compress: frame_mem -> frame_ondisk */
compr_size = compress_lznt(frame_mem, frame_size, frame_ondisk,
frame_size, sbi->compress.lznt);
mutex_unlock(&sbi->compress.mtx_lznt);
kfree(lznt);
if (compr_size + sbi->cluster_size > frame_size) {
/* Frame is not compressed. */
compr_size = frame_size;
ondisk_size = frame_size;
} else if (compr_size) {
/* Frame is compressed. */
ondisk_size = ntfs_up_cluster(sbi, compr_size);
memset(frame_ondisk + compr_size, 0, ondisk_size - compr_size);
} else {
/* Frame is sparsed. */
ondisk_size = 0;
}
down_write(&ni->file.run_lock);
run_truncate_around(&ni->file.run, le64_to_cpu(attr->nres.svcn));
err = attr_allocate_frame(ni, frame, compr_size, ni->i_valid);
up_write(&ni->file.run_lock);
if (err)
goto out2;
if (!ondisk_size)
goto out2;
down_read(&ni->file.run_lock);
err = ntfs_bio_pages(sbi, &ni->file.run,
ondisk_size < frame_size ? pages_disk : pages,
pages_per_frame, frame_vbo, ondisk_size,
REQ_OP_WRITE);
up_read(&ni->file.run_lock);
out3:
vunmap(frame_mem);
out2:
for (i = 0; i < pages_per_frame; i++)
kunmap(pages[i]);
vunmap(frame_ondisk);
out1:
for (i = 0; i < pages_per_frame; i++) {
pg = pages_disk[i];
if (pg) {
kunmap(pg);
unlock_page(pg);
put_page(pg);
}
}
kfree(pages_disk);
out:
return err;
}
/*
* ni_remove_name - Removes name 'de' from MFT and from directory.
* 'de2' and 'undo_step' are used to restore MFT/dir, if error occurs.
*/
int ni_remove_name(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
struct NTFS_DE *de, struct NTFS_DE **de2, int *undo_step)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTR_FILE_NAME *de_name = (struct ATTR_FILE_NAME *)(de + 1);
struct ATTR_FILE_NAME *fname;
struct ATTR_LIST_ENTRY *le;
struct mft_inode *mi;
u16 de_key_size = le16_to_cpu(de->key_size);
u8 name_type;
*undo_step = 0;
/* Find name in record. */
mi_get_ref(&dir_ni->mi, &de_name->home);
fname = ni_fname_name(ni, (struct le_str *)&de_name->name_len,
&de_name->home, &mi, &le);
if (!fname)
return -ENOENT;
memcpy(&de_name->dup, &fname->dup, sizeof(struct NTFS_DUP_INFO));
name_type = paired_name(fname->type);
/* Mark ntfs as dirty. It will be cleared at umount. */
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
/* Step 1: Remove name from directory. */
err = indx_delete_entry(&dir_ni->dir, dir_ni, fname, de_key_size, sbi);
if (err)
return err;
/* Step 2: Remove name from MFT. */
ni_remove_attr_le(ni, attr_from_name(fname), mi, le);
*undo_step = 2;
/* Get paired name. */
fname = ni_fname_type(ni, name_type, &mi, &le);
if (fname) {
u16 de2_key_size = fname_full_size(fname);
*de2 = Add2Ptr(de, 1024);
(*de2)->key_size = cpu_to_le16(de2_key_size);
memcpy(*de2 + 1, fname, de2_key_size);
/* Step 3: Remove paired name from directory. */
err = indx_delete_entry(&dir_ni->dir, dir_ni, fname,
de2_key_size, sbi);
if (err)
return err;
/* Step 4: Remove paired name from MFT. */
ni_remove_attr_le(ni, attr_from_name(fname), mi, le);
*undo_step = 4;
}
return 0;
}
/*
* ni_remove_name_undo - Paired function for ni_remove_name.
*
* Return: True if ok
*/
bool ni_remove_name_undo(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
struct NTFS_DE *de, struct NTFS_DE *de2, int undo_step)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr;
u16 de_key_size;
switch (undo_step) {
case 4:
de_key_size = le16_to_cpu(de2->key_size);
if (ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0,
&attr, NULL, NULL))
return false;
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de2 + 1, de_key_size);
mi_get_ref(&ni->mi, &de2->ref);
de2->size = cpu_to_le16(ALIGN(de_key_size, 8) +
sizeof(struct NTFS_DE));
de2->flags = 0;
de2->res = 0;
if (indx_insert_entry(&dir_ni->dir, dir_ni, de2, sbi, NULL, 1))
return false;
fallthrough;
case 2:
de_key_size = le16_to_cpu(de->key_size);
if (ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0,
&attr, NULL, NULL))
return false;
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de + 1, de_key_size);
mi_get_ref(&ni->mi, &de->ref);
if (indx_insert_entry(&dir_ni->dir, dir_ni, de, sbi, NULL, 1))
return false;
}
return true;
}
/*
* ni_add_name - Add new name into MFT and into directory.
*/
int ni_add_name(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
struct NTFS_DE *de)
{
int err;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
struct mft_inode *mi;
struct ATTR_FILE_NAME *fname;
struct ATTR_FILE_NAME *de_name = (struct ATTR_FILE_NAME *)(de + 1);
u16 de_key_size = le16_to_cpu(de->key_size);
if (sbi->options->windows_names &&
!valid_windows_name(sbi, (struct le_str *)&de_name->name_len))
return -EINVAL;
/* If option "hide_dot_files" then set hidden attribute for dot files. */
if (ni->mi.sbi->options->hide_dot_files) {
if (de_name->name_len > 0 &&
le16_to_cpu(de_name->name[0]) == '.')
ni->std_fa |= FILE_ATTRIBUTE_HIDDEN;
else
ni->std_fa &= ~FILE_ATTRIBUTE_HIDDEN;
}
mi_get_ref(&ni->mi, &de->ref);
mi_get_ref(&dir_ni->mi, &de_name->home);
/* Fill duplicate from any ATTR_NAME. */
fname = ni_fname_name(ni, NULL, NULL, NULL, NULL);
if (fname)
memcpy(&de_name->dup, &fname->dup, sizeof(fname->dup));
de_name->dup.fa = ni->std_fa;
/* Insert new name into MFT. */
err = ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0, &attr,
&mi, &le);
if (err)
return err;
memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de_name, de_key_size);
/* Insert new name into directory. */
err = indx_insert_entry(&dir_ni->dir, dir_ni, de, sbi, NULL, 0);
if (err)
ni_remove_attr_le(ni, attr, mi, le);
return err;
}
/*
* ni_rename - Remove one name and insert new name.
*/
int ni_rename(struct ntfs_inode *dir_ni, struct ntfs_inode *new_dir_ni,
struct ntfs_inode *ni, struct NTFS_DE *de, struct NTFS_DE *new_de,
bool *is_bad)
{
int err;
struct NTFS_DE *de2 = NULL;
int undo = 0;
/*
* There are two possible ways to rename:
* 1) Add new name and remove old name.
* 2) Remove old name and add new name.
*
* In most cases (not all!) adding new name into MFT and into directory can
* allocate additional cluster(s).
* Second way may result to bad inode if we can't add new name
* and then can't restore (add) old name.
*/
/*
* Way 1 - Add new + remove old.
*/
err = ni_add_name(new_dir_ni, ni, new_de);
if (!err) {
err = ni_remove_name(dir_ni, ni, de, &de2, &undo);
if (err && ni_remove_name(new_dir_ni, ni, new_de, &de2, &undo))
*is_bad = true;
}
/*
* Way 2 - Remove old + add new.
*/
/*
* err = ni_remove_name(dir_ni, ni, de, &de2, &undo);
* if (!err) {
* err = ni_add_name(new_dir_ni, ni, new_de);
* if (err && !ni_remove_name_undo(dir_ni, ni, de, de2, undo))
* *is_bad = true;
* }
*/
return err;
}
/*
* ni_is_dirty - Return: True if 'ni' requires ni_write_inode.
*/
bool ni_is_dirty(struct inode *inode)
{
struct ntfs_inode *ni = ntfs_i(inode);
struct rb_node *node;
if (ni->mi.dirty || ni->attr_list.dirty ||
(ni->ni_flags & NI_FLAG_UPDATE_PARENT))
return true;
for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
if (rb_entry(node, struct mft_inode, node)->dirty)
return true;
}
return false;
}
/*
* ni_update_parent
*
* Update duplicate info of ATTR_FILE_NAME in MFT and in parent directories.
*/
static bool ni_update_parent(struct ntfs_inode *ni, struct NTFS_DUP_INFO *dup,
int sync)
{
struct ATTRIB *attr;
struct mft_inode *mi;
struct ATTR_LIST_ENTRY *le = NULL;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct super_block *sb = sbi->sb;
bool re_dirty = false;
if (ni->mi.mrec->flags & RECORD_FLAG_DIR) {
dup->fa |= FILE_ATTRIBUTE_DIRECTORY;
attr = NULL;
dup->alloc_size = 0;
dup->data_size = 0;
} else {
dup->fa &= ~FILE_ATTRIBUTE_DIRECTORY;
attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL,
&mi);
if (!attr) {
dup->alloc_size = dup->data_size = 0;
} else if (!attr->non_res) {
u32 data_size = le32_to_cpu(attr->res.data_size);
dup->alloc_size = cpu_to_le64(ALIGN(data_size, 8));
dup->data_size = cpu_to_le64(data_size);
} else {
u64 new_valid = ni->i_valid;
u64 data_size = le64_to_cpu(attr->nres.data_size);
__le64 valid_le;
dup->alloc_size = is_attr_ext(attr) ?
attr->nres.total_size :
attr->nres.alloc_size;
dup->data_size = attr->nres.data_size;
if (new_valid > data_size)
new_valid = data_size;
valid_le = cpu_to_le64(new_valid);
if (valid_le != attr->nres.valid_size) {
attr->nres.valid_size = valid_le;
mi->dirty = true;
}
}
}
/* TODO: Fill reparse info. */
dup->reparse = 0;
dup->ea_size = 0;
if (ni->ni_flags & NI_FLAG_EA) {
attr = ni_find_attr(ni, attr, &le, ATTR_EA_INFO, NULL, 0, NULL,
NULL);
if (attr) {
const struct EA_INFO *info;
info = resident_data_ex(attr, sizeof(struct EA_INFO));
/* If ATTR_EA_INFO exists 'info' can't be NULL. */
if (info)
dup->ea_size = info->size_pack;
}
}
attr = NULL;
le = NULL;
while ((attr = ni_find_attr(ni, attr, &le, ATTR_NAME, NULL, 0, NULL,
&mi))) {
struct inode *dir;
struct ATTR_FILE_NAME *fname;
fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
if (!fname || !memcmp(&fname->dup, dup, sizeof(fname->dup)))
continue;
/* ntfs_iget5 may sleep. */
dir = ntfs_iget5(sb, &fname->home, NULL);
if (IS_ERR(dir)) {
ntfs_inode_warn(
&ni->vfs_inode,
"failed to open parent directory r=%lx to update",
(long)ino_get(&fname->home));
continue;
}
if (!is_bad_inode(dir)) {
struct ntfs_inode *dir_ni = ntfs_i(dir);
if (!ni_trylock(dir_ni)) {
re_dirty = true;
} else {
indx_update_dup(dir_ni, sbi, fname, dup, sync);
ni_unlock(dir_ni);
memcpy(&fname->dup, dup, sizeof(fname->dup));
mi->dirty = true;
}
}
iput(dir);
}
return re_dirty;
}
/*
* ni_write_inode - Write MFT base record and all subrecords to disk.
*/
int ni_write_inode(struct inode *inode, int sync, const char *hint)
{
int err = 0, err2;
struct ntfs_inode *ni = ntfs_i(inode);
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
bool re_dirty = false;
struct ATTR_STD_INFO *std;
struct rb_node *node, *next;
struct NTFS_DUP_INFO dup;
if (is_bad_inode(inode) || sb_rdonly(sb))
return 0;
if (!ni_trylock(ni)) {
/* 'ni' is under modification, skip for now. */
mark_inode_dirty_sync(inode);
return 0;
}
if (!ni->mi.mrec)
goto out;
if (is_rec_inuse(ni->mi.mrec) &&
!(sbi->flags & NTFS_FLAGS_LOG_REPLAYING) && inode->i_nlink) {
bool modified = false;
struct timespec64 ctime = inode_get_ctime(inode);
/* Update times in standard attribute. */
std = ni_std(ni);
if (!std) {
err = -EINVAL;
goto out;
}
/* Update the access times if they have changed. */
dup.m_time = kernel2nt(&inode->i_mtime);
if (std->m_time != dup.m_time) {
std->m_time = dup.m_time;
modified = true;
}
dup.c_time = kernel2nt(&ctime);
if (std->c_time != dup.c_time) {
std->c_time = dup.c_time;
modified = true;
}
dup.a_time = kernel2nt(&inode->i_atime);
if (std->a_time != dup.a_time) {
std->a_time = dup.a_time;
modified = true;
}
dup.fa = ni->std_fa;
if (std->fa != dup.fa) {
std->fa = dup.fa;
modified = true;
}
/* std attribute is always in primary MFT record. */
if (modified)
ni->mi.dirty = true;
if (!ntfs_is_meta_file(sbi, inode->i_ino) &&
(modified || (ni->ni_flags & NI_FLAG_UPDATE_PARENT))
/* Avoid __wait_on_freeing_inode(inode). */
&& (sb->s_flags & SB_ACTIVE)) {
dup.cr_time = std->cr_time;
/* Not critical if this function fail. */
re_dirty = ni_update_parent(ni, &dup, sync);
if (re_dirty)
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
else
ni->ni_flags &= ~NI_FLAG_UPDATE_PARENT;
}
/* Update attribute list. */
if (ni->attr_list.size && ni->attr_list.dirty) {
if (inode->i_ino != MFT_REC_MFT || sync) {
err = ni_try_remove_attr_list(ni);
if (err)
goto out;
}
err = al_update(ni, sync);
if (err)
goto out;
}
}
for (node = rb_first(&ni->mi_tree); node; node = next) {
struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
bool is_empty;
next = rb_next(node);
if (!mi->dirty)
continue;
is_empty = !mi_enum_attr(mi, NULL);
if (is_empty)
clear_rec_inuse(mi->mrec);
err2 = mi_write(mi, sync);
if (!err && err2)
err = err2;
if (is_empty) {
ntfs_mark_rec_free(sbi, mi->rno, false);
rb_erase(node, &ni->mi_tree);
mi_put(mi);
}
}
if (ni->mi.dirty) {
err2 = mi_write(&ni->mi, sync);
if (!err && err2)
err = err2;
}
out:
ni_unlock(ni);
if (err) {
ntfs_inode_err(inode, "%s failed, %d.", hint, err);
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
return err;
}
if (re_dirty)
mark_inode_dirty_sync(inode);
return 0;
}
| linux-master | fs/ntfs3/frecord.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
* TODO: Merge attr_set_size/attr_data_get_block/attr_allocate_frame?
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
/*
* You can set external NTFS_MIN_LOG2_OF_CLUMP/NTFS_MAX_LOG2_OF_CLUMP to manage
* preallocate algorithm.
*/
#ifndef NTFS_MIN_LOG2_OF_CLUMP
#define NTFS_MIN_LOG2_OF_CLUMP 16
#endif
#ifndef NTFS_MAX_LOG2_OF_CLUMP
#define NTFS_MAX_LOG2_OF_CLUMP 26
#endif
// 16M
#define NTFS_CLUMP_MIN (1 << (NTFS_MIN_LOG2_OF_CLUMP + 8))
// 16G
#define NTFS_CLUMP_MAX (1ull << (NTFS_MAX_LOG2_OF_CLUMP + 8))
static inline u64 get_pre_allocated(u64 size)
{
u32 clump;
u8 align_shift;
u64 ret;
if (size <= NTFS_CLUMP_MIN) {
clump = 1 << NTFS_MIN_LOG2_OF_CLUMP;
align_shift = NTFS_MIN_LOG2_OF_CLUMP;
} else if (size >= NTFS_CLUMP_MAX) {
clump = 1 << NTFS_MAX_LOG2_OF_CLUMP;
align_shift = NTFS_MAX_LOG2_OF_CLUMP;
} else {
align_shift = NTFS_MIN_LOG2_OF_CLUMP - 1 +
__ffs(size >> (8 + NTFS_MIN_LOG2_OF_CLUMP));
clump = 1u << align_shift;
}
ret = (((size + clump - 1) >> align_shift)) << align_shift;
return ret;
}
/*
* attr_load_runs - Load all runs stored in @attr.
*/
static int attr_load_runs(struct ATTRIB *attr, struct ntfs_inode *ni,
struct runs_tree *run, const CLST *vcn)
{
int err;
CLST svcn = le64_to_cpu(attr->nres.svcn);
CLST evcn = le64_to_cpu(attr->nres.evcn);
u32 asize;
u16 run_off;
if (svcn >= evcn + 1 || run_is_mapped_full(run, svcn, evcn))
return 0;
if (vcn && (evcn < *vcn || *vcn < svcn))
return -EINVAL;
asize = le32_to_cpu(attr->size);
run_off = le16_to_cpu(attr->nres.run_off);
if (run_off > asize)
return -EINVAL;
err = run_unpack_ex(run, ni->mi.sbi, ni->mi.rno, svcn, evcn,
vcn ? *vcn : svcn, Add2Ptr(attr, run_off),
asize - run_off);
if (err < 0)
return err;
return 0;
}
/*
* run_deallocate_ex - Deallocate clusters.
*/
static int run_deallocate_ex(struct ntfs_sb_info *sbi, struct runs_tree *run,
CLST vcn, CLST len, CLST *done, bool trim)
{
int err = 0;
CLST vcn_next, vcn0 = vcn, lcn, clen, dn = 0;
size_t idx;
if (!len)
goto out;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
failed:
run_truncate(run, vcn0);
err = -EINVAL;
goto out;
}
for (;;) {
if (clen > len)
clen = len;
if (!clen) {
err = -EINVAL;
goto out;
}
if (lcn != SPARSE_LCN) {
if (sbi) {
/* mark bitmap range [lcn + clen) as free and trim clusters. */
mark_as_free_ex(sbi, lcn, clen, trim);
}
dn += clen;
}
len -= clen;
if (!len)
break;
vcn_next = vcn + clen;
if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
vcn != vcn_next) {
/* Save memory - don't load entire run. */
goto failed;
}
}
out:
if (done)
*done += dn;
return err;
}
/*
* attr_allocate_clusters - Find free space, mark it as used and store in @run.
*/
int attr_allocate_clusters(struct ntfs_sb_info *sbi, struct runs_tree *run,
CLST vcn, CLST lcn, CLST len, CLST *pre_alloc,
enum ALLOCATE_OPT opt, CLST *alen, const size_t fr,
CLST *new_lcn, CLST *new_len)
{
int err;
CLST flen, vcn0 = vcn, pre = pre_alloc ? *pre_alloc : 0;
size_t cnt = run->count;
for (;;) {
err = ntfs_look_for_free_space(sbi, lcn, len + pre, &lcn, &flen,
opt);
if (err == -ENOSPC && pre) {
pre = 0;
if (*pre_alloc)
*pre_alloc = 0;
continue;
}
if (err)
goto out;
if (vcn == vcn0) {
/* Return the first fragment. */
if (new_lcn)
*new_lcn = lcn;
if (new_len)
*new_len = flen;
}
/* Add new fragment into run storage. */
if (!run_add_entry(run, vcn, lcn, flen, opt & ALLOCATE_MFT)) {
/* Undo last 'ntfs_look_for_free_space' */
mark_as_free_ex(sbi, lcn, len, false);
err = -ENOMEM;
goto out;
}
if (opt & ALLOCATE_ZERO) {
u8 shift = sbi->cluster_bits - SECTOR_SHIFT;
err = blkdev_issue_zeroout(sbi->sb->s_bdev,
(sector_t)lcn << shift,
(sector_t)flen << shift,
GFP_NOFS, 0);
if (err)
goto out;
}
vcn += flen;
if (flen >= len || (opt & ALLOCATE_MFT) ||
(fr && run->count - cnt >= fr)) {
*alen = vcn - vcn0;
return 0;
}
len -= flen;
}
out:
/* Undo 'ntfs_look_for_free_space' */
if (vcn - vcn0) {
run_deallocate_ex(sbi, run, vcn0, vcn - vcn0, NULL, false);
run_truncate(run, vcn0);
}
return err;
}
/*
* attr_make_nonresident
*
* If page is not NULL - it is already contains resident data
* and locked (called from ni_write_frame()).
*/
int attr_make_nonresident(struct ntfs_inode *ni, struct ATTRIB *attr,
struct ATTR_LIST_ENTRY *le, struct mft_inode *mi,
u64 new_size, struct runs_tree *run,
struct ATTRIB **ins_attr, struct page *page)
{
struct ntfs_sb_info *sbi;
struct ATTRIB *attr_s;
struct MFT_REC *rec;
u32 used, asize, rsize, aoff, align;
bool is_data;
CLST len, alen;
char *next;
int err;
if (attr->non_res) {
*ins_attr = attr;
return 0;
}
sbi = mi->sbi;
rec = mi->mrec;
attr_s = NULL;
used = le32_to_cpu(rec->used);
asize = le32_to_cpu(attr->size);
next = Add2Ptr(attr, asize);
aoff = PtrOffset(rec, attr);
rsize = le32_to_cpu(attr->res.data_size);
is_data = attr->type == ATTR_DATA && !attr->name_len;
align = sbi->cluster_size;
if (is_attr_compressed(attr))
align <<= COMPRESSION_UNIT;
len = (rsize + align - 1) >> sbi->cluster_bits;
run_init(run);
/* Make a copy of original attribute. */
attr_s = kmemdup(attr, asize, GFP_NOFS);
if (!attr_s) {
err = -ENOMEM;
goto out;
}
if (!len) {
/* Empty resident -> Empty nonresident. */
alen = 0;
} else {
const char *data = resident_data(attr);
err = attr_allocate_clusters(sbi, run, 0, 0, len, NULL,
ALLOCATE_DEF, &alen, 0, NULL,
NULL);
if (err)
goto out1;
if (!rsize) {
/* Empty resident -> Non empty nonresident. */
} else if (!is_data) {
err = ntfs_sb_write_run(sbi, run, 0, data, rsize, 0);
if (err)
goto out2;
} else if (!page) {
char *kaddr;
page = grab_cache_page(ni->vfs_inode.i_mapping, 0);
if (!page) {
err = -ENOMEM;
goto out2;
}
kaddr = kmap_atomic(page);
memcpy(kaddr, data, rsize);
memset(kaddr + rsize, 0, PAGE_SIZE - rsize);
kunmap_atomic(kaddr);
flush_dcache_page(page);
SetPageUptodate(page);
set_page_dirty(page);
unlock_page(page);
put_page(page);
}
}
/* Remove original attribute. */
used -= asize;
memmove(attr, Add2Ptr(attr, asize), used - aoff);
rec->used = cpu_to_le32(used);
mi->dirty = true;
if (le)
al_remove_le(ni, le);
err = ni_insert_nonresident(ni, attr_s->type, attr_name(attr_s),
attr_s->name_len, run, 0, alen,
attr_s->flags, &attr, NULL, NULL);
if (err)
goto out3;
kfree(attr_s);
attr->nres.data_size = cpu_to_le64(rsize);
attr->nres.valid_size = attr->nres.data_size;
*ins_attr = attr;
if (is_data)
ni->ni_flags &= ~NI_FLAG_RESIDENT;
/* Resident attribute becomes non resident. */
return 0;
out3:
attr = Add2Ptr(rec, aoff);
memmove(next, attr, used - aoff);
memcpy(attr, attr_s, asize);
rec->used = cpu_to_le32(used + asize);
mi->dirty = true;
out2:
/* Undo: do not trim new allocated clusters. */
run_deallocate(sbi, run, false);
run_close(run);
out1:
kfree(attr_s);
out:
return err;
}
/*
* attr_set_size_res - Helper for attr_set_size().
*/
static int attr_set_size_res(struct ntfs_inode *ni, struct ATTRIB *attr,
struct ATTR_LIST_ENTRY *le, struct mft_inode *mi,
u64 new_size, struct runs_tree *run,
struct ATTRIB **ins_attr)
{
struct ntfs_sb_info *sbi = mi->sbi;
struct MFT_REC *rec = mi->mrec;
u32 used = le32_to_cpu(rec->used);
u32 asize = le32_to_cpu(attr->size);
u32 aoff = PtrOffset(rec, attr);
u32 rsize = le32_to_cpu(attr->res.data_size);
u32 tail = used - aoff - asize;
char *next = Add2Ptr(attr, asize);
s64 dsize = ALIGN(new_size, 8) - ALIGN(rsize, 8);
if (dsize < 0) {
memmove(next + dsize, next, tail);
} else if (dsize > 0) {
if (used + dsize > sbi->max_bytes_per_attr)
return attr_make_nonresident(ni, attr, le, mi, new_size,
run, ins_attr, NULL);
memmove(next + dsize, next, tail);
memset(next, 0, dsize);
}
if (new_size > rsize)
memset(Add2Ptr(resident_data(attr), rsize), 0,
new_size - rsize);
rec->used = cpu_to_le32(used + dsize);
attr->size = cpu_to_le32(asize + dsize);
attr->res.data_size = cpu_to_le32(new_size);
mi->dirty = true;
*ins_attr = attr;
return 0;
}
/*
* attr_set_size - Change the size of attribute.
*
* Extend:
* - Sparse/compressed: No allocated clusters.
* - Normal: Append allocated and preallocated new clusters.
* Shrink:
* - No deallocate if @keep_prealloc is set.
*/
int attr_set_size(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, struct runs_tree *run,
u64 new_size, const u64 *new_valid, bool keep_prealloc,
struct ATTRIB **ret)
{
int err = 0;
struct ntfs_sb_info *sbi = ni->mi.sbi;
u8 cluster_bits = sbi->cluster_bits;
bool is_mft = ni->mi.rno == MFT_REC_MFT && type == ATTR_DATA &&
!name_len;
u64 old_valid, old_size, old_alloc, new_alloc, new_alloc_tmp;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST alen, vcn, lcn, new_alen, old_alen, svcn, evcn;
CLST next_svcn, pre_alloc = -1, done = 0;
bool is_ext, is_bad = false;
bool dirty = false;
u32 align;
struct MFT_REC *rec;
again:
alen = 0;
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, type, name, name_len, NULL,
&mi_b);
if (!attr_b) {
err = -ENOENT;
goto bad_inode;
}
if (!attr_b->non_res) {
err = attr_set_size_res(ni, attr_b, le_b, mi_b, new_size, run,
&attr_b);
if (err)
return err;
/* Return if file is still resident. */
if (!attr_b->non_res) {
dirty = true;
goto ok1;
}
/* Layout of records may be changed, so do a full search. */
goto again;
}
is_ext = is_attr_ext(attr_b);
align = sbi->cluster_size;
if (is_ext)
align <<= attr_b->nres.c_unit;
old_valid = le64_to_cpu(attr_b->nres.valid_size);
old_size = le64_to_cpu(attr_b->nres.data_size);
old_alloc = le64_to_cpu(attr_b->nres.alloc_size);
again_1:
old_alen = old_alloc >> cluster_bits;
new_alloc = (new_size + align - 1) & ~(u64)(align - 1);
new_alen = new_alloc >> cluster_bits;
if (keep_prealloc && new_size < old_size) {
attr_b->nres.data_size = cpu_to_le64(new_size);
mi_b->dirty = dirty = true;
goto ok;
}
vcn = old_alen - 1;
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn = le64_to_cpu(attr_b->nres.evcn);
if (svcn <= vcn && vcn <= evcn) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto bad_inode;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, type, name, name_len, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto bad_inode;
}
next_le_1:
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
}
/*
* Here we have:
* attr,mi,le - last attribute segment (containing 'vcn').
* attr_b,mi_b,le_b - base (primary) attribute segment.
*/
next_le:
rec = mi->mrec;
err = attr_load_runs(attr, ni, run, NULL);
if (err)
goto out;
if (new_size > old_size) {
CLST to_allocate;
size_t free;
if (new_alloc <= old_alloc) {
attr_b->nres.data_size = cpu_to_le64(new_size);
mi_b->dirty = dirty = true;
goto ok;
}
/*
* Add clusters. In simple case we have to:
* - allocate space (vcn, lcn, len)
* - update packed run in 'mi'
* - update attr->nres.evcn
* - update attr_b->nres.data_size/attr_b->nres.alloc_size
*/
to_allocate = new_alen - old_alen;
add_alloc_in_same_attr_seg:
lcn = 0;
if (is_mft) {
/* MFT allocates clusters from MFT zone. */
pre_alloc = 0;
} else if (is_ext) {
/* No preallocate for sparse/compress. */
pre_alloc = 0;
} else if (pre_alloc == -1) {
pre_alloc = 0;
if (type == ATTR_DATA && !name_len &&
sbi->options->prealloc) {
pre_alloc = bytes_to_cluster(
sbi, get_pre_allocated(
new_size)) -
new_alen;
}
/* Get the last LCN to allocate from. */
if (old_alen &&
!run_lookup_entry(run, vcn, &lcn, NULL, NULL)) {
lcn = SPARSE_LCN;
}
if (lcn == SPARSE_LCN)
lcn = 0;
else if (lcn)
lcn += 1;
free = wnd_zeroes(&sbi->used.bitmap);
if (to_allocate > free) {
err = -ENOSPC;
goto out;
}
if (pre_alloc && to_allocate + pre_alloc > free)
pre_alloc = 0;
}
vcn = old_alen;
if (is_ext) {
if (!run_add_entry(run, vcn, SPARSE_LCN, to_allocate,
false)) {
err = -ENOMEM;
goto out;
}
alen = to_allocate;
} else {
/* ~3 bytes per fragment. */
err = attr_allocate_clusters(
sbi, run, vcn, lcn, to_allocate, &pre_alloc,
is_mft ? ALLOCATE_MFT : ALLOCATE_DEF, &alen,
is_mft ? 0 :
(sbi->record_size -
le32_to_cpu(rec->used) + 8) /
3 +
1,
NULL, NULL);
if (err)
goto out;
}
done += alen;
vcn += alen;
if (to_allocate > alen)
to_allocate -= alen;
else
to_allocate = 0;
pack_runs:
err = mi_pack_runs(mi, attr, run, vcn - svcn);
if (err)
goto undo_1;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
new_alloc_tmp = (u64)next_svcn << cluster_bits;
attr_b->nres.alloc_size = cpu_to_le64(new_alloc_tmp);
mi_b->dirty = dirty = true;
if (next_svcn >= vcn && !to_allocate) {
/* Normal way. Update attribute and exit. */
attr_b->nres.data_size = cpu_to_le64(new_size);
goto ok;
}
/* At least two MFT to avoid recursive loop. */
if (is_mft && next_svcn == vcn &&
((u64)done << sbi->cluster_bits) >= 2 * sbi->record_size) {
new_size = new_alloc_tmp;
attr_b->nres.data_size = attr_b->nres.alloc_size;
goto ok;
}
if (le32_to_cpu(rec->used) < sbi->record_size) {
old_alen = next_svcn;
evcn = old_alen - 1;
goto add_alloc_in_same_attr_seg;
}
attr_b->nres.data_size = attr_b->nres.alloc_size;
if (new_alloc_tmp < old_valid)
attr_b->nres.valid_size = attr_b->nres.data_size;
if (type == ATTR_LIST) {
err = ni_expand_list(ni);
if (err)
goto undo_2;
if (next_svcn < vcn)
goto pack_runs;
/* Layout of records is changed. */
goto again;
}
if (!ni->attr_list.size) {
err = ni_create_attr_list(ni);
/* In case of error layout of records is not changed. */
if (err)
goto undo_2;
/* Layout of records is changed. */
}
if (next_svcn >= vcn) {
/* This is MFT data, repeat. */
goto again;
}
/* Insert new attribute segment. */
err = ni_insert_nonresident(ni, type, name, name_len, run,
next_svcn, vcn - next_svcn,
attr_b->flags, &attr, &mi, NULL);
/*
* Layout of records maybe changed.
* Find base attribute to update.
*/
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, type, name, name_len,
NULL, &mi_b);
if (!attr_b) {
err = -EINVAL;
goto bad_inode;
}
if (err) {
/* ni_insert_nonresident failed. */
attr = NULL;
goto undo_2;
}
if (!is_mft)
run_truncate_head(run, evcn + 1);
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
/*
* Attribute is in consistency state.
* Save this point to restore to if next steps fail.
*/
old_valid = old_size = old_alloc = (u64)vcn << cluster_bits;
attr_b->nres.valid_size = attr_b->nres.data_size =
attr_b->nres.alloc_size = cpu_to_le64(old_size);
mi_b->dirty = dirty = true;
goto again_1;
}
if (new_size != old_size ||
(new_alloc != old_alloc && !keep_prealloc)) {
/*
* Truncate clusters. In simple case we have to:
* - update packed run in 'mi'
* - update attr->nres.evcn
* - update attr_b->nres.data_size/attr_b->nres.alloc_size
* - mark and trim clusters as free (vcn, lcn, len)
*/
CLST dlen = 0;
vcn = max(svcn, new_alen);
new_alloc_tmp = (u64)vcn << cluster_bits;
if (vcn > svcn) {
err = mi_pack_runs(mi, attr, run, vcn - svcn);
if (err)
goto out;
} else if (le && le->vcn) {
u16 le_sz = le16_to_cpu(le->size);
/*
* NOTE: List entries for one attribute are always
* the same size. We deal with last entry (vcn==0)
* and it is not first in entries array
* (list entry for std attribute always first).
* So it is safe to step back.
*/
mi_remove_attr(NULL, mi, attr);
if (!al_remove_le(ni, le)) {
err = -EINVAL;
goto bad_inode;
}
le = (struct ATTR_LIST_ENTRY *)((u8 *)le - le_sz);
} else {
attr->nres.evcn = cpu_to_le64((u64)vcn - 1);
mi->dirty = true;
}
attr_b->nres.alloc_size = cpu_to_le64(new_alloc_tmp);
if (vcn == new_alen) {
attr_b->nres.data_size = cpu_to_le64(new_size);
if (new_size < old_valid)
attr_b->nres.valid_size =
attr_b->nres.data_size;
} else {
if (new_alloc_tmp <=
le64_to_cpu(attr_b->nres.data_size))
attr_b->nres.data_size =
attr_b->nres.alloc_size;
if (new_alloc_tmp <
le64_to_cpu(attr_b->nres.valid_size))
attr_b->nres.valid_size =
attr_b->nres.alloc_size;
}
mi_b->dirty = dirty = true;
err = run_deallocate_ex(sbi, run, vcn, evcn - vcn + 1, &dlen,
true);
if (err)
goto out;
if (is_ext) {
/* dlen - really deallocated clusters. */
le64_sub_cpu(&attr_b->nres.total_size,
((u64)dlen << cluster_bits));
}
run_truncate(run, vcn);
if (new_alloc_tmp <= new_alloc)
goto ok;
old_size = new_alloc_tmp;
vcn = svcn - 1;
if (le == le_b) {
attr = attr_b;
mi = mi_b;
evcn = svcn - 1;
svcn = 0;
goto next_le;
}
if (le->type != type || le->name_len != name_len ||
memcmp(le_name(le), name, name_len * sizeof(short))) {
err = -EINVAL;
goto bad_inode;
}
err = ni_load_mi(ni, le, &mi);
if (err)
goto out;
attr = mi_find_attr(mi, NULL, type, name, name_len, &le->id);
if (!attr) {
err = -EINVAL;
goto bad_inode;
}
goto next_le_1;
}
ok:
if (new_valid) {
__le64 valid = cpu_to_le64(min(*new_valid, new_size));
if (attr_b->nres.valid_size != valid) {
attr_b->nres.valid_size = valid;
mi_b->dirty = true;
}
}
ok1:
if (ret)
*ret = attr_b;
if (((type == ATTR_DATA && !name_len) ||
(type == ATTR_ALLOC && name == I30_NAME))) {
/* Update inode_set_bytes. */
if (attr_b->non_res) {
new_alloc = le64_to_cpu(attr_b->nres.alloc_size);
if (inode_get_bytes(&ni->vfs_inode) != new_alloc) {
inode_set_bytes(&ni->vfs_inode, new_alloc);
dirty = true;
}
}
/* Don't forget to update duplicate information in parent. */
if (dirty) {
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
mark_inode_dirty(&ni->vfs_inode);
}
}
return 0;
undo_2:
vcn -= alen;
attr_b->nres.data_size = cpu_to_le64(old_size);
attr_b->nres.valid_size = cpu_to_le64(old_valid);
attr_b->nres.alloc_size = cpu_to_le64(old_alloc);
/* Restore 'attr' and 'mi'. */
if (attr)
goto restore_run;
if (le64_to_cpu(attr_b->nres.svcn) <= svcn &&
svcn <= le64_to_cpu(attr_b->nres.evcn)) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto bad_inode;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, type, name, name_len,
&svcn, &mi);
if (!attr)
goto bad_inode;
}
restore_run:
if (mi_pack_runs(mi, attr, run, evcn - svcn + 1))
is_bad = true;
undo_1:
run_deallocate_ex(sbi, run, vcn, alen, NULL, false);
run_truncate(run, vcn);
out:
if (is_bad) {
bad_inode:
_ntfs_bad_inode(&ni->vfs_inode);
}
return err;
}
/*
* attr_data_get_block - Returns 'lcn' and 'len' for given 'vcn'.
*
* @new == NULL means just to get current mapping for 'vcn'
* @new != NULL means allocate real cluster if 'vcn' maps to hole
* @zero - zeroout new allocated clusters
*
* NOTE:
* - @new != NULL is called only for sparsed or compressed attributes.
* - new allocated clusters are zeroed via blkdev_issue_zeroout.
*/
int attr_data_get_block(struct ntfs_inode *ni, CLST vcn, CLST clen, CLST *lcn,
CLST *len, bool *new, bool zero)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
struct ntfs_sb_info *sbi;
u8 cluster_bits;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST hint, svcn, to_alloc, evcn1, next_svcn, asize, end, vcn0, alen;
CLST alloc, evcn;
unsigned fr;
u64 total_size, total_size0;
int step = 0;
if (new)
*new = false;
/* Try to find in cache. */
down_read(&ni->file.run_lock);
if (!run_lookup_entry(run, vcn, lcn, len, NULL))
*len = 0;
up_read(&ni->file.run_lock);
if (*len) {
if (*lcn != SPARSE_LCN || !new)
return 0; /* Fast normal way without allocation. */
else if (clen > *len)
clen = *len;
}
/* No cluster in cache or we need to allocate cluster in hole. */
sbi = ni->mi.sbi;
cluster_bits = sbi->cluster_bits;
ni_lock(ni);
down_write(&ni->file.run_lock);
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL, &mi_b);
if (!attr_b) {
err = -ENOENT;
goto out;
}
if (!attr_b->non_res) {
*lcn = RESIDENT_LCN;
*len = 1;
goto out;
}
asize = le64_to_cpu(attr_b->nres.alloc_size) >> cluster_bits;
if (vcn >= asize) {
if (new) {
err = -EINVAL;
} else {
*len = 1;
*lcn = SPARSE_LCN;
}
goto out;
}
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
attr = attr_b;
le = le_b;
mi = mi_b;
if (le_b && (vcn < svcn || evcn1 <= vcn)) {
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
/* Load in cache actual information. */
err = attr_load_runs(attr, ni, run, NULL);
if (err)
goto out;
if (!*len) {
if (run_lookup_entry(run, vcn, lcn, len, NULL)) {
if (*lcn != SPARSE_LCN || !new)
goto ok; /* Slow normal way without allocation. */
if (clen > *len)
clen = *len;
} else if (!new) {
/* Here we may return -ENOENT.
* In any case caller gets zero length. */
goto ok;
}
}
if (!is_attr_ext(attr_b)) {
/* The code below only for sparsed or compressed attributes. */
err = -EINVAL;
goto out;
}
vcn0 = vcn;
to_alloc = clen;
fr = (sbi->record_size - le32_to_cpu(mi->mrec->used) + 8) / 3 + 1;
/* Allocate frame aligned clusters.
* ntfs.sys usually uses 16 clusters per frame for sparsed or compressed.
* ntfs3 uses 1 cluster per frame for new created sparsed files. */
if (attr_b->nres.c_unit) {
CLST clst_per_frame = 1u << attr_b->nres.c_unit;
CLST cmask = ~(clst_per_frame - 1);
/* Get frame aligned vcn and to_alloc. */
vcn = vcn0 & cmask;
to_alloc = ((vcn0 + clen + clst_per_frame - 1) & cmask) - vcn;
if (fr < clst_per_frame)
fr = clst_per_frame;
zero = true;
/* Check if 'vcn' and 'vcn0' in different attribute segments. */
if (vcn < svcn || evcn1 <= vcn) {
/* Load attribute for truncated vcn. */
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0,
&vcn, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
err = attr_load_runs(attr, ni, run, NULL);
if (err)
goto out;
}
}
if (vcn + to_alloc > asize)
to_alloc = asize - vcn;
/* Get the last LCN to allocate from. */
hint = 0;
if (vcn > evcn1) {
if (!run_add_entry(run, evcn1, SPARSE_LCN, vcn - evcn1,
false)) {
err = -ENOMEM;
goto out;
}
} else if (vcn && !run_lookup_entry(run, vcn - 1, &hint, NULL, NULL)) {
hint = -1;
}
/* Allocate and zeroout new clusters. */
err = attr_allocate_clusters(sbi, run, vcn, hint + 1, to_alloc, NULL,
zero ? ALLOCATE_ZERO : ALLOCATE_DEF, &alen,
fr, lcn, len);
if (err)
goto out;
*new = true;
step = 1;
end = vcn + alen;
/* Save 'total_size0' to restore if error. */
total_size0 = le64_to_cpu(attr_b->nres.total_size);
total_size = total_size0 + ((u64)alen << cluster_bits);
if (vcn != vcn0) {
if (!run_lookup_entry(run, vcn0, lcn, len, NULL)) {
err = -EINVAL;
goto out;
}
if (*lcn == SPARSE_LCN) {
/* Internal error. Should not happened. */
WARN_ON(1);
err = -EINVAL;
goto out;
}
/* Check case when vcn0 + len overlaps new allocated clusters. */
if (vcn0 + *len > end)
*len = end - vcn0;
}
repack:
err = mi_pack_runs(mi, attr, run, max(end, evcn1) - svcn);
if (err)
goto out;
attr_b->nres.total_size = cpu_to_le64(total_size);
inode_set_bytes(&ni->vfs_inode, total_size);
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
mi_b->dirty = true;
mark_inode_dirty(&ni->vfs_inode);
/* Stored [vcn : next_svcn) from [vcn : end). */
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
if (end <= evcn1) {
if (next_svcn == evcn1) {
/* Normal way. Update attribute and exit. */
goto ok;
}
/* Add new segment [next_svcn : evcn1 - next_svcn). */
if (!ni->attr_list.size) {
err = ni_create_attr_list(ni);
if (err)
goto undo1;
/* Layout of records is changed. */
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL,
0, NULL, &mi_b);
if (!attr_b) {
err = -ENOENT;
goto out;
}
attr = attr_b;
le = le_b;
mi = mi_b;
goto repack;
}
}
/*
* The code below may require additional cluster (to extend attribute list)
* and / or one MFT record
* It is too complex to undo operations if -ENOSPC occurs deep inside
* in 'ni_insert_nonresident'.
* Return in advance -ENOSPC here if there are no free cluster and no free MFT.
*/
if (!ntfs_check_for_free_space(sbi, 1, 1)) {
/* Undo step 1. */
err = -ENOSPC;
goto undo1;
}
step = 2;
svcn = evcn1;
/* Estimate next attribute. */
attr = ni_find_attr(ni, attr, &le, ATTR_DATA, NULL, 0, &svcn, &mi);
if (!attr) {
/* Insert new attribute segment. */
goto ins_ext;
}
/* Try to update existed attribute segment. */
alloc = bytes_to_cluster(sbi, le64_to_cpu(attr_b->nres.alloc_size));
evcn = le64_to_cpu(attr->nres.evcn);
if (end < next_svcn)
end = next_svcn;
while (end > evcn) {
/* Remove segment [svcn : evcn). */
mi_remove_attr(NULL, mi, attr);
if (!al_remove_le(ni, le)) {
err = -EINVAL;
goto out;
}
if (evcn + 1 >= alloc) {
/* Last attribute segment. */
evcn1 = evcn + 1;
goto ins_ext;
}
if (ni_load_mi(ni, le, &mi)) {
attr = NULL;
goto out;
}
attr = mi_find_attr(mi, NULL, ATTR_DATA, NULL, 0, &le->id);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
}
if (end < svcn)
end = svcn;
err = attr_load_runs(attr, ni, run, &end);
if (err)
goto out;
evcn1 = evcn + 1;
attr->nres.svcn = cpu_to_le64(next_svcn);
err = mi_pack_runs(mi, attr, run, evcn1 - next_svcn);
if (err)
goto out;
le->vcn = cpu_to_le64(next_svcn);
ni->attr_list.dirty = true;
mi->dirty = true;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
ins_ext:
if (evcn1 > next_svcn) {
err = ni_insert_nonresident(ni, ATTR_DATA, NULL, 0, run,
next_svcn, evcn1 - next_svcn,
attr_b->flags, &attr, &mi, NULL);
if (err)
goto out;
}
ok:
run_truncate_around(run, vcn);
out:
if (err && step > 1) {
/* Too complex to restore. */
_ntfs_bad_inode(&ni->vfs_inode);
}
up_write(&ni->file.run_lock);
ni_unlock(ni);
return err;
undo1:
/* Undo step1. */
attr_b->nres.total_size = cpu_to_le64(total_size0);
inode_set_bytes(&ni->vfs_inode, total_size0);
if (run_deallocate_ex(sbi, run, vcn, alen, NULL, false) ||
!run_add_entry(run, vcn, SPARSE_LCN, alen, false) ||
mi_pack_runs(mi, attr, run, max(end, evcn1) - svcn)) {
_ntfs_bad_inode(&ni->vfs_inode);
}
goto out;
}
int attr_data_read_resident(struct ntfs_inode *ni, struct page *page)
{
u64 vbo;
struct ATTRIB *attr;
u32 data_size;
attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, NULL);
if (!attr)
return -EINVAL;
if (attr->non_res)
return E_NTFS_NONRESIDENT;
vbo = page->index << PAGE_SHIFT;
data_size = le32_to_cpu(attr->res.data_size);
if (vbo < data_size) {
const char *data = resident_data(attr);
char *kaddr = kmap_atomic(page);
u32 use = data_size - vbo;
if (use > PAGE_SIZE)
use = PAGE_SIZE;
memcpy(kaddr, data + vbo, use);
memset(kaddr + use, 0, PAGE_SIZE - use);
kunmap_atomic(kaddr);
flush_dcache_page(page);
SetPageUptodate(page);
} else if (!PageUptodate(page)) {
zero_user_segment(page, 0, PAGE_SIZE);
SetPageUptodate(page);
}
return 0;
}
int attr_data_write_resident(struct ntfs_inode *ni, struct page *page)
{
u64 vbo;
struct mft_inode *mi;
struct ATTRIB *attr;
u32 data_size;
attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, &mi);
if (!attr)
return -EINVAL;
if (attr->non_res) {
/* Return special error code to check this case. */
return E_NTFS_NONRESIDENT;
}
vbo = page->index << PAGE_SHIFT;
data_size = le32_to_cpu(attr->res.data_size);
if (vbo < data_size) {
char *data = resident_data(attr);
char *kaddr = kmap_atomic(page);
u32 use = data_size - vbo;
if (use > PAGE_SIZE)
use = PAGE_SIZE;
memcpy(data + vbo, kaddr, use);
kunmap_atomic(kaddr);
mi->dirty = true;
}
ni->i_valid = data_size;
return 0;
}
/*
* attr_load_runs_vcn - Load runs with VCN.
*/
int attr_load_runs_vcn(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, struct runs_tree *run,
CLST vcn)
{
struct ATTRIB *attr;
int err;
CLST svcn, evcn;
u16 ro;
if (!ni) {
/* Is record corrupted? */
return -ENOENT;
}
attr = ni_find_attr(ni, NULL, NULL, type, name, name_len, &vcn, NULL);
if (!attr) {
/* Is record corrupted? */
return -ENOENT;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
if (evcn < vcn || vcn < svcn) {
/* Is record corrupted? */
return -EINVAL;
}
ro = le16_to_cpu(attr->nres.run_off);
if (ro > le32_to_cpu(attr->size))
return -EINVAL;
err = run_unpack_ex(run, ni->mi.sbi, ni->mi.rno, svcn, evcn, svcn,
Add2Ptr(attr, ro), le32_to_cpu(attr->size) - ro);
if (err < 0)
return err;
return 0;
}
/*
* attr_load_runs_range - Load runs for given range [from to).
*/
int attr_load_runs_range(struct ntfs_inode *ni, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, struct runs_tree *run,
u64 from, u64 to)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
u8 cluster_bits = sbi->cluster_bits;
CLST vcn;
CLST vcn_last = (to - 1) >> cluster_bits;
CLST lcn, clen;
int err;
for (vcn = from >> cluster_bits; vcn <= vcn_last; vcn += clen) {
if (!run_lookup_entry(run, vcn, &lcn, &clen, NULL)) {
err = attr_load_runs_vcn(ni, type, name, name_len, run,
vcn);
if (err)
return err;
clen = 0; /* Next run_lookup_entry(vcn) must be success. */
}
}
return 0;
}
#ifdef CONFIG_NTFS3_LZX_XPRESS
/*
* attr_wof_frame_info
*
* Read header of Xpress/LZX file to get info about frame.
*/
int attr_wof_frame_info(struct ntfs_inode *ni, struct ATTRIB *attr,
struct runs_tree *run, u64 frame, u64 frames,
u8 frame_bits, u32 *ondisk_size, u64 *vbo_data)
{
struct ntfs_sb_info *sbi = ni->mi.sbi;
u64 vbo[2], off[2], wof_size;
u32 voff;
u8 bytes_per_off;
char *addr;
struct page *page;
int i, err;
__le32 *off32;
__le64 *off64;
if (ni->vfs_inode.i_size < 0x100000000ull) {
/* File starts with array of 32 bit offsets. */
bytes_per_off = sizeof(__le32);
vbo[1] = frame << 2;
*vbo_data = frames << 2;
} else {
/* File starts with array of 64 bit offsets. */
bytes_per_off = sizeof(__le64);
vbo[1] = frame << 3;
*vbo_data = frames << 3;
}
/*
* Read 4/8 bytes at [vbo - 4(8)] == offset where compressed frame starts.
* Read 4/8 bytes at [vbo] == offset where compressed frame ends.
*/
if (!attr->non_res) {
if (vbo[1] + bytes_per_off > le32_to_cpu(attr->res.data_size)) {
ntfs_inode_err(&ni->vfs_inode, "is corrupted");
return -EINVAL;
}
addr = resident_data(attr);
if (bytes_per_off == sizeof(__le32)) {
off32 = Add2Ptr(addr, vbo[1]);
off[0] = vbo[1] ? le32_to_cpu(off32[-1]) : 0;
off[1] = le32_to_cpu(off32[0]);
} else {
off64 = Add2Ptr(addr, vbo[1]);
off[0] = vbo[1] ? le64_to_cpu(off64[-1]) : 0;
off[1] = le64_to_cpu(off64[0]);
}
*vbo_data += off[0];
*ondisk_size = off[1] - off[0];
return 0;
}
wof_size = le64_to_cpu(attr->nres.data_size);
down_write(&ni->file.run_lock);
page = ni->file.offs_page;
if (!page) {
page = alloc_page(GFP_KERNEL);
if (!page) {
err = -ENOMEM;
goto out;
}
page->index = -1;
ni->file.offs_page = page;
}
lock_page(page);
addr = page_address(page);
if (vbo[1]) {
voff = vbo[1] & (PAGE_SIZE - 1);
vbo[0] = vbo[1] - bytes_per_off;
i = 0;
} else {
voff = 0;
vbo[0] = 0;
off[0] = 0;
i = 1;
}
do {
pgoff_t index = vbo[i] >> PAGE_SHIFT;
if (index != page->index) {
u64 from = vbo[i] & ~(u64)(PAGE_SIZE - 1);
u64 to = min(from + PAGE_SIZE, wof_size);
err = attr_load_runs_range(ni, ATTR_DATA, WOF_NAME,
ARRAY_SIZE(WOF_NAME), run,
from, to);
if (err)
goto out1;
err = ntfs_bio_pages(sbi, run, &page, 1, from,
to - from, REQ_OP_READ);
if (err) {
page->index = -1;
goto out1;
}
page->index = index;
}
if (i) {
if (bytes_per_off == sizeof(__le32)) {
off32 = Add2Ptr(addr, voff);
off[1] = le32_to_cpu(*off32);
} else {
off64 = Add2Ptr(addr, voff);
off[1] = le64_to_cpu(*off64);
}
} else if (!voff) {
if (bytes_per_off == sizeof(__le32)) {
off32 = Add2Ptr(addr, PAGE_SIZE - sizeof(u32));
off[0] = le32_to_cpu(*off32);
} else {
off64 = Add2Ptr(addr, PAGE_SIZE - sizeof(u64));
off[0] = le64_to_cpu(*off64);
}
} else {
/* Two values in one page. */
if (bytes_per_off == sizeof(__le32)) {
off32 = Add2Ptr(addr, voff);
off[0] = le32_to_cpu(off32[-1]);
off[1] = le32_to_cpu(off32[0]);
} else {
off64 = Add2Ptr(addr, voff);
off[0] = le64_to_cpu(off64[-1]);
off[1] = le64_to_cpu(off64[0]);
}
break;
}
} while (++i < 2);
*vbo_data += off[0];
*ondisk_size = off[1] - off[0];
out1:
unlock_page(page);
out:
up_write(&ni->file.run_lock);
return err;
}
#endif
/*
* attr_is_frame_compressed - Used to detect compressed frame.
*/
int attr_is_frame_compressed(struct ntfs_inode *ni, struct ATTRIB *attr,
CLST frame, CLST *clst_data)
{
int err;
u32 clst_frame;
CLST clen, lcn, vcn, alen, slen, vcn_next;
size_t idx;
struct runs_tree *run;
*clst_data = 0;
if (!is_attr_compressed(attr))
return 0;
if (!attr->non_res)
return 0;
clst_frame = 1u << attr->nres.c_unit;
vcn = frame * clst_frame;
run = &ni->file.run;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
err = attr_load_runs_vcn(ni, attr->type, attr_name(attr),
attr->name_len, run, vcn);
if (err)
return err;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
return -EINVAL;
}
if (lcn == SPARSE_LCN) {
/* Sparsed frame. */
return 0;
}
if (clen >= clst_frame) {
/*
* The frame is not compressed 'cause
* it does not contain any sparse clusters.
*/
*clst_data = clst_frame;
return 0;
}
alen = bytes_to_cluster(ni->mi.sbi, le64_to_cpu(attr->nres.alloc_size));
slen = 0;
*clst_data = clen;
/*
* The frame is compressed if *clst_data + slen >= clst_frame.
* Check next fragments.
*/
while ((vcn += clen) < alen) {
vcn_next = vcn;
if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
vcn_next != vcn) {
err = attr_load_runs_vcn(ni, attr->type,
attr_name(attr),
attr->name_len, run, vcn_next);
if (err)
return err;
vcn = vcn_next;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
return -EINVAL;
}
if (lcn == SPARSE_LCN) {
slen += clen;
} else {
if (slen) {
/*
* Data_clusters + sparse_clusters =
* not enough for frame.
*/
return -EINVAL;
}
*clst_data += clen;
}
if (*clst_data + slen >= clst_frame) {
if (!slen) {
/*
* There is no sparsed clusters in this frame
* so it is not compressed.
*/
*clst_data = clst_frame;
} else {
/* Frame is compressed. */
}
break;
}
}
return 0;
}
/*
* attr_allocate_frame - Allocate/free clusters for @frame.
*
* Assumed: down_write(&ni->file.run_lock);
*/
int attr_allocate_frame(struct ntfs_inode *ni, CLST frame, size_t compr_size,
u64 new_valid)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST svcn, evcn1, next_svcn, len;
CLST vcn, end, clst_data;
u64 total_size, valid_size, data_size;
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL, &mi_b);
if (!attr_b)
return -ENOENT;
if (!is_attr_ext(attr_b))
return -EINVAL;
vcn = frame << NTFS_LZNT_CUNIT;
total_size = le64_to_cpu(attr_b->nres.total_size);
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
data_size = le64_to_cpu(attr_b->nres.data_size);
if (svcn <= vcn && vcn < evcn1) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto out;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
err = attr_load_runs(attr, ni, run, NULL);
if (err)
goto out;
err = attr_is_frame_compressed(ni, attr_b, frame, &clst_data);
if (err)
goto out;
total_size -= (u64)clst_data << sbi->cluster_bits;
len = bytes_to_cluster(sbi, compr_size);
if (len == clst_data)
goto out;
if (len < clst_data) {
err = run_deallocate_ex(sbi, run, vcn + len, clst_data - len,
NULL, true);
if (err)
goto out;
if (!run_add_entry(run, vcn + len, SPARSE_LCN, clst_data - len,
false)) {
err = -ENOMEM;
goto out;
}
end = vcn + clst_data;
/* Run contains updated range [vcn + len : end). */
} else {
CLST alen, hint = 0;
/* Get the last LCN to allocate from. */
if (vcn + clst_data &&
!run_lookup_entry(run, vcn + clst_data - 1, &hint, NULL,
NULL)) {
hint = -1;
}
err = attr_allocate_clusters(sbi, run, vcn + clst_data,
hint + 1, len - clst_data, NULL,
ALLOCATE_DEF, &alen, 0, NULL,
NULL);
if (err)
goto out;
end = vcn + len;
/* Run contains updated range [vcn + clst_data : end). */
}
total_size += (u64)len << sbi->cluster_bits;
repack:
err = mi_pack_runs(mi, attr, run, max(end, evcn1) - svcn);
if (err)
goto out;
attr_b->nres.total_size = cpu_to_le64(total_size);
inode_set_bytes(&ni->vfs_inode, total_size);
mi_b->dirty = true;
mark_inode_dirty(&ni->vfs_inode);
/* Stored [vcn : next_svcn) from [vcn : end). */
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
if (end <= evcn1) {
if (next_svcn == evcn1) {
/* Normal way. Update attribute and exit. */
goto ok;
}
/* Add new segment [next_svcn : evcn1 - next_svcn). */
if (!ni->attr_list.size) {
err = ni_create_attr_list(ni);
if (err)
goto out;
/* Layout of records is changed. */
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL,
0, NULL, &mi_b);
if (!attr_b) {
err = -ENOENT;
goto out;
}
attr = attr_b;
le = le_b;
mi = mi_b;
goto repack;
}
}
svcn = evcn1;
/* Estimate next attribute. */
attr = ni_find_attr(ni, attr, &le, ATTR_DATA, NULL, 0, &svcn, &mi);
if (attr) {
CLST alloc = bytes_to_cluster(
sbi, le64_to_cpu(attr_b->nres.alloc_size));
CLST evcn = le64_to_cpu(attr->nres.evcn);
if (end < next_svcn)
end = next_svcn;
while (end > evcn) {
/* Remove segment [svcn : evcn). */
mi_remove_attr(NULL, mi, attr);
if (!al_remove_le(ni, le)) {
err = -EINVAL;
goto out;
}
if (evcn + 1 >= alloc) {
/* Last attribute segment. */
evcn1 = evcn + 1;
goto ins_ext;
}
if (ni_load_mi(ni, le, &mi)) {
attr = NULL;
goto out;
}
attr = mi_find_attr(mi, NULL, ATTR_DATA, NULL, 0,
&le->id);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn = le64_to_cpu(attr->nres.evcn);
}
if (end < svcn)
end = svcn;
err = attr_load_runs(attr, ni, run, &end);
if (err)
goto out;
evcn1 = evcn + 1;
attr->nres.svcn = cpu_to_le64(next_svcn);
err = mi_pack_runs(mi, attr, run, evcn1 - next_svcn);
if (err)
goto out;
le->vcn = cpu_to_le64(next_svcn);
ni->attr_list.dirty = true;
mi->dirty = true;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
}
ins_ext:
if (evcn1 > next_svcn) {
err = ni_insert_nonresident(ni, ATTR_DATA, NULL, 0, run,
next_svcn, evcn1 - next_svcn,
attr_b->flags, &attr, &mi, NULL);
if (err)
goto out;
}
ok:
run_truncate_around(run, vcn);
out:
if (new_valid > data_size)
new_valid = data_size;
valid_size = le64_to_cpu(attr_b->nres.valid_size);
if (new_valid != valid_size) {
attr_b->nres.valid_size = cpu_to_le64(valid_size);
mi_b->dirty = true;
}
return err;
}
/*
* attr_collapse_range - Collapse range in file.
*/
int attr_collapse_range(struct ntfs_inode *ni, u64 vbo, u64 bytes)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST svcn, evcn1, len, dealloc, alen;
CLST vcn, end;
u64 valid_size, data_size, alloc_size, total_size;
u32 mask;
__le16 a_flags;
if (!bytes)
return 0;
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL, &mi_b);
if (!attr_b)
return -ENOENT;
if (!attr_b->non_res) {
/* Attribute is resident. Nothing to do? */
return 0;
}
data_size = le64_to_cpu(attr_b->nres.data_size);
alloc_size = le64_to_cpu(attr_b->nres.alloc_size);
a_flags = attr_b->flags;
if (is_attr_ext(attr_b)) {
total_size = le64_to_cpu(attr_b->nres.total_size);
mask = (sbi->cluster_size << attr_b->nres.c_unit) - 1;
} else {
total_size = alloc_size;
mask = sbi->cluster_mask;
}
if ((vbo & mask) || (bytes & mask)) {
/* Allow to collapse only cluster aligned ranges. */
return -EINVAL;
}
if (vbo > data_size)
return -EINVAL;
down_write(&ni->file.run_lock);
if (vbo + bytes >= data_size) {
u64 new_valid = min(ni->i_valid, vbo);
/* Simple truncate file at 'vbo'. */
truncate_setsize(&ni->vfs_inode, vbo);
err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run, vbo,
&new_valid, true, NULL);
if (!err && new_valid < ni->i_valid)
ni->i_valid = new_valid;
goto out;
}
/*
* Enumerate all attribute segments and collapse.
*/
alen = alloc_size >> sbi->cluster_bits;
vcn = vbo >> sbi->cluster_bits;
len = bytes >> sbi->cluster_bits;
end = vcn + len;
dealloc = 0;
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
if (svcn <= vcn && vcn < evcn1) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto out;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto out;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
for (;;) {
if (svcn >= end) {
/* Shift VCN- */
attr->nres.svcn = cpu_to_le64(svcn - len);
attr->nres.evcn = cpu_to_le64(evcn1 - 1 - len);
if (le) {
le->vcn = attr->nres.svcn;
ni->attr_list.dirty = true;
}
mi->dirty = true;
} else if (svcn < vcn || end < evcn1) {
CLST vcn1, eat, next_svcn;
/* Collapse a part of this attribute segment. */
err = attr_load_runs(attr, ni, run, &svcn);
if (err)
goto out;
vcn1 = max(vcn, svcn);
eat = min(end, evcn1) - vcn1;
err = run_deallocate_ex(sbi, run, vcn1, eat, &dealloc,
true);
if (err)
goto out;
if (!run_collapse_range(run, vcn1, eat)) {
err = -ENOMEM;
goto out;
}
if (svcn >= vcn) {
/* Shift VCN */
attr->nres.svcn = cpu_to_le64(vcn);
if (le) {
le->vcn = attr->nres.svcn;
ni->attr_list.dirty = true;
}
}
err = mi_pack_runs(mi, attr, run, evcn1 - svcn - eat);
if (err)
goto out;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
if (next_svcn + eat < evcn1) {
err = ni_insert_nonresident(
ni, ATTR_DATA, NULL, 0, run, next_svcn,
evcn1 - eat - next_svcn, a_flags, &attr,
&mi, &le);
if (err)
goto out;
/* Layout of records maybe changed. */
attr_b = NULL;
}
/* Free all allocated memory. */
run_truncate(run, 0);
} else {
u16 le_sz;
u16 roff = le16_to_cpu(attr->nres.run_off);
if (roff > le32_to_cpu(attr->size)) {
err = -EINVAL;
goto out;
}
run_unpack_ex(RUN_DEALLOCATE, sbi, ni->mi.rno, svcn,
evcn1 - 1, svcn, Add2Ptr(attr, roff),
le32_to_cpu(attr->size) - roff);
/* Delete this attribute segment. */
mi_remove_attr(NULL, mi, attr);
if (!le)
break;
le_sz = le16_to_cpu(le->size);
if (!al_remove_le(ni, le)) {
err = -EINVAL;
goto out;
}
if (evcn1 >= alen)
break;
if (!svcn) {
/* Load next record that contains this attribute. */
if (ni_load_mi(ni, le, &mi)) {
err = -EINVAL;
goto out;
}
/* Look for required attribute. */
attr = mi_find_attr(mi, NULL, ATTR_DATA, NULL,
0, &le->id);
if (!attr) {
err = -EINVAL;
goto out;
}
goto next_attr;
}
le = (struct ATTR_LIST_ENTRY *)((u8 *)le - le_sz);
}
if (evcn1 >= alen)
break;
attr = ni_enum_attr_ex(ni, attr, &le, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
next_attr:
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
if (!attr_b) {
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL,
&mi_b);
if (!attr_b) {
err = -ENOENT;
goto out;
}
}
data_size -= bytes;
valid_size = ni->i_valid;
if (vbo + bytes <= valid_size)
valid_size -= bytes;
else if (vbo < valid_size)
valid_size = vbo;
attr_b->nres.alloc_size = cpu_to_le64(alloc_size - bytes);
attr_b->nres.data_size = cpu_to_le64(data_size);
attr_b->nres.valid_size = cpu_to_le64(min(valid_size, data_size));
total_size -= (u64)dealloc << sbi->cluster_bits;
if (is_attr_ext(attr_b))
attr_b->nres.total_size = cpu_to_le64(total_size);
mi_b->dirty = true;
/* Update inode size. */
ni->i_valid = valid_size;
ni->vfs_inode.i_size = data_size;
inode_set_bytes(&ni->vfs_inode, total_size);
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
mark_inode_dirty(&ni->vfs_inode);
out:
up_write(&ni->file.run_lock);
if (err)
_ntfs_bad_inode(&ni->vfs_inode);
return err;
}
/*
* attr_punch_hole
*
* Not for normal files.
*/
int attr_punch_hole(struct ntfs_inode *ni, u64 vbo, u64 bytes, u32 *frame_size)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST svcn, evcn1, vcn, len, end, alen, hole, next_svcn;
u64 total_size, alloc_size;
u32 mask;
__le16 a_flags;
struct runs_tree run2;
if (!bytes)
return 0;
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL, &mi_b);
if (!attr_b)
return -ENOENT;
if (!attr_b->non_res) {
u32 data_size = le32_to_cpu(attr_b->res.data_size);
u32 from, to;
if (vbo > data_size)
return 0;
from = vbo;
to = min_t(u64, vbo + bytes, data_size);
memset(Add2Ptr(resident_data(attr_b), from), 0, to - from);
return 0;
}
if (!is_attr_ext(attr_b))
return -EOPNOTSUPP;
alloc_size = le64_to_cpu(attr_b->nres.alloc_size);
total_size = le64_to_cpu(attr_b->nres.total_size);
if (vbo >= alloc_size) {
/* NOTE: It is allowed. */
return 0;
}
mask = (sbi->cluster_size << attr_b->nres.c_unit) - 1;
bytes += vbo;
if (bytes > alloc_size)
bytes = alloc_size;
bytes -= vbo;
if ((vbo & mask) || (bytes & mask)) {
/* We have to zero a range(s). */
if (frame_size == NULL) {
/* Caller insists range is aligned. */
return -EINVAL;
}
*frame_size = mask + 1;
return E_NTFS_NOTALIGNED;
}
down_write(&ni->file.run_lock);
run_init(&run2);
run_truncate(run, 0);
/*
* Enumerate all attribute segments and punch hole where necessary.
*/
alen = alloc_size >> sbi->cluster_bits;
vcn = vbo >> sbi->cluster_bits;
len = bytes >> sbi->cluster_bits;
end = vcn + len;
hole = 0;
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
a_flags = attr_b->flags;
if (svcn <= vcn && vcn < evcn1) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto bad_inode;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto bad_inode;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
while (svcn < end) {
CLST vcn1, zero, hole2 = hole;
err = attr_load_runs(attr, ni, run, &svcn);
if (err)
goto done;
vcn1 = max(vcn, svcn);
zero = min(end, evcn1) - vcn1;
/*
* Check range [vcn1 + zero).
* Calculate how many clusters there are.
* Don't do any destructive actions.
*/
err = run_deallocate_ex(NULL, run, vcn1, zero, &hole2, false);
if (err)
goto done;
/* Check if required range is already hole. */
if (hole2 == hole)
goto next_attr;
/* Make a clone of run to undo. */
err = run_clone(run, &run2);
if (err)
goto done;
/* Make a hole range (sparse) [vcn1 + zero). */
if (!run_add_entry(run, vcn1, SPARSE_LCN, zero, false)) {
err = -ENOMEM;
goto done;
}
/* Update run in attribute segment. */
err = mi_pack_runs(mi, attr, run, evcn1 - svcn);
if (err)
goto done;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
if (next_svcn < evcn1) {
/* Insert new attribute segment. */
err = ni_insert_nonresident(ni, ATTR_DATA, NULL, 0, run,
next_svcn,
evcn1 - next_svcn, a_flags,
&attr, &mi, &le);
if (err)
goto undo_punch;
/* Layout of records maybe changed. */
attr_b = NULL;
}
/* Real deallocate. Should not fail. */
run_deallocate_ex(sbi, &run2, vcn1, zero, &hole, true);
next_attr:
/* Free all allocated memory. */
run_truncate(run, 0);
if (evcn1 >= alen)
break;
/* Get next attribute segment. */
attr = ni_enum_attr_ex(ni, attr, &le, &mi);
if (!attr) {
err = -EINVAL;
goto bad_inode;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
done:
if (!hole)
goto out;
if (!attr_b) {
attr_b = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL,
&mi_b);
if (!attr_b) {
err = -EINVAL;
goto bad_inode;
}
}
total_size -= (u64)hole << sbi->cluster_bits;
attr_b->nres.total_size = cpu_to_le64(total_size);
mi_b->dirty = true;
/* Update inode size. */
inode_set_bytes(&ni->vfs_inode, total_size);
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
mark_inode_dirty(&ni->vfs_inode);
out:
run_close(&run2);
up_write(&ni->file.run_lock);
return err;
bad_inode:
_ntfs_bad_inode(&ni->vfs_inode);
goto out;
undo_punch:
/*
* Restore packed runs.
* 'mi_pack_runs' should not fail, cause we restore original.
*/
if (mi_pack_runs(mi, attr, &run2, evcn1 - svcn))
goto bad_inode;
goto done;
}
/*
* attr_insert_range - Insert range (hole) in file.
* Not for normal files.
*/
int attr_insert_range(struct ntfs_inode *ni, u64 vbo, u64 bytes)
{
int err = 0;
struct runs_tree *run = &ni->file.run;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct ATTRIB *attr = NULL, *attr_b;
struct ATTR_LIST_ENTRY *le, *le_b;
struct mft_inode *mi, *mi_b;
CLST vcn, svcn, evcn1, len, next_svcn;
u64 data_size, alloc_size;
u32 mask;
__le16 a_flags;
if (!bytes)
return 0;
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL, &mi_b);
if (!attr_b)
return -ENOENT;
if (!is_attr_ext(attr_b)) {
/* It was checked above. See fallocate. */
return -EOPNOTSUPP;
}
if (!attr_b->non_res) {
data_size = le32_to_cpu(attr_b->res.data_size);
alloc_size = data_size;
mask = sbi->cluster_mask; /* cluster_size - 1 */
} else {
data_size = le64_to_cpu(attr_b->nres.data_size);
alloc_size = le64_to_cpu(attr_b->nres.alloc_size);
mask = (sbi->cluster_size << attr_b->nres.c_unit) - 1;
}
if (vbo > data_size) {
/* Insert range after the file size is not allowed. */
return -EINVAL;
}
if ((vbo & mask) || (bytes & mask)) {
/* Allow to insert only frame aligned ranges. */
return -EINVAL;
}
/*
* valid_size <= data_size <= alloc_size
* Check alloc_size for maximum possible.
*/
if (bytes > sbi->maxbytes_sparse - alloc_size)
return -EFBIG;
vcn = vbo >> sbi->cluster_bits;
len = bytes >> sbi->cluster_bits;
down_write(&ni->file.run_lock);
if (!attr_b->non_res) {
err = attr_set_size(ni, ATTR_DATA, NULL, 0, run,
data_size + bytes, NULL, false, NULL);
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL,
&mi_b);
if (!attr_b) {
err = -EINVAL;
goto bad_inode;
}
if (err)
goto out;
if (!attr_b->non_res) {
/* Still resident. */
char *data = Add2Ptr(attr_b,
le16_to_cpu(attr_b->res.data_off));
memmove(data + bytes, data, bytes);
memset(data, 0, bytes);
goto done;
}
/* Resident files becomes nonresident. */
data_size = le64_to_cpu(attr_b->nres.data_size);
alloc_size = le64_to_cpu(attr_b->nres.alloc_size);
}
/*
* Enumerate all attribute segments and shift start vcn.
*/
a_flags = attr_b->flags;
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
if (svcn <= vcn && vcn < evcn1) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
err = -EINVAL;
goto bad_inode;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
err = -EINVAL;
goto bad_inode;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
run_truncate(run, 0); /* clear cached values. */
err = attr_load_runs(attr, ni, run, NULL);
if (err)
goto out;
if (!run_insert_range(run, vcn, len)) {
err = -ENOMEM;
goto out;
}
/* Try to pack in current record as much as possible. */
err = mi_pack_runs(mi, attr, run, evcn1 + len - svcn);
if (err)
goto out;
next_svcn = le64_to_cpu(attr->nres.evcn) + 1;
while ((attr = ni_enum_attr_ex(ni, attr, &le, &mi)) &&
attr->type == ATTR_DATA && !attr->name_len) {
le64_add_cpu(&attr->nres.svcn, len);
le64_add_cpu(&attr->nres.evcn, len);
if (le) {
le->vcn = attr->nres.svcn;
ni->attr_list.dirty = true;
}
mi->dirty = true;
}
if (next_svcn < evcn1 + len) {
err = ni_insert_nonresident(ni, ATTR_DATA, NULL, 0, run,
next_svcn, evcn1 + len - next_svcn,
a_flags, NULL, NULL, NULL);
le_b = NULL;
attr_b = ni_find_attr(ni, NULL, &le_b, ATTR_DATA, NULL, 0, NULL,
&mi_b);
if (!attr_b) {
err = -EINVAL;
goto bad_inode;
}
if (err) {
/* ni_insert_nonresident failed. Try to undo. */
goto undo_insert_range;
}
}
/*
* Update primary attribute segment.
*/
if (vbo <= ni->i_valid)
ni->i_valid += bytes;
attr_b->nres.data_size = cpu_to_le64(data_size + bytes);
attr_b->nres.alloc_size = cpu_to_le64(alloc_size + bytes);
/* ni->valid may be not equal valid_size (temporary). */
if (ni->i_valid > data_size + bytes)
attr_b->nres.valid_size = attr_b->nres.data_size;
else
attr_b->nres.valid_size = cpu_to_le64(ni->i_valid);
mi_b->dirty = true;
done:
ni->vfs_inode.i_size += bytes;
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
mark_inode_dirty(&ni->vfs_inode);
out:
run_truncate(run, 0); /* clear cached values. */
up_write(&ni->file.run_lock);
return err;
bad_inode:
_ntfs_bad_inode(&ni->vfs_inode);
goto out;
undo_insert_range:
svcn = le64_to_cpu(attr_b->nres.svcn);
evcn1 = le64_to_cpu(attr_b->nres.evcn) + 1;
if (svcn <= vcn && vcn < evcn1) {
attr = attr_b;
le = le_b;
mi = mi_b;
} else if (!le_b) {
goto bad_inode;
} else {
le = le_b;
attr = ni_find_attr(ni, attr_b, &le, ATTR_DATA, NULL, 0, &vcn,
&mi);
if (!attr) {
goto bad_inode;
}
svcn = le64_to_cpu(attr->nres.svcn);
evcn1 = le64_to_cpu(attr->nres.evcn) + 1;
}
if (attr_load_runs(attr, ni, run, NULL))
goto bad_inode;
if (!run_collapse_range(run, vcn, len))
goto bad_inode;
if (mi_pack_runs(mi, attr, run, evcn1 + len - svcn))
goto bad_inode;
while ((attr = ni_enum_attr_ex(ni, attr, &le, &mi)) &&
attr->type == ATTR_DATA && !attr->name_len) {
le64_sub_cpu(&attr->nres.svcn, len);
le64_sub_cpu(&attr->nres.evcn, len);
if (le) {
le->vcn = attr->nres.svcn;
ni->attr_list.dirty = true;
}
mi->dirty = true;
}
goto out;
}
| linux-master | fs/ntfs3/attrib.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/fs.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
static inline int compare_attr(const struct ATTRIB *left, enum ATTR_TYPE type,
const __le16 *name, u8 name_len,
const u16 *upcase)
{
/* First, compare the type codes. */
int diff = le32_to_cpu(left->type) - le32_to_cpu(type);
if (diff)
return diff;
/* They have the same type code, so we have to compare the names. */
return ntfs_cmp_names(attr_name(left), left->name_len, name, name_len,
upcase, true);
}
/*
* mi_new_attt_id
*
* Return: Unused attribute id that is less than mrec->next_attr_id.
*/
static __le16 mi_new_attt_id(struct mft_inode *mi)
{
u16 free_id, max_id, t16;
struct MFT_REC *rec = mi->mrec;
struct ATTRIB *attr;
__le16 id;
id = rec->next_attr_id;
free_id = le16_to_cpu(id);
if (free_id < 0x7FFF) {
rec->next_attr_id = cpu_to_le16(free_id + 1);
return id;
}
/* One record can store up to 1024/24 ~= 42 attributes. */
free_id = 0;
max_id = 0;
attr = NULL;
for (;;) {
attr = mi_enum_attr(mi, attr);
if (!attr) {
rec->next_attr_id = cpu_to_le16(max_id + 1);
mi->dirty = true;
return cpu_to_le16(free_id);
}
t16 = le16_to_cpu(attr->id);
if (t16 == free_id) {
free_id += 1;
attr = NULL;
} else if (max_id < t16)
max_id = t16;
}
}
int mi_get(struct ntfs_sb_info *sbi, CLST rno, struct mft_inode **mi)
{
int err;
struct mft_inode *m = kzalloc(sizeof(struct mft_inode), GFP_NOFS);
if (!m)
return -ENOMEM;
err = mi_init(m, sbi, rno);
if (err) {
kfree(m);
return err;
}
err = mi_read(m, false);
if (err) {
mi_put(m);
return err;
}
*mi = m;
return 0;
}
void mi_put(struct mft_inode *mi)
{
mi_clear(mi);
kfree(mi);
}
int mi_init(struct mft_inode *mi, struct ntfs_sb_info *sbi, CLST rno)
{
mi->sbi = sbi;
mi->rno = rno;
mi->mrec = kmalloc(sbi->record_size, GFP_NOFS);
if (!mi->mrec)
return -ENOMEM;
return 0;
}
/*
* mi_read - Read MFT data.
*/
int mi_read(struct mft_inode *mi, bool is_mft)
{
int err;
struct MFT_REC *rec = mi->mrec;
struct ntfs_sb_info *sbi = mi->sbi;
u32 bpr = sbi->record_size;
u64 vbo = (u64)mi->rno << sbi->record_bits;
struct ntfs_inode *mft_ni = sbi->mft.ni;
struct runs_tree *run = mft_ni ? &mft_ni->file.run : NULL;
struct rw_semaphore *rw_lock = NULL;
if (is_mounted(sbi)) {
if (!is_mft && mft_ni) {
rw_lock = &mft_ni->file.run_lock;
down_read(rw_lock);
}
}
err = ntfs_read_bh(sbi, run, vbo, &rec->rhdr, bpr, &mi->nb);
if (rw_lock)
up_read(rw_lock);
if (!err)
goto ok;
if (err == -E_NTFS_FIXUP) {
mi->dirty = true;
goto ok;
}
if (err != -ENOENT)
goto out;
if (rw_lock) {
ni_lock(mft_ni);
down_write(rw_lock);
}
err = attr_load_runs_vcn(mft_ni, ATTR_DATA, NULL, 0, run,
vbo >> sbi->cluster_bits);
if (rw_lock) {
up_write(rw_lock);
ni_unlock(mft_ni);
}
if (err)
goto out;
if (rw_lock)
down_read(rw_lock);
err = ntfs_read_bh(sbi, run, vbo, &rec->rhdr, bpr, &mi->nb);
if (rw_lock)
up_read(rw_lock);
if (err == -E_NTFS_FIXUP) {
mi->dirty = true;
goto ok;
}
if (err)
goto out;
ok:
/* Check field 'total' only here. */
if (le32_to_cpu(rec->total) != bpr) {
err = -EINVAL;
goto out;
}
return 0;
out:
if (err == -E_NTFS_CORRUPT) {
ntfs_err(sbi->sb, "mft corrupted");
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
err = -EINVAL;
}
return err;
}
struct ATTRIB *mi_enum_attr(struct mft_inode *mi, struct ATTRIB *attr)
{
const struct MFT_REC *rec = mi->mrec;
u32 used = le32_to_cpu(rec->used);
u32 t32, off, asize;
u16 t16;
if (!attr) {
u32 total = le32_to_cpu(rec->total);
off = le16_to_cpu(rec->attr_off);
if (used > total)
return NULL;
if (off >= used || off < MFTRECORD_FIXUP_OFFSET_1 ||
!IS_ALIGNED(off, 4)) {
return NULL;
}
/* Skip non-resident records. */
if (!is_rec_inuse(rec))
return NULL;
attr = Add2Ptr(rec, off);
} else {
/* Check if input attr inside record. */
off = PtrOffset(rec, attr);
if (off >= used)
return NULL;
asize = le32_to_cpu(attr->size);
if (asize < SIZEOF_RESIDENT) {
/* Impossible 'cause we should not return such attribute. */
return NULL;
}
if (off + asize < off) {
/* Overflow check. */
return NULL;
}
attr = Add2Ptr(attr, asize);
off += asize;
}
asize = le32_to_cpu(attr->size);
/* Can we use the first field (attr->type). */
if (off + 8 > used) {
static_assert(ALIGN(sizeof(enum ATTR_TYPE), 8) == 8);
return NULL;
}
if (attr->type == ATTR_END) {
/* End of enumeration. */
return NULL;
}
/* 0x100 is last known attribute for now. */
t32 = le32_to_cpu(attr->type);
if ((t32 & 0xf) || (t32 > 0x100))
return NULL;
/* Check overflow and boundary. */
if (off + asize < off || off + asize > used)
return NULL;
/* Check size of attribute. */
if (!attr->non_res) {
if (asize < SIZEOF_RESIDENT)
return NULL;
t16 = le16_to_cpu(attr->res.data_off);
if (t16 > asize)
return NULL;
t32 = le32_to_cpu(attr->res.data_size);
if (t16 + t32 > asize)
return NULL;
t32 = sizeof(short) * attr->name_len;
if (t32 && le16_to_cpu(attr->name_off) + t32 > t16)
return NULL;
return attr;
}
/* Check some nonresident fields. */
if (attr->name_len &&
le16_to_cpu(attr->name_off) + sizeof(short) * attr->name_len >
le16_to_cpu(attr->nres.run_off)) {
return NULL;
}
if (attr->nres.svcn || !is_attr_ext(attr)) {
if (asize + 8 < SIZEOF_NONRESIDENT)
return NULL;
if (attr->nres.c_unit)
return NULL;
} else if (asize + 8 < SIZEOF_NONRESIDENT_EX)
return NULL;
return attr;
}
/*
* mi_find_attr - Find the attribute by type and name and id.
*/
struct ATTRIB *mi_find_attr(struct mft_inode *mi, struct ATTRIB *attr,
enum ATTR_TYPE type, const __le16 *name,
u8 name_len, const __le16 *id)
{
u32 type_in = le32_to_cpu(type);
u32 atype;
next_attr:
attr = mi_enum_attr(mi, attr);
if (!attr)
return NULL;
atype = le32_to_cpu(attr->type);
if (atype > type_in)
return NULL;
if (atype < type_in)
goto next_attr;
if (attr->name_len != name_len)
goto next_attr;
if (name_len && memcmp(attr_name(attr), name, name_len * sizeof(short)))
goto next_attr;
if (id && *id != attr->id)
goto next_attr;
return attr;
}
int mi_write(struct mft_inode *mi, int wait)
{
struct MFT_REC *rec;
int err;
struct ntfs_sb_info *sbi;
if (!mi->dirty)
return 0;
sbi = mi->sbi;
rec = mi->mrec;
err = ntfs_write_bh(sbi, &rec->rhdr, &mi->nb, wait);
if (err)
return err;
if (mi->rno < sbi->mft.recs_mirr)
sbi->flags |= NTFS_FLAGS_MFTMIRR;
mi->dirty = false;
return 0;
}
int mi_format_new(struct mft_inode *mi, struct ntfs_sb_info *sbi, CLST rno,
__le16 flags, bool is_mft)
{
int err;
u16 seq = 1;
struct MFT_REC *rec;
u64 vbo = (u64)rno << sbi->record_bits;
err = mi_init(mi, sbi, rno);
if (err)
return err;
rec = mi->mrec;
if (rno == MFT_REC_MFT) {
;
} else if (rno < MFT_REC_FREE) {
seq = rno;
} else if (rno >= sbi->mft.used) {
;
} else if (mi_read(mi, is_mft)) {
;
} else if (rec->rhdr.sign == NTFS_FILE_SIGNATURE) {
/* Record is reused. Update its sequence number. */
seq = le16_to_cpu(rec->seq) + 1;
if (!seq)
seq = 1;
}
memcpy(rec, sbi->new_rec, sbi->record_size);
rec->seq = cpu_to_le16(seq);
rec->flags = RECORD_FLAG_IN_USE | flags;
if (MFTRECORD_FIXUP_OFFSET == MFTRECORD_FIXUP_OFFSET_3)
rec->mft_record = cpu_to_le32(rno);
mi->dirty = true;
if (!mi->nb.nbufs) {
struct ntfs_inode *ni = sbi->mft.ni;
bool lock = false;
if (is_mounted(sbi) && !is_mft) {
down_read(&ni->file.run_lock);
lock = true;
}
err = ntfs_get_bh(sbi, &ni->file.run, vbo, sbi->record_size,
&mi->nb);
if (lock)
up_read(&ni->file.run_lock);
}
return err;
}
/*
* mi_insert_attr - Reserve space for new attribute.
*
* Return: Not full constructed attribute or NULL if not possible to create.
*/
struct ATTRIB *mi_insert_attr(struct mft_inode *mi, enum ATTR_TYPE type,
const __le16 *name, u8 name_len, u32 asize,
u16 name_off)
{
size_t tail;
struct ATTRIB *attr;
__le16 id;
struct MFT_REC *rec = mi->mrec;
struct ntfs_sb_info *sbi = mi->sbi;
u32 used = le32_to_cpu(rec->used);
const u16 *upcase = sbi->upcase;
/* Can we insert mi attribute? */
if (used + asize > sbi->record_size)
return NULL;
/*
* Scan through the list of attributes to find the point
* at which we should insert it.
*/
attr = NULL;
while ((attr = mi_enum_attr(mi, attr))) {
int diff = compare_attr(attr, type, name, name_len, upcase);
if (diff < 0)
continue;
if (!diff && !is_attr_indexed(attr))
return NULL;
break;
}
if (!attr) {
/* Append. */
tail = 8;
attr = Add2Ptr(rec, used - 8);
} else {
/* Insert before 'attr'. */
tail = used - PtrOffset(rec, attr);
}
id = mi_new_attt_id(mi);
memmove(Add2Ptr(attr, asize), attr, tail);
memset(attr, 0, asize);
attr->type = type;
attr->size = cpu_to_le32(asize);
attr->name_len = name_len;
attr->name_off = cpu_to_le16(name_off);
attr->id = id;
memmove(Add2Ptr(attr, name_off), name, name_len * sizeof(short));
rec->used = cpu_to_le32(used + asize);
mi->dirty = true;
return attr;
}
/*
* mi_remove_attr - Remove the attribute from record.
*
* NOTE: The source attr will point to next attribute.
*/
bool mi_remove_attr(struct ntfs_inode *ni, struct mft_inode *mi,
struct ATTRIB *attr)
{
struct MFT_REC *rec = mi->mrec;
u32 aoff = PtrOffset(rec, attr);
u32 used = le32_to_cpu(rec->used);
u32 asize = le32_to_cpu(attr->size);
if (aoff + asize > used)
return false;
if (ni && is_attr_indexed(attr)) {
le16_add_cpu(&ni->mi.mrec->hard_links, -1);
ni->mi.dirty = true;
}
used -= asize;
memmove(attr, Add2Ptr(attr, asize), used - aoff);
rec->used = cpu_to_le32(used);
mi->dirty = true;
return true;
}
/* bytes = "new attribute size" - "old attribute size" */
bool mi_resize_attr(struct mft_inode *mi, struct ATTRIB *attr, int bytes)
{
struct MFT_REC *rec = mi->mrec;
u32 aoff = PtrOffset(rec, attr);
u32 total, used = le32_to_cpu(rec->used);
u32 nsize, asize = le32_to_cpu(attr->size);
u32 rsize = le32_to_cpu(attr->res.data_size);
int tail = (int)(used - aoff - asize);
int dsize;
char *next;
if (tail < 0 || aoff >= used)
return false;
if (!bytes)
return true;
total = le32_to_cpu(rec->total);
next = Add2Ptr(attr, asize);
if (bytes > 0) {
dsize = ALIGN(bytes, 8);
if (used + dsize > total)
return false;
nsize = asize + dsize;
/* Move tail */
memmove(next + dsize, next, tail);
memset(next, 0, dsize);
used += dsize;
rsize += dsize;
} else {
dsize = ALIGN(-bytes, 8);
if (dsize > asize)
return false;
nsize = asize - dsize;
memmove(next - dsize, next, tail);
used -= dsize;
rsize -= dsize;
}
rec->used = cpu_to_le32(used);
attr->size = cpu_to_le32(nsize);
if (!attr->non_res)
attr->res.data_size = cpu_to_le32(rsize);
mi->dirty = true;
return true;
}
/*
* Pack runs in MFT record.
* If failed record is not changed.
*/
int mi_pack_runs(struct mft_inode *mi, struct ATTRIB *attr,
struct runs_tree *run, CLST len)
{
int err = 0;
struct ntfs_sb_info *sbi = mi->sbi;
u32 new_run_size;
CLST plen;
struct MFT_REC *rec = mi->mrec;
CLST svcn = le64_to_cpu(attr->nres.svcn);
u32 used = le32_to_cpu(rec->used);
u32 aoff = PtrOffset(rec, attr);
u32 asize = le32_to_cpu(attr->size);
char *next = Add2Ptr(attr, asize);
u16 run_off = le16_to_cpu(attr->nres.run_off);
u32 run_size = asize - run_off;
u32 tail = used - aoff - asize;
u32 dsize = sbi->record_size - used;
/* Make a maximum gap in current record. */
memmove(next + dsize, next, tail);
/* Pack as much as possible. */
err = run_pack(run, svcn, len, Add2Ptr(attr, run_off), run_size + dsize,
&plen);
if (err < 0) {
memmove(next, next + dsize, tail);
return err;
}
new_run_size = ALIGN(err, 8);
memmove(next + new_run_size - run_size, next + dsize, tail);
attr->size = cpu_to_le32(asize + new_run_size - run_size);
attr->nres.evcn = cpu_to_le64(svcn + plen - 1);
rec->used = cpu_to_le32(used + new_run_size - run_size);
mi->dirty = true;
return 0;
}
| linux-master | fs/ntfs3/record.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/nls.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
// clang-format off
const struct cpu_str NAME_MFT = {
4, 0, { '$', 'M', 'F', 'T' },
};
const struct cpu_str NAME_MIRROR = {
8, 0, { '$', 'M', 'F', 'T', 'M', 'i', 'r', 'r' },
};
const struct cpu_str NAME_LOGFILE = {
8, 0, { '$', 'L', 'o', 'g', 'F', 'i', 'l', 'e' },
};
const struct cpu_str NAME_VOLUME = {
7, 0, { '$', 'V', 'o', 'l', 'u', 'm', 'e' },
};
const struct cpu_str NAME_ATTRDEF = {
8, 0, { '$', 'A', 't', 't', 'r', 'D', 'e', 'f' },
};
const struct cpu_str NAME_ROOT = {
1, 0, { '.' },
};
const struct cpu_str NAME_BITMAP = {
7, 0, { '$', 'B', 'i', 't', 'm', 'a', 'p' },
};
const struct cpu_str NAME_BOOT = {
5, 0, { '$', 'B', 'o', 'o', 't' },
};
const struct cpu_str NAME_BADCLUS = {
8, 0, { '$', 'B', 'a', 'd', 'C', 'l', 'u', 's' },
};
const struct cpu_str NAME_QUOTA = {
6, 0, { '$', 'Q', 'u', 'o', 't', 'a' },
};
const struct cpu_str NAME_SECURE = {
7, 0, { '$', 'S', 'e', 'c', 'u', 'r', 'e' },
};
const struct cpu_str NAME_UPCASE = {
7, 0, { '$', 'U', 'p', 'C', 'a', 's', 'e' },
};
const struct cpu_str NAME_EXTEND = {
7, 0, { '$', 'E', 'x', 't', 'e', 'n', 'd' },
};
const struct cpu_str NAME_OBJID = {
6, 0, { '$', 'O', 'b', 'j', 'I', 'd' },
};
const struct cpu_str NAME_REPARSE = {
8, 0, { '$', 'R', 'e', 'p', 'a', 'r', 's', 'e' },
};
const struct cpu_str NAME_USNJRNL = {
8, 0, { '$', 'U', 's', 'n', 'J', 'r', 'n', 'l' },
};
const __le16 BAD_NAME[4] = {
cpu_to_le16('$'), cpu_to_le16('B'), cpu_to_le16('a'), cpu_to_le16('d'),
};
const __le16 I30_NAME[4] = {
cpu_to_le16('$'), cpu_to_le16('I'), cpu_to_le16('3'), cpu_to_le16('0'),
};
const __le16 SII_NAME[4] = {
cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('I'), cpu_to_le16('I'),
};
const __le16 SDH_NAME[4] = {
cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('H'),
};
const __le16 SDS_NAME[4] = {
cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('S'),
};
const __le16 SO_NAME[2] = {
cpu_to_le16('$'), cpu_to_le16('O'),
};
const __le16 SQ_NAME[2] = {
cpu_to_le16('$'), cpu_to_le16('Q'),
};
const __le16 SR_NAME[2] = {
cpu_to_le16('$'), cpu_to_le16('R'),
};
#ifdef CONFIG_NTFS3_LZX_XPRESS
const __le16 WOF_NAME[17] = {
cpu_to_le16('W'), cpu_to_le16('o'), cpu_to_le16('f'), cpu_to_le16('C'),
cpu_to_le16('o'), cpu_to_le16('m'), cpu_to_le16('p'), cpu_to_le16('r'),
cpu_to_le16('e'), cpu_to_le16('s'), cpu_to_le16('s'), cpu_to_le16('e'),
cpu_to_le16('d'), cpu_to_le16('D'), cpu_to_le16('a'), cpu_to_le16('t'),
cpu_to_le16('a'),
};
#endif
static const __le16 CON_NAME[3] = {
cpu_to_le16('C'), cpu_to_le16('O'), cpu_to_le16('N'),
};
static const __le16 NUL_NAME[3] = {
cpu_to_le16('N'), cpu_to_le16('U'), cpu_to_le16('L'),
};
static const __le16 AUX_NAME[3] = {
cpu_to_le16('A'), cpu_to_le16('U'), cpu_to_le16('X'),
};
static const __le16 PRN_NAME[3] = {
cpu_to_le16('P'), cpu_to_le16('R'), cpu_to_le16('N'),
};
static const __le16 COM_NAME[3] = {
cpu_to_le16('C'), cpu_to_le16('O'), cpu_to_le16('M'),
};
static const __le16 LPT_NAME[3] = {
cpu_to_le16('L'), cpu_to_le16('P'), cpu_to_le16('T'),
};
// clang-format on
/*
* ntfs_fix_pre_write - Insert fixups into @rhdr before writing to disk.
*/
bool ntfs_fix_pre_write(struct NTFS_RECORD_HEADER *rhdr, size_t bytes)
{
u16 *fixup, *ptr;
u16 sample;
u16 fo = le16_to_cpu(rhdr->fix_off);
u16 fn = le16_to_cpu(rhdr->fix_num);
if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
fn * SECTOR_SIZE > bytes) {
return false;
}
/* Get fixup pointer. */
fixup = Add2Ptr(rhdr, fo);
if (*fixup >= 0x7FFF)
*fixup = 1;
else
*fixup += 1;
sample = *fixup;
ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
while (fn--) {
*++fixup = *ptr;
*ptr = sample;
ptr += SECTOR_SIZE / sizeof(short);
}
return true;
}
/*
* ntfs_fix_post_read - Remove fixups after reading from disk.
*
* Return: < 0 if error, 0 if ok, 1 if need to update fixups.
*/
int ntfs_fix_post_read(struct NTFS_RECORD_HEADER *rhdr, size_t bytes,
bool simple)
{
int ret;
u16 *fixup, *ptr;
u16 sample, fo, fn;
fo = le16_to_cpu(rhdr->fix_off);
fn = simple ? ((bytes >> SECTOR_SHIFT) + 1) :
le16_to_cpu(rhdr->fix_num);
/* Check errors. */
if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
fn * SECTOR_SIZE > bytes) {
return -E_NTFS_CORRUPT;
}
/* Get fixup pointer. */
fixup = Add2Ptr(rhdr, fo);
sample = *fixup;
ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
ret = 0;
while (fn--) {
/* Test current word. */
if (*ptr != sample) {
/* Fixup does not match! Is it serious error? */
ret = -E_NTFS_FIXUP;
}
/* Replace fixup. */
*ptr = *++fixup;
ptr += SECTOR_SIZE / sizeof(short);
}
return ret;
}
/*
* ntfs_extend_init - Load $Extend file.
*/
int ntfs_extend_init(struct ntfs_sb_info *sbi)
{
int err;
struct super_block *sb = sbi->sb;
struct inode *inode, *inode2;
struct MFT_REF ref;
if (sbi->volume.major_ver < 3) {
ntfs_notice(sb, "Skip $Extend 'cause NTFS version");
return 0;
}
ref.low = cpu_to_le32(MFT_REC_EXTEND);
ref.high = 0;
ref.seq = cpu_to_le16(MFT_REC_EXTEND);
inode = ntfs_iget5(sb, &ref, &NAME_EXTEND);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $Extend (%d).", err);
inode = NULL;
goto out;
}
/* If ntfs_iget5() reads from disk it never returns bad inode. */
if (!S_ISDIR(inode->i_mode)) {
err = -EINVAL;
goto out;
}
/* Try to find $ObjId */
inode2 = dir_search_u(inode, &NAME_OBJID, NULL);
if (inode2 && !IS_ERR(inode2)) {
if (is_bad_inode(inode2)) {
iput(inode2);
} else {
sbi->objid.ni = ntfs_i(inode2);
sbi->objid_no = inode2->i_ino;
}
}
/* Try to find $Quota */
inode2 = dir_search_u(inode, &NAME_QUOTA, NULL);
if (inode2 && !IS_ERR(inode2)) {
sbi->quota_no = inode2->i_ino;
iput(inode2);
}
/* Try to find $Reparse */
inode2 = dir_search_u(inode, &NAME_REPARSE, NULL);
if (inode2 && !IS_ERR(inode2)) {
sbi->reparse.ni = ntfs_i(inode2);
sbi->reparse_no = inode2->i_ino;
}
/* Try to find $UsnJrnl */
inode2 = dir_search_u(inode, &NAME_USNJRNL, NULL);
if (inode2 && !IS_ERR(inode2)) {
sbi->usn_jrnl_no = inode2->i_ino;
iput(inode2);
}
err = 0;
out:
iput(inode);
return err;
}
int ntfs_loadlog_and_replay(struct ntfs_inode *ni, struct ntfs_sb_info *sbi)
{
int err = 0;
struct super_block *sb = sbi->sb;
bool initialized = false;
struct MFT_REF ref;
struct inode *inode;
/* Check for 4GB. */
if (ni->vfs_inode.i_size >= 0x100000000ull) {
ntfs_err(sb, "\x24LogFile is large than 4G.");
err = -EINVAL;
goto out;
}
sbi->flags |= NTFS_FLAGS_LOG_REPLAYING;
ref.low = cpu_to_le32(MFT_REC_MFT);
ref.high = 0;
ref.seq = cpu_to_le16(1);
inode = ntfs_iget5(sb, &ref, NULL);
if (IS_ERR(inode))
inode = NULL;
if (!inode) {
/* Try to use MFT copy. */
u64 t64 = sbi->mft.lbo;
sbi->mft.lbo = sbi->mft.lbo2;
inode = ntfs_iget5(sb, &ref, NULL);
sbi->mft.lbo = t64;
if (IS_ERR(inode))
inode = NULL;
}
if (!inode) {
err = -EINVAL;
ntfs_err(sb, "Failed to load $MFT.");
goto out;
}
sbi->mft.ni = ntfs_i(inode);
/* LogFile should not contains attribute list. */
err = ni_load_all_mi(sbi->mft.ni);
if (!err)
err = log_replay(ni, &initialized);
iput(inode);
sbi->mft.ni = NULL;
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->flags & NTFS_FLAGS_NEED_REPLAY) {
err = 0;
goto out;
}
if (sb_rdonly(sb) || !initialized)
goto out;
/* Fill LogFile by '-1' if it is initialized. */
err = ntfs_bio_fill_1(sbi, &ni->file.run);
out:
sbi->flags &= ~NTFS_FLAGS_LOG_REPLAYING;
return err;
}
/*
* ntfs_look_for_free_space - Look for a free space in bitmap.
*/
int ntfs_look_for_free_space(struct ntfs_sb_info *sbi, CLST lcn, CLST len,
CLST *new_lcn, CLST *new_len,
enum ALLOCATE_OPT opt)
{
int err;
CLST alen;
struct super_block *sb = sbi->sb;
size_t alcn, zlen, zeroes, zlcn, zlen2, ztrim, new_zlen;
struct wnd_bitmap *wnd = &sbi->used.bitmap;
down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
if (opt & ALLOCATE_MFT) {
zlen = wnd_zone_len(wnd);
if (!zlen) {
err = ntfs_refresh_zone(sbi);
if (err)
goto up_write;
zlen = wnd_zone_len(wnd);
}
if (!zlen) {
ntfs_err(sbi->sb, "no free space to extend mft");
err = -ENOSPC;
goto up_write;
}
lcn = wnd_zone_bit(wnd);
alen = min_t(CLST, len, zlen);
wnd_zone_set(wnd, lcn + alen, zlen - alen);
err = wnd_set_used(wnd, lcn, alen);
if (err)
goto up_write;
alcn = lcn;
goto space_found;
}
/*
* 'Cause cluster 0 is always used this value means that we should use
* cached value of 'next_free_lcn' to improve performance.
*/
if (!lcn)
lcn = sbi->used.next_free_lcn;
if (lcn >= wnd->nbits)
lcn = 0;
alen = wnd_find(wnd, len, lcn, BITMAP_FIND_MARK_AS_USED, &alcn);
if (alen)
goto space_found;
/* Try to use clusters from MftZone. */
zlen = wnd_zone_len(wnd);
zeroes = wnd_zeroes(wnd);
/* Check too big request */
if (len > zeroes + zlen || zlen <= NTFS_MIN_MFT_ZONE) {
err = -ENOSPC;
goto up_write;
}
/* How many clusters to cat from zone. */
zlcn = wnd_zone_bit(wnd);
zlen2 = zlen >> 1;
ztrim = clamp_val(len, zlen2, zlen);
new_zlen = max_t(size_t, zlen - ztrim, NTFS_MIN_MFT_ZONE);
wnd_zone_set(wnd, zlcn, new_zlen);
/* Allocate continues clusters. */
alen = wnd_find(wnd, len, 0,
BITMAP_FIND_MARK_AS_USED | BITMAP_FIND_FULL, &alcn);
if (!alen) {
err = -ENOSPC;
goto up_write;
}
space_found:
err = 0;
*new_len = alen;
*new_lcn = alcn;
ntfs_unmap_meta(sb, alcn, alen);
/* Set hint for next requests. */
if (!(opt & ALLOCATE_MFT))
sbi->used.next_free_lcn = alcn + alen;
up_write:
up_write(&wnd->rw_lock);
return err;
}
/*
* ntfs_check_for_free_space
*
* Check if it is possible to allocate 'clen' clusters and 'mlen' Mft records
*/
bool ntfs_check_for_free_space(struct ntfs_sb_info *sbi, CLST clen, CLST mlen)
{
size_t free, zlen, avail;
struct wnd_bitmap *wnd;
wnd = &sbi->used.bitmap;
down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
free = wnd_zeroes(wnd);
zlen = min_t(size_t, NTFS_MIN_MFT_ZONE, wnd_zone_len(wnd));
up_read(&wnd->rw_lock);
if (free < zlen + clen)
return false;
avail = free - (zlen + clen);
wnd = &sbi->mft.bitmap;
down_read_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
free = wnd_zeroes(wnd);
zlen = wnd_zone_len(wnd);
up_read(&wnd->rw_lock);
if (free >= zlen + mlen)
return true;
return avail >= bytes_to_cluster(sbi, mlen << sbi->record_bits);
}
/*
* ntfs_extend_mft - Allocate additional MFT records.
*
* sbi->mft.bitmap is locked for write.
*
* NOTE: recursive:
* ntfs_look_free_mft ->
* ntfs_extend_mft ->
* attr_set_size ->
* ni_insert_nonresident ->
* ni_insert_attr ->
* ni_ins_attr_ext ->
* ntfs_look_free_mft ->
* ntfs_extend_mft
*
* To avoid recursive always allocate space for two new MFT records
* see attrib.c: "at least two MFT to avoid recursive loop".
*/
static int ntfs_extend_mft(struct ntfs_sb_info *sbi)
{
int err;
struct ntfs_inode *ni = sbi->mft.ni;
size_t new_mft_total;
u64 new_mft_bytes, new_bitmap_bytes;
struct ATTRIB *attr;
struct wnd_bitmap *wnd = &sbi->mft.bitmap;
new_mft_total = ALIGN(wnd->nbits + NTFS_MFT_INCREASE_STEP, 128);
new_mft_bytes = (u64)new_mft_total << sbi->record_bits;
/* Step 1: Resize $MFT::DATA. */
down_write(&ni->file.run_lock);
err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run,
new_mft_bytes, NULL, false, &attr);
if (err) {
up_write(&ni->file.run_lock);
goto out;
}
attr->nres.valid_size = attr->nres.data_size;
new_mft_total = le64_to_cpu(attr->nres.alloc_size) >> sbi->record_bits;
ni->mi.dirty = true;
/* Step 2: Resize $MFT::BITMAP. */
new_bitmap_bytes = bitmap_size(new_mft_total);
err = attr_set_size(ni, ATTR_BITMAP, NULL, 0, &sbi->mft.bitmap.run,
new_bitmap_bytes, &new_bitmap_bytes, true, NULL);
/* Refresh MFT Zone if necessary. */
down_write_nested(&sbi->used.bitmap.rw_lock, BITMAP_MUTEX_CLUSTERS);
ntfs_refresh_zone(sbi);
up_write(&sbi->used.bitmap.rw_lock);
up_write(&ni->file.run_lock);
if (err)
goto out;
err = wnd_extend(wnd, new_mft_total);
if (err)
goto out;
ntfs_clear_mft_tail(sbi, sbi->mft.used, new_mft_total);
err = _ni_write_inode(&ni->vfs_inode, 0);
out:
return err;
}
/*
* ntfs_look_free_mft - Look for a free MFT record.
*/
int ntfs_look_free_mft(struct ntfs_sb_info *sbi, CLST *rno, bool mft,
struct ntfs_inode *ni, struct mft_inode **mi)
{
int err = 0;
size_t zbit, zlen, from, to, fr;
size_t mft_total;
struct MFT_REF ref;
struct super_block *sb = sbi->sb;
struct wnd_bitmap *wnd = &sbi->mft.bitmap;
u32 ir;
static_assert(sizeof(sbi->mft.reserved_bitmap) * 8 >=
MFT_REC_FREE - MFT_REC_RESERVED);
if (!mft)
down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
zlen = wnd_zone_len(wnd);
/* Always reserve space for MFT. */
if (zlen) {
if (mft) {
zbit = wnd_zone_bit(wnd);
*rno = zbit;
wnd_zone_set(wnd, zbit + 1, zlen - 1);
}
goto found;
}
/* No MFT zone. Find the nearest to '0' free MFT. */
if (!wnd_find(wnd, 1, MFT_REC_FREE, 0, &zbit)) {
/* Resize MFT */
mft_total = wnd->nbits;
err = ntfs_extend_mft(sbi);
if (!err) {
zbit = mft_total;
goto reserve_mft;
}
if (!mft || MFT_REC_FREE == sbi->mft.next_reserved)
goto out;
err = 0;
/*
* Look for free record reserved area [11-16) ==
* [MFT_REC_RESERVED, MFT_REC_FREE ) MFT bitmap always
* marks it as used.
*/
if (!sbi->mft.reserved_bitmap) {
/* Once per session create internal bitmap for 5 bits. */
sbi->mft.reserved_bitmap = 0xFF;
ref.high = 0;
for (ir = MFT_REC_RESERVED; ir < MFT_REC_FREE; ir++) {
struct inode *i;
struct ntfs_inode *ni;
struct MFT_REC *mrec;
ref.low = cpu_to_le32(ir);
ref.seq = cpu_to_le16(ir);
i = ntfs_iget5(sb, &ref, NULL);
if (IS_ERR(i)) {
next:
ntfs_notice(
sb,
"Invalid reserved record %x",
ref.low);
continue;
}
if (is_bad_inode(i)) {
iput(i);
goto next;
}
ni = ntfs_i(i);
mrec = ni->mi.mrec;
if (!is_rec_base(mrec))
goto next;
if (mrec->hard_links)
goto next;
if (!ni_std(ni))
goto next;
if (ni_find_attr(ni, NULL, NULL, ATTR_NAME,
NULL, 0, NULL, NULL))
goto next;
__clear_bit(ir - MFT_REC_RESERVED,
&sbi->mft.reserved_bitmap);
}
}
/* Scan 5 bits for zero. Bit 0 == MFT_REC_RESERVED */
zbit = find_next_zero_bit(&sbi->mft.reserved_bitmap,
MFT_REC_FREE, MFT_REC_RESERVED);
if (zbit >= MFT_REC_FREE) {
sbi->mft.next_reserved = MFT_REC_FREE;
goto out;
}
zlen = 1;
sbi->mft.next_reserved = zbit;
} else {
reserve_mft:
zlen = zbit == MFT_REC_FREE ? (MFT_REC_USER - MFT_REC_FREE) : 4;
if (zbit + zlen > wnd->nbits)
zlen = wnd->nbits - zbit;
while (zlen > 1 && !wnd_is_free(wnd, zbit, zlen))
zlen -= 1;
/* [zbit, zbit + zlen) will be used for MFT itself. */
from = sbi->mft.used;
if (from < zbit)
from = zbit;
to = zbit + zlen;
if (from < to) {
ntfs_clear_mft_tail(sbi, from, to);
sbi->mft.used = to;
}
}
if (mft) {
*rno = zbit;
zbit += 1;
zlen -= 1;
}
wnd_zone_set(wnd, zbit, zlen);
found:
if (!mft) {
/* The request to get record for general purpose. */
if (sbi->mft.next_free < MFT_REC_USER)
sbi->mft.next_free = MFT_REC_USER;
for (;;) {
if (sbi->mft.next_free >= sbi->mft.bitmap.nbits) {
} else if (!wnd_find(wnd, 1, MFT_REC_USER, 0, &fr)) {
sbi->mft.next_free = sbi->mft.bitmap.nbits;
} else {
*rno = fr;
sbi->mft.next_free = *rno + 1;
break;
}
err = ntfs_extend_mft(sbi);
if (err)
goto out;
}
}
if (ni && !ni_add_subrecord(ni, *rno, mi)) {
err = -ENOMEM;
goto out;
}
/* We have found a record that are not reserved for next MFT. */
if (*rno >= MFT_REC_FREE)
wnd_set_used(wnd, *rno, 1);
else if (*rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited)
__set_bit(*rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
out:
if (!mft)
up_write(&wnd->rw_lock);
return err;
}
/*
* ntfs_mark_rec_free - Mark record as free.
* is_mft - true if we are changing MFT
*/
void ntfs_mark_rec_free(struct ntfs_sb_info *sbi, CLST rno, bool is_mft)
{
struct wnd_bitmap *wnd = &sbi->mft.bitmap;
if (!is_mft)
down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
if (rno >= wnd->nbits)
goto out;
if (rno >= MFT_REC_FREE) {
if (!wnd_is_used(wnd, rno, 1))
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
else
wnd_set_free(wnd, rno, 1);
} else if (rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited) {
__clear_bit(rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
}
if (rno < wnd_zone_bit(wnd))
wnd_zone_set(wnd, rno, 1);
else if (rno < sbi->mft.next_free && rno >= MFT_REC_USER)
sbi->mft.next_free = rno;
out:
if (!is_mft)
up_write(&wnd->rw_lock);
}
/*
* ntfs_clear_mft_tail - Format empty records [from, to).
*
* sbi->mft.bitmap is locked for write.
*/
int ntfs_clear_mft_tail(struct ntfs_sb_info *sbi, size_t from, size_t to)
{
int err;
u32 rs;
u64 vbo;
struct runs_tree *run;
struct ntfs_inode *ni;
if (from >= to)
return 0;
rs = sbi->record_size;
ni = sbi->mft.ni;
run = &ni->file.run;
down_read(&ni->file.run_lock);
vbo = (u64)from * rs;
for (; from < to; from++, vbo += rs) {
struct ntfs_buffers nb;
err = ntfs_get_bh(sbi, run, vbo, rs, &nb);
if (err)
goto out;
err = ntfs_write_bh(sbi, &sbi->new_rec->rhdr, &nb, 0);
nb_put(&nb);
if (err)
goto out;
}
out:
sbi->mft.used = from;
up_read(&ni->file.run_lock);
return err;
}
/*
* ntfs_refresh_zone - Refresh MFT zone.
*
* sbi->used.bitmap is locked for rw.
* sbi->mft.bitmap is locked for write.
* sbi->mft.ni->file.run_lock for write.
*/
int ntfs_refresh_zone(struct ntfs_sb_info *sbi)
{
CLST lcn, vcn, len;
size_t lcn_s, zlen;
struct wnd_bitmap *wnd = &sbi->used.bitmap;
struct ntfs_inode *ni = sbi->mft.ni;
/* Do not change anything unless we have non empty MFT zone. */
if (wnd_zone_len(wnd))
return 0;
vcn = bytes_to_cluster(sbi,
(u64)sbi->mft.bitmap.nbits << sbi->record_bits);
if (!run_lookup_entry(&ni->file.run, vcn - 1, &lcn, &len, NULL))
lcn = SPARSE_LCN;
/* We should always find Last Lcn for MFT. */
if (lcn == SPARSE_LCN)
return -EINVAL;
lcn_s = lcn + 1;
/* Try to allocate clusters after last MFT run. */
zlen = wnd_find(wnd, sbi->zone_max, lcn_s, 0, &lcn_s);
wnd_zone_set(wnd, lcn_s, zlen);
return 0;
}
/*
* ntfs_update_mftmirr - Update $MFTMirr data.
*/
void ntfs_update_mftmirr(struct ntfs_sb_info *sbi, int wait)
{
int err;
struct super_block *sb = sbi->sb;
u32 blocksize, bytes;
sector_t block1, block2;
/*
* sb can be NULL here. In this case sbi->flags should be 0 too.
*/
if (!sb || !(sbi->flags & NTFS_FLAGS_MFTMIRR))
return;
blocksize = sb->s_blocksize;
bytes = sbi->mft.recs_mirr << sbi->record_bits;
block1 = sbi->mft.lbo >> sb->s_blocksize_bits;
block2 = sbi->mft.lbo2 >> sb->s_blocksize_bits;
for (; bytes >= blocksize; bytes -= blocksize) {
struct buffer_head *bh1, *bh2;
bh1 = sb_bread(sb, block1++);
if (!bh1)
return;
bh2 = sb_getblk(sb, block2++);
if (!bh2) {
put_bh(bh1);
return;
}
if (buffer_locked(bh2))
__wait_on_buffer(bh2);
lock_buffer(bh2);
memcpy(bh2->b_data, bh1->b_data, blocksize);
set_buffer_uptodate(bh2);
mark_buffer_dirty(bh2);
unlock_buffer(bh2);
put_bh(bh1);
bh1 = NULL;
err = wait ? sync_dirty_buffer(bh2) : 0;
put_bh(bh2);
if (err)
return;
}
sbi->flags &= ~NTFS_FLAGS_MFTMIRR;
}
/*
* ntfs_bad_inode
*
* Marks inode as bad and marks fs as 'dirty'
*/
void ntfs_bad_inode(struct inode *inode, const char *hint)
{
struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
ntfs_inode_err(inode, "%s", hint);
make_bad_inode(inode);
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
}
/*
* ntfs_set_state
*
* Mount: ntfs_set_state(NTFS_DIRTY_DIRTY)
* Umount: ntfs_set_state(NTFS_DIRTY_CLEAR)
* NTFS error: ntfs_set_state(NTFS_DIRTY_ERROR)
*/
int ntfs_set_state(struct ntfs_sb_info *sbi, enum NTFS_DIRTY_FLAGS dirty)
{
int err;
struct ATTRIB *attr;
struct VOLUME_INFO *info;
struct mft_inode *mi;
struct ntfs_inode *ni;
__le16 info_flags;
/*
* Do not change state if fs was real_dirty.
* Do not change state if fs already dirty(clear).
* Do not change any thing if mounted read only.
*/
if (sbi->volume.real_dirty || sb_rdonly(sbi->sb))
return 0;
/* Check cached value. */
if ((dirty == NTFS_DIRTY_CLEAR ? 0 : VOLUME_FLAG_DIRTY) ==
(sbi->volume.flags & VOLUME_FLAG_DIRTY))
return 0;
ni = sbi->volume.ni;
if (!ni)
return -EINVAL;
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_DIRTY);
attr = ni_find_attr(ni, NULL, NULL, ATTR_VOL_INFO, NULL, 0, NULL, &mi);
if (!attr) {
err = -EINVAL;
goto out;
}
info = resident_data_ex(attr, SIZEOF_ATTRIBUTE_VOLUME_INFO);
if (!info) {
err = -EINVAL;
goto out;
}
info_flags = info->flags;
switch (dirty) {
case NTFS_DIRTY_ERROR:
ntfs_notice(sbi->sb, "Mark volume as dirty due to NTFS errors");
sbi->volume.real_dirty = true;
fallthrough;
case NTFS_DIRTY_DIRTY:
info->flags |= VOLUME_FLAG_DIRTY;
break;
case NTFS_DIRTY_CLEAR:
info->flags &= ~VOLUME_FLAG_DIRTY;
break;
}
/* Cache current volume flags. */
if (info_flags != info->flags) {
sbi->volume.flags = info->flags;
mi->dirty = true;
}
err = 0;
out:
ni_unlock(ni);
if (err)
return err;
mark_inode_dirty(&ni->vfs_inode);
/* verify(!ntfs_update_mftmirr()); */
/*
* If we used wait=1, sync_inode_metadata waits for the io for the
* inode to finish. It hangs when media is removed.
* So wait=0 is sent down to sync_inode_metadata
* and filemap_fdatawrite is used for the data blocks.
*/
err = sync_inode_metadata(&ni->vfs_inode, 0);
if (!err)
err = filemap_fdatawrite(ni->vfs_inode.i_mapping);
return err;
}
/*
* security_hash - Calculates a hash of security descriptor.
*/
static inline __le32 security_hash(const void *sd, size_t bytes)
{
u32 hash = 0;
const __le32 *ptr = sd;
bytes >>= 2;
while (bytes--)
hash = ((hash >> 0x1D) | (hash << 3)) + le32_to_cpu(*ptr++);
return cpu_to_le32(hash);
}
int ntfs_sb_read(struct super_block *sb, u64 lbo, size_t bytes, void *buffer)
{
struct block_device *bdev = sb->s_bdev;
u32 blocksize = sb->s_blocksize;
u64 block = lbo >> sb->s_blocksize_bits;
u32 off = lbo & (blocksize - 1);
u32 op = blocksize - off;
for (; bytes; block += 1, off = 0, op = blocksize) {
struct buffer_head *bh = __bread(bdev, block, blocksize);
if (!bh)
return -EIO;
if (op > bytes)
op = bytes;
memcpy(buffer, bh->b_data + off, op);
put_bh(bh);
bytes -= op;
buffer = Add2Ptr(buffer, op);
}
return 0;
}
int ntfs_sb_write(struct super_block *sb, u64 lbo, size_t bytes,
const void *buf, int wait)
{
u32 blocksize = sb->s_blocksize;
struct block_device *bdev = sb->s_bdev;
sector_t block = lbo >> sb->s_blocksize_bits;
u32 off = lbo & (blocksize - 1);
u32 op = blocksize - off;
struct buffer_head *bh;
if (!wait && (sb->s_flags & SB_SYNCHRONOUS))
wait = 1;
for (; bytes; block += 1, off = 0, op = blocksize) {
if (op > bytes)
op = bytes;
if (op < blocksize) {
bh = __bread(bdev, block, blocksize);
if (!bh) {
ntfs_err(sb, "failed to read block %llx",
(u64)block);
return -EIO;
}
} else {
bh = __getblk(bdev, block, blocksize);
if (!bh)
return -ENOMEM;
}
if (buffer_locked(bh))
__wait_on_buffer(bh);
lock_buffer(bh);
if (buf) {
memcpy(bh->b_data + off, buf, op);
buf = Add2Ptr(buf, op);
} else {
memset(bh->b_data + off, -1, op);
}
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
if (wait) {
int err = sync_dirty_buffer(bh);
if (err) {
ntfs_err(
sb,
"failed to sync buffer at block %llx, error %d",
(u64)block, err);
put_bh(bh);
return err;
}
}
put_bh(bh);
bytes -= op;
}
return 0;
}
int ntfs_sb_write_run(struct ntfs_sb_info *sbi, const struct runs_tree *run,
u64 vbo, const void *buf, size_t bytes, int sync)
{
struct super_block *sb = sbi->sb;
u8 cluster_bits = sbi->cluster_bits;
u32 off = vbo & sbi->cluster_mask;
CLST lcn, clen, vcn = vbo >> cluster_bits, vcn_next;
u64 lbo, len;
size_t idx;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
return -ENOENT;
if (lcn == SPARSE_LCN)
return -EINVAL;
lbo = ((u64)lcn << cluster_bits) + off;
len = ((u64)clen << cluster_bits) - off;
for (;;) {
u32 op = min_t(u64, len, bytes);
int err = ntfs_sb_write(sb, lbo, op, buf, sync);
if (err)
return err;
bytes -= op;
if (!bytes)
break;
vcn_next = vcn + clen;
if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
vcn != vcn_next)
return -ENOENT;
if (lcn == SPARSE_LCN)
return -EINVAL;
if (buf)
buf = Add2Ptr(buf, op);
lbo = ((u64)lcn << cluster_bits);
len = ((u64)clen << cluster_bits);
}
return 0;
}
struct buffer_head *ntfs_bread_run(struct ntfs_sb_info *sbi,
const struct runs_tree *run, u64 vbo)
{
struct super_block *sb = sbi->sb;
u8 cluster_bits = sbi->cluster_bits;
CLST lcn;
u64 lbo;
if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, NULL, NULL))
return ERR_PTR(-ENOENT);
lbo = ((u64)lcn << cluster_bits) + (vbo & sbi->cluster_mask);
return ntfs_bread(sb, lbo >> sb->s_blocksize_bits);
}
int ntfs_read_run_nb(struct ntfs_sb_info *sbi, const struct runs_tree *run,
u64 vbo, void *buf, u32 bytes, struct ntfs_buffers *nb)
{
int err;
struct super_block *sb = sbi->sb;
u32 blocksize = sb->s_blocksize;
u8 cluster_bits = sbi->cluster_bits;
u32 off = vbo & sbi->cluster_mask;
u32 nbh = 0;
CLST vcn_next, vcn = vbo >> cluster_bits;
CLST lcn, clen;
u64 lbo, len;
size_t idx;
struct buffer_head *bh;
if (!run) {
/* First reading of $Volume + $MFTMirr + $LogFile goes here. */
if (vbo > MFT_REC_VOL * sbi->record_size) {
err = -ENOENT;
goto out;
}
/* Use absolute boot's 'MFTCluster' to read record. */
lbo = vbo + sbi->mft.lbo;
len = sbi->record_size;
} else if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
err = -ENOENT;
goto out;
} else {
if (lcn == SPARSE_LCN) {
err = -EINVAL;
goto out;
}
lbo = ((u64)lcn << cluster_bits) + off;
len = ((u64)clen << cluster_bits) - off;
}
off = lbo & (blocksize - 1);
if (nb) {
nb->off = off;
nb->bytes = bytes;
}
for (;;) {
u32 len32 = len >= bytes ? bytes : len;
sector_t block = lbo >> sb->s_blocksize_bits;
do {
u32 op = blocksize - off;
if (op > len32)
op = len32;
bh = ntfs_bread(sb, block);
if (!bh) {
err = -EIO;
goto out;
}
if (buf) {
memcpy(buf, bh->b_data + off, op);
buf = Add2Ptr(buf, op);
}
if (!nb) {
put_bh(bh);
} else if (nbh >= ARRAY_SIZE(nb->bh)) {
err = -EINVAL;
goto out;
} else {
nb->bh[nbh++] = bh;
nb->nbufs = nbh;
}
bytes -= op;
if (!bytes)
return 0;
len32 -= op;
block += 1;
off = 0;
} while (len32);
vcn_next = vcn + clen;
if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
vcn != vcn_next) {
err = -ENOENT;
goto out;
}
if (lcn == SPARSE_LCN) {
err = -EINVAL;
goto out;
}
lbo = ((u64)lcn << cluster_bits);
len = ((u64)clen << cluster_bits);
}
out:
if (!nbh)
return err;
while (nbh) {
put_bh(nb->bh[--nbh]);
nb->bh[nbh] = NULL;
}
nb->nbufs = 0;
return err;
}
/*
* ntfs_read_bh
*
* Return: < 0 if error, 0 if ok, -E_NTFS_FIXUP if need to update fixups.
*/
int ntfs_read_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
struct NTFS_RECORD_HEADER *rhdr, u32 bytes,
struct ntfs_buffers *nb)
{
int err = ntfs_read_run_nb(sbi, run, vbo, rhdr, bytes, nb);
if (err)
return err;
return ntfs_fix_post_read(rhdr, nb->bytes, true);
}
int ntfs_get_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
u32 bytes, struct ntfs_buffers *nb)
{
int err = 0;
struct super_block *sb = sbi->sb;
u32 blocksize = sb->s_blocksize;
u8 cluster_bits = sbi->cluster_bits;
CLST vcn_next, vcn = vbo >> cluster_bits;
u32 off;
u32 nbh = 0;
CLST lcn, clen;
u64 lbo, len;
size_t idx;
nb->bytes = bytes;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
err = -ENOENT;
goto out;
}
off = vbo & sbi->cluster_mask;
lbo = ((u64)lcn << cluster_bits) + off;
len = ((u64)clen << cluster_bits) - off;
nb->off = off = lbo & (blocksize - 1);
for (;;) {
u32 len32 = min_t(u64, len, bytes);
sector_t block = lbo >> sb->s_blocksize_bits;
do {
u32 op;
struct buffer_head *bh;
if (nbh >= ARRAY_SIZE(nb->bh)) {
err = -EINVAL;
goto out;
}
op = blocksize - off;
if (op > len32)
op = len32;
if (op == blocksize) {
bh = sb_getblk(sb, block);
if (!bh) {
err = -ENOMEM;
goto out;
}
if (buffer_locked(bh))
__wait_on_buffer(bh);
set_buffer_uptodate(bh);
} else {
bh = ntfs_bread(sb, block);
if (!bh) {
err = -EIO;
goto out;
}
}
nb->bh[nbh++] = bh;
bytes -= op;
if (!bytes) {
nb->nbufs = nbh;
return 0;
}
block += 1;
len32 -= op;
off = 0;
} while (len32);
vcn_next = vcn + clen;
if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
vcn != vcn_next) {
err = -ENOENT;
goto out;
}
lbo = ((u64)lcn << cluster_bits);
len = ((u64)clen << cluster_bits);
}
out:
while (nbh) {
put_bh(nb->bh[--nbh]);
nb->bh[nbh] = NULL;
}
nb->nbufs = 0;
return err;
}
int ntfs_write_bh(struct ntfs_sb_info *sbi, struct NTFS_RECORD_HEADER *rhdr,
struct ntfs_buffers *nb, int sync)
{
int err = 0;
struct super_block *sb = sbi->sb;
u32 block_size = sb->s_blocksize;
u32 bytes = nb->bytes;
u32 off = nb->off;
u16 fo = le16_to_cpu(rhdr->fix_off);
u16 fn = le16_to_cpu(rhdr->fix_num);
u32 idx;
__le16 *fixup;
__le16 sample;
if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
fn * SECTOR_SIZE > bytes) {
return -EINVAL;
}
for (idx = 0; bytes && idx < nb->nbufs; idx += 1, off = 0) {
u32 op = block_size - off;
char *bh_data;
struct buffer_head *bh = nb->bh[idx];
__le16 *ptr, *end_data;
if (op > bytes)
op = bytes;
if (buffer_locked(bh))
__wait_on_buffer(bh);
lock_buffer(bh);
bh_data = bh->b_data + off;
end_data = Add2Ptr(bh_data, op);
memcpy(bh_data, rhdr, op);
if (!idx) {
u16 t16;
fixup = Add2Ptr(bh_data, fo);
sample = *fixup;
t16 = le16_to_cpu(sample);
if (t16 >= 0x7FFF) {
sample = *fixup = cpu_to_le16(1);
} else {
sample = cpu_to_le16(t16 + 1);
*fixup = sample;
}
*(__le16 *)Add2Ptr(rhdr, fo) = sample;
}
ptr = Add2Ptr(bh_data, SECTOR_SIZE - sizeof(short));
do {
*++fixup = *ptr;
*ptr = sample;
ptr += SECTOR_SIZE / sizeof(short);
} while (ptr < end_data);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
unlock_buffer(bh);
if (sync) {
int err2 = sync_dirty_buffer(bh);
if (!err && err2)
err = err2;
}
bytes -= op;
rhdr = Add2Ptr(rhdr, op);
}
return err;
}
/*
* ntfs_bio_pages - Read/write pages from/to disk.
*/
int ntfs_bio_pages(struct ntfs_sb_info *sbi, const struct runs_tree *run,
struct page **pages, u32 nr_pages, u64 vbo, u32 bytes,
enum req_op op)
{
int err = 0;
struct bio *new, *bio = NULL;
struct super_block *sb = sbi->sb;
struct block_device *bdev = sb->s_bdev;
struct page *page;
u8 cluster_bits = sbi->cluster_bits;
CLST lcn, clen, vcn, vcn_next;
u32 add, off, page_idx;
u64 lbo, len;
size_t run_idx;
struct blk_plug plug;
if (!bytes)
return 0;
blk_start_plug(&plug);
/* Align vbo and bytes to be 512 bytes aligned. */
lbo = (vbo + bytes + 511) & ~511ull;
vbo = vbo & ~511ull;
bytes = lbo - vbo;
vcn = vbo >> cluster_bits;
if (!run_lookup_entry(run, vcn, &lcn, &clen, &run_idx)) {
err = -ENOENT;
goto out;
}
off = vbo & sbi->cluster_mask;
page_idx = 0;
page = pages[0];
for (;;) {
lbo = ((u64)lcn << cluster_bits) + off;
len = ((u64)clen << cluster_bits) - off;
new_bio:
new = bio_alloc(bdev, nr_pages - page_idx, op, GFP_NOFS);
if (bio) {
bio_chain(bio, new);
submit_bio(bio);
}
bio = new;
bio->bi_iter.bi_sector = lbo >> 9;
while (len) {
off = vbo & (PAGE_SIZE - 1);
add = off + len > PAGE_SIZE ? (PAGE_SIZE - off) : len;
if (bio_add_page(bio, page, add, off) < add)
goto new_bio;
if (bytes <= add)
goto out;
bytes -= add;
vbo += add;
if (add + off == PAGE_SIZE) {
page_idx += 1;
if (WARN_ON(page_idx >= nr_pages)) {
err = -EINVAL;
goto out;
}
page = pages[page_idx];
}
if (len <= add)
break;
len -= add;
lbo += add;
}
vcn_next = vcn + clen;
if (!run_get_entry(run, ++run_idx, &vcn, &lcn, &clen) ||
vcn != vcn_next) {
err = -ENOENT;
goto out;
}
off = 0;
}
out:
if (bio) {
if (!err)
err = submit_bio_wait(bio);
bio_put(bio);
}
blk_finish_plug(&plug);
return err;
}
/*
* ntfs_bio_fill_1 - Helper for ntfs_loadlog_and_replay().
*
* Fill on-disk logfile range by (-1)
* this means empty logfile.
*/
int ntfs_bio_fill_1(struct ntfs_sb_info *sbi, const struct runs_tree *run)
{
int err = 0;
struct super_block *sb = sbi->sb;
struct block_device *bdev = sb->s_bdev;
u8 cluster_bits = sbi->cluster_bits;
struct bio *new, *bio = NULL;
CLST lcn, clen;
u64 lbo, len;
size_t run_idx;
struct page *fill;
void *kaddr;
struct blk_plug plug;
fill = alloc_page(GFP_KERNEL);
if (!fill)
return -ENOMEM;
kaddr = kmap_atomic(fill);
memset(kaddr, -1, PAGE_SIZE);
kunmap_atomic(kaddr);
flush_dcache_page(fill);
lock_page(fill);
if (!run_lookup_entry(run, 0, &lcn, &clen, &run_idx)) {
err = -ENOENT;
goto out;
}
/*
* TODO: Try blkdev_issue_write_same.
*/
blk_start_plug(&plug);
do {
lbo = (u64)lcn << cluster_bits;
len = (u64)clen << cluster_bits;
new_bio:
new = bio_alloc(bdev, BIO_MAX_VECS, REQ_OP_WRITE, GFP_NOFS);
if (bio) {
bio_chain(bio, new);
submit_bio(bio);
}
bio = new;
bio->bi_iter.bi_sector = lbo >> 9;
for (;;) {
u32 add = len > PAGE_SIZE ? PAGE_SIZE : len;
if (bio_add_page(bio, fill, add, 0) < add)
goto new_bio;
lbo += add;
if (len <= add)
break;
len -= add;
}
} while (run_get_entry(run, ++run_idx, NULL, &lcn, &clen));
if (!err)
err = submit_bio_wait(bio);
bio_put(bio);
blk_finish_plug(&plug);
out:
unlock_page(fill);
put_page(fill);
return err;
}
int ntfs_vbo_to_lbo(struct ntfs_sb_info *sbi, const struct runs_tree *run,
u64 vbo, u64 *lbo, u64 *bytes)
{
u32 off;
CLST lcn, len;
u8 cluster_bits = sbi->cluster_bits;
if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, &len, NULL))
return -ENOENT;
off = vbo & sbi->cluster_mask;
*lbo = lcn == SPARSE_LCN ? -1 : (((u64)lcn << cluster_bits) + off);
*bytes = ((u64)len << cluster_bits) - off;
return 0;
}
struct ntfs_inode *ntfs_new_inode(struct ntfs_sb_info *sbi, CLST rno,
enum RECORD_FLAG flag)
{
int err = 0;
struct super_block *sb = sbi->sb;
struct inode *inode = new_inode(sb);
struct ntfs_inode *ni;
if (!inode)
return ERR_PTR(-ENOMEM);
ni = ntfs_i(inode);
err = mi_format_new(&ni->mi, sbi, rno, flag, false);
if (err)
goto out;
inode->i_ino = rno;
if (insert_inode_locked(inode) < 0) {
err = -EIO;
goto out;
}
out:
if (err) {
make_bad_inode(inode);
iput(inode);
ni = ERR_PTR(err);
}
return ni;
}
/*
* O:BAG:BAD:(A;OICI;FA;;;WD)
* Owner S-1-5-32-544 (Administrators)
* Group S-1-5-32-544 (Administrators)
* ACE: allow S-1-1-0 (Everyone) with FILE_ALL_ACCESS
*/
const u8 s_default_security[] __aligned(8) = {
0x01, 0x00, 0x04, 0x80, 0x30, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x1C, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x14, 0x00, 0xFF, 0x01, 0x1F, 0x00,
0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00,
0x20, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00,
};
static_assert(sizeof(s_default_security) == 0x50);
static inline u32 sid_length(const struct SID *sid)
{
return struct_size(sid, SubAuthority, sid->SubAuthorityCount);
}
/*
* is_acl_valid
*
* Thanks Mark Harmstone for idea.
*/
static bool is_acl_valid(const struct ACL *acl, u32 len)
{
const struct ACE_HEADER *ace;
u32 i;
u16 ace_count, ace_size;
if (acl->AclRevision != ACL_REVISION &&
acl->AclRevision != ACL_REVISION_DS) {
/*
* This value should be ACL_REVISION, unless the ACL contains an
* object-specific ACE, in which case this value must be ACL_REVISION_DS.
* All ACEs in an ACL must be at the same revision level.
*/
return false;
}
if (acl->Sbz1)
return false;
if (le16_to_cpu(acl->AclSize) > len)
return false;
if (acl->Sbz2)
return false;
len -= sizeof(struct ACL);
ace = (struct ACE_HEADER *)&acl[1];
ace_count = le16_to_cpu(acl->AceCount);
for (i = 0; i < ace_count; i++) {
if (len < sizeof(struct ACE_HEADER))
return false;
ace_size = le16_to_cpu(ace->AceSize);
if (len < ace_size)
return false;
len -= ace_size;
ace = Add2Ptr(ace, ace_size);
}
return true;
}
bool is_sd_valid(const struct SECURITY_DESCRIPTOR_RELATIVE *sd, u32 len)
{
u32 sd_owner, sd_group, sd_sacl, sd_dacl;
if (len < sizeof(struct SECURITY_DESCRIPTOR_RELATIVE))
return false;
if (sd->Revision != 1)
return false;
if (sd->Sbz1)
return false;
if (!(sd->Control & SE_SELF_RELATIVE))
return false;
sd_owner = le32_to_cpu(sd->Owner);
if (sd_owner) {
const struct SID *owner = Add2Ptr(sd, sd_owner);
if (sd_owner + offsetof(struct SID, SubAuthority) > len)
return false;
if (owner->Revision != 1)
return false;
if (sd_owner + sid_length(owner) > len)
return false;
}
sd_group = le32_to_cpu(sd->Group);
if (sd_group) {
const struct SID *group = Add2Ptr(sd, sd_group);
if (sd_group + offsetof(struct SID, SubAuthority) > len)
return false;
if (group->Revision != 1)
return false;
if (sd_group + sid_length(group) > len)
return false;
}
sd_sacl = le32_to_cpu(sd->Sacl);
if (sd_sacl) {
const struct ACL *sacl = Add2Ptr(sd, sd_sacl);
if (sd_sacl + sizeof(struct ACL) > len)
return false;
if (!is_acl_valid(sacl, len - sd_sacl))
return false;
}
sd_dacl = le32_to_cpu(sd->Dacl);
if (sd_dacl) {
const struct ACL *dacl = Add2Ptr(sd, sd_dacl);
if (sd_dacl + sizeof(struct ACL) > len)
return false;
if (!is_acl_valid(dacl, len - sd_dacl))
return false;
}
return true;
}
/*
* ntfs_security_init - Load and parse $Secure.
*/
int ntfs_security_init(struct ntfs_sb_info *sbi)
{
int err;
struct super_block *sb = sbi->sb;
struct inode *inode;
struct ntfs_inode *ni;
struct MFT_REF ref;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
u64 sds_size;
size_t off;
struct NTFS_DE *ne;
struct NTFS_DE_SII *sii_e;
struct ntfs_fnd *fnd_sii = NULL;
const struct INDEX_ROOT *root_sii;
const struct INDEX_ROOT *root_sdh;
struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
struct ntfs_index *indx_sii = &sbi->security.index_sii;
ref.low = cpu_to_le32(MFT_REC_SECURE);
ref.high = 0;
ref.seq = cpu_to_le16(MFT_REC_SECURE);
inode = ntfs_iget5(sb, &ref, &NAME_SECURE);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ntfs_err(sb, "Failed to load $Secure (%d).", err);
inode = NULL;
goto out;
}
ni = ntfs_i(inode);
le = NULL;
attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SDH_NAME,
ARRAY_SIZE(SDH_NAME), NULL, NULL);
if (!attr ||
!(root_sdh = resident_data_ex(attr, sizeof(struct INDEX_ROOT))) ||
root_sdh->type != ATTR_ZERO ||
root_sdh->rule != NTFS_COLLATION_TYPE_SECURITY_HASH ||
offsetof(struct INDEX_ROOT, ihdr) +
le32_to_cpu(root_sdh->ihdr.used) >
le32_to_cpu(attr->res.data_size)) {
ntfs_err(sb, "$Secure::$SDH is corrupted.");
err = -EINVAL;
goto out;
}
err = indx_init(indx_sdh, sbi, attr, INDEX_MUTEX_SDH);
if (err) {
ntfs_err(sb, "Failed to initialize $Secure::$SDH (%d).", err);
goto out;
}
attr = ni_find_attr(ni, attr, &le, ATTR_ROOT, SII_NAME,
ARRAY_SIZE(SII_NAME), NULL, NULL);
if (!attr ||
!(root_sii = resident_data_ex(attr, sizeof(struct INDEX_ROOT))) ||
root_sii->type != ATTR_ZERO ||
root_sii->rule != NTFS_COLLATION_TYPE_UINT ||
offsetof(struct INDEX_ROOT, ihdr) +
le32_to_cpu(root_sii->ihdr.used) >
le32_to_cpu(attr->res.data_size)) {
ntfs_err(sb, "$Secure::$SII is corrupted.");
err = -EINVAL;
goto out;
}
err = indx_init(indx_sii, sbi, attr, INDEX_MUTEX_SII);
if (err) {
ntfs_err(sb, "Failed to initialize $Secure::$SII (%d).", err);
goto out;
}
fnd_sii = fnd_get();
if (!fnd_sii) {
err = -ENOMEM;
goto out;
}
sds_size = inode->i_size;
/* Find the last valid Id. */
sbi->security.next_id = SECURITY_ID_FIRST;
/* Always write new security at the end of bucket. */
sbi->security.next_off =
ALIGN(sds_size - SecurityDescriptorsBlockSize, 16);
off = 0;
ne = NULL;
for (;;) {
u32 next_id;
err = indx_find_raw(indx_sii, ni, root_sii, &ne, &off, fnd_sii);
if (err || !ne)
break;
sii_e = (struct NTFS_DE_SII *)ne;
if (le16_to_cpu(ne->view.data_size) < sizeof(sii_e->sec_hdr))
continue;
next_id = le32_to_cpu(sii_e->sec_id) + 1;
if (next_id >= sbi->security.next_id)
sbi->security.next_id = next_id;
}
sbi->security.ni = ni;
inode = NULL;
out:
iput(inode);
fnd_put(fnd_sii);
return err;
}
/*
* ntfs_get_security_by_id - Read security descriptor by id.
*/
int ntfs_get_security_by_id(struct ntfs_sb_info *sbi, __le32 security_id,
struct SECURITY_DESCRIPTOR_RELATIVE **sd,
size_t *size)
{
int err;
int diff;
struct ntfs_inode *ni = sbi->security.ni;
struct ntfs_index *indx = &sbi->security.index_sii;
void *p = NULL;
struct NTFS_DE_SII *sii_e;
struct ntfs_fnd *fnd_sii;
struct SECURITY_HDR d_security;
const struct INDEX_ROOT *root_sii;
u32 t32;
*sd = NULL;
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
fnd_sii = fnd_get();
if (!fnd_sii) {
err = -ENOMEM;
goto out;
}
root_sii = indx_get_root(indx, ni, NULL, NULL);
if (!root_sii) {
err = -EINVAL;
goto out;
}
/* Try to find this SECURITY descriptor in SII indexes. */
err = indx_find(indx, ni, root_sii, &security_id, sizeof(security_id),
NULL, &diff, (struct NTFS_DE **)&sii_e, fnd_sii);
if (err)
goto out;
if (diff)
goto out;
t32 = le32_to_cpu(sii_e->sec_hdr.size);
if (t32 < sizeof(struct SECURITY_HDR)) {
err = -EINVAL;
goto out;
}
if (t32 > sizeof(struct SECURITY_HDR) + 0x10000) {
/* Looks like too big security. 0x10000 - is arbitrary big number. */
err = -EFBIG;
goto out;
}
*size = t32 - sizeof(struct SECURITY_HDR);
p = kmalloc(*size, GFP_NOFS);
if (!p) {
err = -ENOMEM;
goto out;
}
err = ntfs_read_run_nb(sbi, &ni->file.run,
le64_to_cpu(sii_e->sec_hdr.off), &d_security,
sizeof(d_security), NULL);
if (err)
goto out;
if (memcmp(&d_security, &sii_e->sec_hdr, sizeof(d_security))) {
err = -EINVAL;
goto out;
}
err = ntfs_read_run_nb(sbi, &ni->file.run,
le64_to_cpu(sii_e->sec_hdr.off) +
sizeof(struct SECURITY_HDR),
p, *size, NULL);
if (err)
goto out;
*sd = p;
p = NULL;
out:
kfree(p);
fnd_put(fnd_sii);
ni_unlock(ni);
return err;
}
/*
* ntfs_insert_security - Insert security descriptor into $Secure::SDS.
*
* SECURITY Descriptor Stream data is organized into chunks of 256K bytes
* and it contains a mirror copy of each security descriptor. When writing
* to a security descriptor at location X, another copy will be written at
* location (X+256K).
* When writing a security descriptor that will cross the 256K boundary,
* the pointer will be advanced by 256K to skip
* over the mirror portion.
*/
int ntfs_insert_security(struct ntfs_sb_info *sbi,
const struct SECURITY_DESCRIPTOR_RELATIVE *sd,
u32 size_sd, __le32 *security_id, bool *inserted)
{
int err, diff;
struct ntfs_inode *ni = sbi->security.ni;
struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
struct ntfs_index *indx_sii = &sbi->security.index_sii;
struct NTFS_DE_SDH *e;
struct NTFS_DE_SDH sdh_e;
struct NTFS_DE_SII sii_e;
struct SECURITY_HDR *d_security;
u32 new_sec_size = size_sd + sizeof(struct SECURITY_HDR);
u32 aligned_sec_size = ALIGN(new_sec_size, 16);
struct SECURITY_KEY hash_key;
struct ntfs_fnd *fnd_sdh = NULL;
const struct INDEX_ROOT *root_sdh;
const struct INDEX_ROOT *root_sii;
u64 mirr_off, new_sds_size;
u32 next, left;
static_assert((1 << Log2OfSecurityDescriptorsBlockSize) ==
SecurityDescriptorsBlockSize);
hash_key.hash = security_hash(sd, size_sd);
hash_key.sec_id = SECURITY_ID_INVALID;
if (inserted)
*inserted = false;
*security_id = SECURITY_ID_INVALID;
/* Allocate a temporal buffer. */
d_security = kzalloc(aligned_sec_size, GFP_NOFS);
if (!d_security)
return -ENOMEM;
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
fnd_sdh = fnd_get();
if (!fnd_sdh) {
err = -ENOMEM;
goto out;
}
root_sdh = indx_get_root(indx_sdh, ni, NULL, NULL);
if (!root_sdh) {
err = -EINVAL;
goto out;
}
root_sii = indx_get_root(indx_sii, ni, NULL, NULL);
if (!root_sii) {
err = -EINVAL;
goto out;
}
/*
* Check if such security already exists.
* Use "SDH" and hash -> to get the offset in "SDS".
*/
err = indx_find(indx_sdh, ni, root_sdh, &hash_key, sizeof(hash_key),
&d_security->key.sec_id, &diff, (struct NTFS_DE **)&e,
fnd_sdh);
if (err)
goto out;
while (e) {
if (le32_to_cpu(e->sec_hdr.size) == new_sec_size) {
err = ntfs_read_run_nb(sbi, &ni->file.run,
le64_to_cpu(e->sec_hdr.off),
d_security, new_sec_size, NULL);
if (err)
goto out;
if (le32_to_cpu(d_security->size) == new_sec_size &&
d_security->key.hash == hash_key.hash &&
!memcmp(d_security + 1, sd, size_sd)) {
*security_id = d_security->key.sec_id;
/* Such security already exists. */
err = 0;
goto out;
}
}
err = indx_find_sort(indx_sdh, ni, root_sdh,
(struct NTFS_DE **)&e, fnd_sdh);
if (err)
goto out;
if (!e || e->key.hash != hash_key.hash)
break;
}
/* Zero unused space. */
next = sbi->security.next_off & (SecurityDescriptorsBlockSize - 1);
left = SecurityDescriptorsBlockSize - next;
/* Zero gap until SecurityDescriptorsBlockSize. */
if (left < new_sec_size) {
/* Zero "left" bytes from sbi->security.next_off. */
sbi->security.next_off += SecurityDescriptorsBlockSize + left;
}
/* Zero tail of previous security. */
//used = ni->vfs_inode.i_size & (SecurityDescriptorsBlockSize - 1);
/*
* Example:
* 0x40438 == ni->vfs_inode.i_size
* 0x00440 == sbi->security.next_off
* need to zero [0x438-0x440)
* if (next > used) {
* u32 tozero = next - used;
* zero "tozero" bytes from sbi->security.next_off - tozero
*/
/* Format new security descriptor. */
d_security->key.hash = hash_key.hash;
d_security->key.sec_id = cpu_to_le32(sbi->security.next_id);
d_security->off = cpu_to_le64(sbi->security.next_off);
d_security->size = cpu_to_le32(new_sec_size);
memcpy(d_security + 1, sd, size_sd);
/* Write main SDS bucket. */
err = ntfs_sb_write_run(sbi, &ni->file.run, sbi->security.next_off,
d_security, aligned_sec_size, 0);
if (err)
goto out;
mirr_off = sbi->security.next_off + SecurityDescriptorsBlockSize;
new_sds_size = mirr_off + aligned_sec_size;
if (new_sds_size > ni->vfs_inode.i_size) {
err = attr_set_size(ni, ATTR_DATA, SDS_NAME,
ARRAY_SIZE(SDS_NAME), &ni->file.run,
new_sds_size, &new_sds_size, false, NULL);
if (err)
goto out;
}
/* Write copy SDS bucket. */
err = ntfs_sb_write_run(sbi, &ni->file.run, mirr_off, d_security,
aligned_sec_size, 0);
if (err)
goto out;
/* Fill SII entry. */
sii_e.de.view.data_off =
cpu_to_le16(offsetof(struct NTFS_DE_SII, sec_hdr));
sii_e.de.view.data_size = cpu_to_le16(sizeof(struct SECURITY_HDR));
sii_e.de.view.res = 0;
sii_e.de.size = cpu_to_le16(sizeof(struct NTFS_DE_SII));
sii_e.de.key_size = cpu_to_le16(sizeof(d_security->key.sec_id));
sii_e.de.flags = 0;
sii_e.de.res = 0;
sii_e.sec_id = d_security->key.sec_id;
memcpy(&sii_e.sec_hdr, d_security, sizeof(struct SECURITY_HDR));
err = indx_insert_entry(indx_sii, ni, &sii_e.de, NULL, NULL, 0);
if (err)
goto out;
/* Fill SDH entry. */
sdh_e.de.view.data_off =
cpu_to_le16(offsetof(struct NTFS_DE_SDH, sec_hdr));
sdh_e.de.view.data_size = cpu_to_le16(sizeof(struct SECURITY_HDR));
sdh_e.de.view.res = 0;
sdh_e.de.size = cpu_to_le16(SIZEOF_SDH_DIRENTRY);
sdh_e.de.key_size = cpu_to_le16(sizeof(sdh_e.key));
sdh_e.de.flags = 0;
sdh_e.de.res = 0;
sdh_e.key.hash = d_security->key.hash;
sdh_e.key.sec_id = d_security->key.sec_id;
memcpy(&sdh_e.sec_hdr, d_security, sizeof(struct SECURITY_HDR));
sdh_e.magic[0] = cpu_to_le16('I');
sdh_e.magic[1] = cpu_to_le16('I');
fnd_clear(fnd_sdh);
err = indx_insert_entry(indx_sdh, ni, &sdh_e.de, (void *)(size_t)1,
fnd_sdh, 0);
if (err)
goto out;
*security_id = d_security->key.sec_id;
if (inserted)
*inserted = true;
/* Update Id and offset for next descriptor. */
sbi->security.next_id += 1;
sbi->security.next_off += aligned_sec_size;
out:
fnd_put(fnd_sdh);
mark_inode_dirty(&ni->vfs_inode);
ni_unlock(ni);
kfree(d_security);
return err;
}
/*
* ntfs_reparse_init - Load and parse $Extend/$Reparse.
*/
int ntfs_reparse_init(struct ntfs_sb_info *sbi)
{
int err;
struct ntfs_inode *ni = sbi->reparse.ni;
struct ntfs_index *indx = &sbi->reparse.index_r;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
const struct INDEX_ROOT *root_r;
if (!ni)
return 0;
le = NULL;
attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SR_NAME,
ARRAY_SIZE(SR_NAME), NULL, NULL);
if (!attr) {
err = -EINVAL;
goto out;
}
root_r = resident_data(attr);
if (root_r->type != ATTR_ZERO ||
root_r->rule != NTFS_COLLATION_TYPE_UINTS) {
err = -EINVAL;
goto out;
}
err = indx_init(indx, sbi, attr, INDEX_MUTEX_SR);
if (err)
goto out;
out:
return err;
}
/*
* ntfs_objid_init - Load and parse $Extend/$ObjId.
*/
int ntfs_objid_init(struct ntfs_sb_info *sbi)
{
int err;
struct ntfs_inode *ni = sbi->objid.ni;
struct ntfs_index *indx = &sbi->objid.index_o;
struct ATTRIB *attr;
struct ATTR_LIST_ENTRY *le;
const struct INDEX_ROOT *root;
if (!ni)
return 0;
le = NULL;
attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SO_NAME,
ARRAY_SIZE(SO_NAME), NULL, NULL);
if (!attr) {
err = -EINVAL;
goto out;
}
root = resident_data(attr);
if (root->type != ATTR_ZERO ||
root->rule != NTFS_COLLATION_TYPE_UINTS) {
err = -EINVAL;
goto out;
}
err = indx_init(indx, sbi, attr, INDEX_MUTEX_SO);
if (err)
goto out;
out:
return err;
}
int ntfs_objid_remove(struct ntfs_sb_info *sbi, struct GUID *guid)
{
int err;
struct ntfs_inode *ni = sbi->objid.ni;
struct ntfs_index *indx = &sbi->objid.index_o;
if (!ni)
return -EINVAL;
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_OBJID);
err = indx_delete_entry(indx, ni, guid, sizeof(*guid), NULL);
mark_inode_dirty(&ni->vfs_inode);
ni_unlock(ni);
return err;
}
int ntfs_insert_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
const struct MFT_REF *ref)
{
int err;
struct ntfs_inode *ni = sbi->reparse.ni;
struct ntfs_index *indx = &sbi->reparse.index_r;
struct NTFS_DE_R re;
if (!ni)
return -EINVAL;
memset(&re, 0, sizeof(re));
re.de.view.data_off = cpu_to_le16(offsetof(struct NTFS_DE_R, zero));
re.de.size = cpu_to_le16(sizeof(struct NTFS_DE_R));
re.de.key_size = cpu_to_le16(sizeof(re.key));
re.key.ReparseTag = rtag;
memcpy(&re.key.ref, ref, sizeof(*ref));
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
err = indx_insert_entry(indx, ni, &re.de, NULL, NULL, 0);
mark_inode_dirty(&ni->vfs_inode);
ni_unlock(ni);
return err;
}
int ntfs_remove_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
const struct MFT_REF *ref)
{
int err, diff;
struct ntfs_inode *ni = sbi->reparse.ni;
struct ntfs_index *indx = &sbi->reparse.index_r;
struct ntfs_fnd *fnd = NULL;
struct REPARSE_KEY rkey;
struct NTFS_DE_R *re;
struct INDEX_ROOT *root_r;
if (!ni)
return -EINVAL;
rkey.ReparseTag = rtag;
rkey.ref = *ref;
mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
if (rtag) {
err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
goto out1;
}
fnd = fnd_get();
if (!fnd) {
err = -ENOMEM;
goto out1;
}
root_r = indx_get_root(indx, ni, NULL, NULL);
if (!root_r) {
err = -EINVAL;
goto out;
}
/* 1 - forces to ignore rkey.ReparseTag when comparing keys. */
err = indx_find(indx, ni, root_r, &rkey, sizeof(rkey), (void *)1, &diff,
(struct NTFS_DE **)&re, fnd);
if (err)
goto out;
if (memcmp(&re->key.ref, ref, sizeof(*ref))) {
/* Impossible. Looks like volume corrupt? */
goto out;
}
memcpy(&rkey, &re->key, sizeof(rkey));
fnd_put(fnd);
fnd = NULL;
err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
if (err)
goto out;
out:
fnd_put(fnd);
out1:
mark_inode_dirty(&ni->vfs_inode);
ni_unlock(ni);
return err;
}
static inline void ntfs_unmap_and_discard(struct ntfs_sb_info *sbi, CLST lcn,
CLST len)
{
ntfs_unmap_meta(sbi->sb, lcn, len);
ntfs_discard(sbi, lcn, len);
}
void mark_as_free_ex(struct ntfs_sb_info *sbi, CLST lcn, CLST len, bool trim)
{
CLST end, i, zone_len, zlen;
struct wnd_bitmap *wnd = &sbi->used.bitmap;
down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
if (!wnd_is_used(wnd, lcn, len)) {
ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
end = lcn + len;
len = 0;
for (i = lcn; i < end; i++) {
if (wnd_is_used(wnd, i, 1)) {
if (!len)
lcn = i;
len += 1;
continue;
}
if (!len)
continue;
if (trim)
ntfs_unmap_and_discard(sbi, lcn, len);
wnd_set_free(wnd, lcn, len);
len = 0;
}
if (!len)
goto out;
}
if (trim)
ntfs_unmap_and_discard(sbi, lcn, len);
wnd_set_free(wnd, lcn, len);
/* append to MFT zone, if possible. */
zone_len = wnd_zone_len(wnd);
zlen = min(zone_len + len, sbi->zone_max);
if (zlen == zone_len) {
/* MFT zone already has maximum size. */
} else if (!zone_len) {
/* Create MFT zone only if 'zlen' is large enough. */
if (zlen == sbi->zone_max)
wnd_zone_set(wnd, lcn, zlen);
} else {
CLST zone_lcn = wnd_zone_bit(wnd);
if (lcn + len == zone_lcn) {
/* Append into head MFT zone. */
wnd_zone_set(wnd, lcn, zlen);
} else if (zone_lcn + zone_len == lcn) {
/* Append into tail MFT zone. */
wnd_zone_set(wnd, zone_lcn, zlen);
}
}
out:
up_write(&wnd->rw_lock);
}
/*
* run_deallocate - Deallocate clusters.
*/
int run_deallocate(struct ntfs_sb_info *sbi, const struct runs_tree *run,
bool trim)
{
CLST lcn, len;
size_t idx = 0;
while (run_get_entry(run, idx++, NULL, &lcn, &len)) {
if (lcn == SPARSE_LCN)
continue;
mark_as_free_ex(sbi, lcn, len, trim);
}
return 0;
}
static inline bool name_has_forbidden_chars(const struct le_str *fname)
{
int i, ch;
/* check for forbidden chars */
for (i = 0; i < fname->len; ++i) {
ch = le16_to_cpu(fname->name[i]);
/* control chars */
if (ch < 0x20)
return true;
switch (ch) {
/* disallowed by Windows */
case '\\':
case '/':
case ':':
case '*':
case '?':
case '<':
case '>':
case '|':
case '\"':
return true;
default:
/* allowed char */
break;
}
}
/* file names cannot end with space or . */
if (fname->len > 0) {
ch = le16_to_cpu(fname->name[fname->len - 1]);
if (ch == ' ' || ch == '.')
return true;
}
return false;
}
static inline bool is_reserved_name(const struct ntfs_sb_info *sbi,
const struct le_str *fname)
{
int port_digit;
const __le16 *name = fname->name;
int len = fname->len;
const u16 *upcase = sbi->upcase;
/* check for 3 chars reserved names (device names) */
/* name by itself or with any extension is forbidden */
if (len == 3 || (len > 3 && le16_to_cpu(name[3]) == '.'))
if (!ntfs_cmp_names(name, 3, CON_NAME, 3, upcase, false) ||
!ntfs_cmp_names(name, 3, NUL_NAME, 3, upcase, false) ||
!ntfs_cmp_names(name, 3, AUX_NAME, 3, upcase, false) ||
!ntfs_cmp_names(name, 3, PRN_NAME, 3, upcase, false))
return true;
/* check for 4 chars reserved names (port name followed by 1..9) */
/* name by itself or with any extension is forbidden */
if (len == 4 || (len > 4 && le16_to_cpu(name[4]) == '.')) {
port_digit = le16_to_cpu(name[3]);
if (port_digit >= '1' && port_digit <= '9')
if (!ntfs_cmp_names(name, 3, COM_NAME, 3, upcase,
false) ||
!ntfs_cmp_names(name, 3, LPT_NAME, 3, upcase,
false))
return true;
}
return false;
}
/*
* valid_windows_name - Check if a file name is valid in Windows.
*/
bool valid_windows_name(struct ntfs_sb_info *sbi, const struct le_str *fname)
{
return !name_has_forbidden_chars(fname) &&
!is_reserved_name(sbi, fname);
}
/*
* ntfs_set_label - updates current ntfs label.
*/
int ntfs_set_label(struct ntfs_sb_info *sbi, u8 *label, int len)
{
int err;
struct ATTRIB *attr;
struct ntfs_inode *ni = sbi->volume.ni;
const u8 max_ulen = 0x80; /* TODO: use attrdef to get maximum length */
/* Allocate PATH_MAX bytes. */
struct cpu_str *uni = __getname();
if (!uni)
return -ENOMEM;
err = ntfs_nls_to_utf16(sbi, label, len, uni, (PATH_MAX - 2) / 2,
UTF16_LITTLE_ENDIAN);
if (err < 0)
goto out;
if (uni->len > max_ulen) {
ntfs_warn(sbi->sb, "new label is too long");
err = -EFBIG;
goto out;
}
ni_lock(ni);
/* Ignore any errors. */
ni_remove_attr(ni, ATTR_LABEL, NULL, 0, false, NULL);
err = ni_insert_resident(ni, uni->len * sizeof(u16), ATTR_LABEL, NULL,
0, &attr, NULL, NULL);
if (err < 0)
goto unlock_out;
/* write new label in on-disk struct. */
memcpy(resident_data(attr), uni->name, uni->len * sizeof(u16));
/* update cached value of current label. */
if (len >= ARRAY_SIZE(sbi->volume.label))
len = ARRAY_SIZE(sbi->volume.label) - 1;
memcpy(sbi->volume.label, label, len);
sbi->volume.label[len] = 0;
mark_inode_dirty_sync(&ni->vfs_inode);
unlock_out:
ni_unlock(ni);
if (!err)
err = _ni_write_inode(&ni->vfs_inode, 0);
out:
__putname(uni);
return err;
} | linux-master | fs/ntfs3/fsntfs.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
* Regular file handling primitives for NTFS-based filesystems.
*
*/
#include <linux/backing-dev.h>
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/compat.h>
#include <linux/falloc.h>
#include <linux/fiemap.h>
#include "debug.h"
#include "ntfs.h"
#include "ntfs_fs.h"
static int ntfs_ioctl_fitrim(struct ntfs_sb_info *sbi, unsigned long arg)
{
struct fstrim_range __user *user_range;
struct fstrim_range range;
struct block_device *dev;
int err;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
dev = sbi->sb->s_bdev;
if (!bdev_max_discard_sectors(dev))
return -EOPNOTSUPP;
user_range = (struct fstrim_range __user *)arg;
if (copy_from_user(&range, user_range, sizeof(range)))
return -EFAULT;
range.minlen = max_t(u32, range.minlen, bdev_discard_granularity(dev));
err = ntfs_trim_fs(sbi, &range);
if (err < 0)
return err;
if (copy_to_user(user_range, &range, sizeof(range)))
return -EFAULT;
return 0;
}
static long ntfs_ioctl(struct file *filp, u32 cmd, unsigned long arg)
{
struct inode *inode = file_inode(filp);
struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
switch (cmd) {
case FITRIM:
return ntfs_ioctl_fitrim(sbi, arg);
}
return -ENOTTY; /* Inappropriate ioctl for device. */
}
#ifdef CONFIG_COMPAT
static long ntfs_compat_ioctl(struct file *filp, u32 cmd, unsigned long arg)
{
return ntfs_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
}
#endif
/*
* ntfs_getattr - inode_operations::getattr
*/
int ntfs_getattr(struct mnt_idmap *idmap, const struct path *path,
struct kstat *stat, u32 request_mask, u32 flags)
{
struct inode *inode = d_inode(path->dentry);
struct ntfs_inode *ni = ntfs_i(inode);
if (is_compressed(ni))
stat->attributes |= STATX_ATTR_COMPRESSED;
if (is_encrypted(ni))
stat->attributes |= STATX_ATTR_ENCRYPTED;
stat->attributes_mask |= STATX_ATTR_COMPRESSED | STATX_ATTR_ENCRYPTED;
generic_fillattr(idmap, request_mask, inode, stat);
stat->result_mask |= STATX_BTIME;
stat->btime = ni->i_crtime;
stat->blksize = ni->mi.sbi->cluster_size; /* 512, 1K, ..., 2M */
return 0;
}
static int ntfs_extend_initialized_size(struct file *file,
struct ntfs_inode *ni,
const loff_t valid,
const loff_t new_valid)
{
struct inode *inode = &ni->vfs_inode;
struct address_space *mapping = inode->i_mapping;
struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
loff_t pos = valid;
int err;
if (is_resident(ni)) {
ni->i_valid = new_valid;
return 0;
}
WARN_ON(is_compressed(ni));
WARN_ON(valid >= new_valid);
for (;;) {
u32 zerofrom, len;
struct page *page;
u8 bits;
CLST vcn, lcn, clen;
if (is_sparsed(ni)) {
bits = sbi->cluster_bits;
vcn = pos >> bits;
err = attr_data_get_block(ni, vcn, 1, &lcn, &clen, NULL,
false);
if (err)
goto out;
if (lcn == SPARSE_LCN) {
pos = ((loff_t)clen + vcn) << bits;
ni->i_valid = pos;
goto next;
}
}
zerofrom = pos & (PAGE_SIZE - 1);
len = PAGE_SIZE - zerofrom;
if (pos + len > new_valid)
len = new_valid - pos;
err = ntfs_write_begin(file, mapping, pos, len, &page, NULL);
if (err)
goto out;
zero_user_segment(page, zerofrom, PAGE_SIZE);
/* This function in any case puts page. */
err = ntfs_write_end(file, mapping, pos, len, len, page, NULL);
if (err < 0)
goto out;
pos += len;
next:
if (pos >= new_valid)
break;
balance_dirty_pages_ratelimited(mapping);
cond_resched();
}
return 0;
out:
ni->i_valid = valid;
ntfs_inode_warn(inode, "failed to extend initialized size to %llx.",
new_valid);
return err;
}
/*
* ntfs_zero_range - Helper function for punch_hole.
*
* It zeroes a range [vbo, vbo_to).
*/
static int ntfs_zero_range(struct inode *inode, u64 vbo, u64 vbo_to)
{
int err = 0;
struct address_space *mapping = inode->i_mapping;
u32 blocksize = i_blocksize(inode);
pgoff_t idx = vbo >> PAGE_SHIFT;
u32 from = vbo & (PAGE_SIZE - 1);
pgoff_t idx_end = (vbo_to + PAGE_SIZE - 1) >> PAGE_SHIFT;
loff_t page_off;
struct buffer_head *head, *bh;
u32 bh_next, bh_off, to;
sector_t iblock;
struct page *page;
for (; idx < idx_end; idx += 1, from = 0) {
page_off = (loff_t)idx << PAGE_SHIFT;
to = (page_off + PAGE_SIZE) > vbo_to ? (vbo_to - page_off) :
PAGE_SIZE;
iblock = page_off >> inode->i_blkbits;
page = find_or_create_page(mapping, idx,
mapping_gfp_constraint(mapping,
~__GFP_FS));
if (!page)
return -ENOMEM;
if (!page_has_buffers(page))
create_empty_buffers(page, blocksize, 0);
bh = head = page_buffers(page);
bh_off = 0;
do {
bh_next = bh_off + blocksize;
if (bh_next <= from || bh_off >= to)
continue;
if (!buffer_mapped(bh)) {
ntfs_get_block(inode, iblock, bh, 0);
/* Unmapped? It's a hole - nothing to do. */
if (!buffer_mapped(bh))
continue;
}
/* Ok, it's mapped. Make sure it's up-to-date. */
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
err = bh_read(bh, 0);
if (err < 0) {
unlock_page(page);
put_page(page);
goto out;
}
}
mark_buffer_dirty(bh);
} while (bh_off = bh_next, iblock += 1,
head != (bh = bh->b_this_page));
zero_user_segment(page, from, to);
unlock_page(page);
put_page(page);
cond_resched();
}
out:
mark_inode_dirty(inode);
return err;
}
/*
* ntfs_file_mmap - file_operations::mmap
*/
static int ntfs_file_mmap(struct file *file, struct vm_area_struct *vma)
{
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
u64 from = ((u64)vma->vm_pgoff << PAGE_SHIFT);
bool rw = vma->vm_flags & VM_WRITE;
int err;
if (is_encrypted(ni)) {
ntfs_inode_warn(inode, "mmap encrypted not supported");
return -EOPNOTSUPP;
}
if (is_dedup(ni)) {
ntfs_inode_warn(inode, "mmap deduplicated not supported");
return -EOPNOTSUPP;
}
if (is_compressed(ni) && rw) {
ntfs_inode_warn(inode, "mmap(write) compressed not supported");
return -EOPNOTSUPP;
}
if (rw) {
u64 to = min_t(loff_t, i_size_read(inode),
from + vma->vm_end - vma->vm_start);
if (is_sparsed(ni)) {
/* Allocate clusters for rw map. */
struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
CLST lcn, len;
CLST vcn = from >> sbi->cluster_bits;
CLST end = bytes_to_cluster(sbi, to);
bool new;
for (; vcn < end; vcn += len) {
err = attr_data_get_block(ni, vcn, 1, &lcn,
&len, &new, true);
if (err)
goto out;
}
}
if (ni->i_valid < to) {
if (!inode_trylock(inode)) {
err = -EAGAIN;
goto out;
}
err = ntfs_extend_initialized_size(file, ni,
ni->i_valid, to);
inode_unlock(inode);
if (err)
goto out;
}
}
err = generic_file_mmap(file, vma);
out:
return err;
}
static int ntfs_extend(struct inode *inode, loff_t pos, size_t count,
struct file *file)
{
struct ntfs_inode *ni = ntfs_i(inode);
struct address_space *mapping = inode->i_mapping;
loff_t end = pos + count;
bool extend_init = file && pos > ni->i_valid;
int err;
if (end <= inode->i_size && !extend_init)
return 0;
/* Mark rw ntfs as dirty. It will be cleared at umount. */
ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_DIRTY);
if (end > inode->i_size) {
err = ntfs_set_size(inode, end);
if (err)
goto out;
}
if (extend_init && !is_compressed(ni)) {
err = ntfs_extend_initialized_size(file, ni, ni->i_valid, pos);
if (err)
goto out;
} else {
err = 0;
}
inode->i_mtime = inode_set_ctime_current(inode);
mark_inode_dirty(inode);
if (IS_SYNC(inode)) {
int err2;
err = filemap_fdatawrite_range(mapping, pos, end - 1);
err2 = sync_mapping_buffers(mapping);
if (!err)
err = err2;
err2 = write_inode_now(inode, 1);
if (!err)
err = err2;
if (!err)
err = filemap_fdatawait_range(mapping, pos, end - 1);
}
out:
return err;
}
static int ntfs_truncate(struct inode *inode, loff_t new_size)
{
struct super_block *sb = inode->i_sb;
struct ntfs_inode *ni = ntfs_i(inode);
int err, dirty = 0;
u64 new_valid;
if (!S_ISREG(inode->i_mode))
return 0;
if (is_compressed(ni)) {
if (ni->i_valid > new_size)
ni->i_valid = new_size;
} else {
err = block_truncate_page(inode->i_mapping, new_size,
ntfs_get_block);
if (err)
return err;
}
new_valid = ntfs_up_block(sb, min_t(u64, ni->i_valid, new_size));
truncate_setsize(inode, new_size);
ni_lock(ni);
down_write(&ni->file.run_lock);
err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run, new_size,
&new_valid, ni->mi.sbi->options->prealloc, NULL);
up_write(&ni->file.run_lock);
if (new_valid < ni->i_valid)
ni->i_valid = new_valid;
ni_unlock(ni);
ni->std_fa |= FILE_ATTRIBUTE_ARCHIVE;
inode->i_mtime = inode_set_ctime_current(inode);
if (!IS_DIRSYNC(inode)) {
dirty = 1;
} else {
err = ntfs_sync_inode(inode);
if (err)
return err;
}
if (dirty)
mark_inode_dirty(inode);
/*ntfs_flush_inodes(inode->i_sb, inode, NULL);*/
return 0;
}
/*
* ntfs_fallocate
*
* Preallocate space for a file. This implements ntfs's fallocate file
* operation, which gets called from sys_fallocate system call. User
* space requests 'len' bytes at 'vbo'. If FALLOC_FL_KEEP_SIZE is set
* we just allocate clusters without zeroing them out. Otherwise we
* allocate and zero out clusters via an expanding truncate.
*/
static long ntfs_fallocate(struct file *file, int mode, loff_t vbo, loff_t len)
{
struct inode *inode = file->f_mapping->host;
struct address_space *mapping = inode->i_mapping;
struct super_block *sb = inode->i_sb;
struct ntfs_sb_info *sbi = sb->s_fs_info;
struct ntfs_inode *ni = ntfs_i(inode);
loff_t end = vbo + len;
loff_t vbo_down = round_down(vbo, max_t(unsigned long,
sbi->cluster_size, PAGE_SIZE));
bool is_supported_holes = is_sparsed(ni) || is_compressed(ni);
loff_t i_size, new_size;
bool map_locked;
int err;
/* No support for dir. */
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
/*
* vfs_fallocate checks all possible combinations of mode.
* Do additional checks here before ntfs_set_state(dirty).
*/
if (mode & FALLOC_FL_PUNCH_HOLE) {
if (!is_supported_holes)
return -EOPNOTSUPP;
} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
} else if (mode & FALLOC_FL_INSERT_RANGE) {
if (!is_supported_holes)
return -EOPNOTSUPP;
} else if (mode &
~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)) {
ntfs_inode_warn(inode, "fallocate(0x%x) is not supported",
mode);
return -EOPNOTSUPP;
}
ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
inode_lock(inode);
i_size = inode->i_size;
new_size = max(end, i_size);
map_locked = false;
if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
/* Should never be here, see ntfs_file_open. */
err = -EOPNOTSUPP;
goto out;
}
if (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE |
FALLOC_FL_INSERT_RANGE)) {
inode_dio_wait(inode);
filemap_invalidate_lock(mapping);
map_locked = true;
}
if (mode & FALLOC_FL_PUNCH_HOLE) {
u32 frame_size;
loff_t mask, vbo_a, end_a, tmp;
err = filemap_write_and_wait_range(mapping, vbo_down,
LLONG_MAX);
if (err)
goto out;
truncate_pagecache(inode, vbo_down);
ni_lock(ni);
err = attr_punch_hole(ni, vbo, len, &frame_size);
ni_unlock(ni);
if (err != E_NTFS_NOTALIGNED)
goto out;
/* Process not aligned punch. */
mask = frame_size - 1;
vbo_a = (vbo + mask) & ~mask;
end_a = end & ~mask;
tmp = min(vbo_a, end);
if (tmp > vbo) {
err = ntfs_zero_range(inode, vbo, tmp);
if (err)
goto out;
}
if (vbo < end_a && end_a < end) {
err = ntfs_zero_range(inode, end_a, end);
if (err)
goto out;
}
/* Aligned punch_hole */
if (end_a > vbo_a) {
ni_lock(ni);
err = attr_punch_hole(ni, vbo_a, end_a - vbo_a, NULL);
ni_unlock(ni);
}
} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
/*
* Write tail of the last page before removed range since
* it will get removed from the page cache below.
*/
err = filemap_write_and_wait_range(mapping, vbo_down, vbo);
if (err)
goto out;
/*
* Write data that will be shifted to preserve them
* when discarding page cache below.
*/
err = filemap_write_and_wait_range(mapping, end, LLONG_MAX);
if (err)
goto out;
truncate_pagecache(inode, vbo_down);
ni_lock(ni);
err = attr_collapse_range(ni, vbo, len);
ni_unlock(ni);
} else if (mode & FALLOC_FL_INSERT_RANGE) {
/* Check new size. */
err = inode_newsize_ok(inode, new_size);
if (err)
goto out;
/* Write out all dirty pages. */
err = filemap_write_and_wait_range(mapping, vbo_down,
LLONG_MAX);
if (err)
goto out;
truncate_pagecache(inode, vbo_down);
ni_lock(ni);
err = attr_insert_range(ni, vbo, len);
ni_unlock(ni);
} else {
/* Check new size. */
u8 cluster_bits = sbi->cluster_bits;
/* generic/213: expected -ENOSPC instead of -EFBIG. */
if (!is_supported_holes) {
loff_t to_alloc = new_size - inode_get_bytes(inode);
if (to_alloc > 0 &&
(to_alloc >> cluster_bits) >
wnd_zeroes(&sbi->used.bitmap)) {
err = -ENOSPC;
goto out;
}
}
err = inode_newsize_ok(inode, new_size);
if (err)
goto out;
if (new_size > i_size) {
/*
* Allocate clusters, do not change 'valid' size.
*/
err = ntfs_set_size(inode, new_size);
if (err)
goto out;
}
if (is_supported_holes) {
CLST vcn = vbo >> cluster_bits;
CLST cend = bytes_to_cluster(sbi, end);
CLST cend_v = bytes_to_cluster(sbi, ni->i_valid);
CLST lcn, clen;
bool new;
if (cend_v > cend)
cend_v = cend;
/*
* Allocate and zero new clusters.
* Zeroing these clusters may be too long.
*/
for (; vcn < cend_v; vcn += clen) {
err = attr_data_get_block(ni, vcn, cend_v - vcn,
&lcn, &clen, &new,
true);
if (err)
goto out;
}
/*
* Allocate but not zero new clusters.
*/
for (; vcn < cend; vcn += clen) {
err = attr_data_get_block(ni, vcn, cend - vcn,
&lcn, &clen, &new,
false);
if (err)
goto out;
}
}
if (mode & FALLOC_FL_KEEP_SIZE) {
ni_lock(ni);
/* True - Keep preallocated. */
err = attr_set_size(ni, ATTR_DATA, NULL, 0,
&ni->file.run, i_size, &ni->i_valid,
true, NULL);
ni_unlock(ni);
} else if (new_size > i_size) {
inode->i_size = new_size;
}
}
out:
if (map_locked)
filemap_invalidate_unlock(mapping);
if (!err) {
inode->i_mtime = inode_set_ctime_current(inode);
mark_inode_dirty(inode);
}
inode_unlock(inode);
return err;
}
/*
* ntfs3_setattr - inode_operations::setattr
*/
int ntfs3_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
struct iattr *attr)
{
struct inode *inode = d_inode(dentry);
struct ntfs_inode *ni = ntfs_i(inode);
u32 ia_valid = attr->ia_valid;
umode_t mode = inode->i_mode;
int err;
err = setattr_prepare(idmap, dentry, attr);
if (err)
goto out;
if (ia_valid & ATTR_SIZE) {
loff_t newsize, oldsize;
if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
/* Should never be here, see ntfs_file_open(). */
err = -EOPNOTSUPP;
goto out;
}
inode_dio_wait(inode);
oldsize = inode->i_size;
newsize = attr->ia_size;
if (newsize <= oldsize)
err = ntfs_truncate(inode, newsize);
else
err = ntfs_extend(inode, newsize, 0, NULL);
if (err)
goto out;
ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
inode->i_size = newsize;
}
setattr_copy(idmap, inode, attr);
if (mode != inode->i_mode) {
err = ntfs_acl_chmod(idmap, dentry);
if (err)
goto out;
/* Linux 'w' -> Windows 'ro'. */
if (0222 & inode->i_mode)
ni->std_fa &= ~FILE_ATTRIBUTE_READONLY;
else
ni->std_fa |= FILE_ATTRIBUTE_READONLY;
}
if (ia_valid & (ATTR_UID | ATTR_GID | ATTR_MODE))
ntfs_save_wsl_perm(inode, NULL);
mark_inode_dirty(inode);
out:
return err;
}
static ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
if (is_encrypted(ni)) {
ntfs_inode_warn(inode, "encrypted i/o not supported");
return -EOPNOTSUPP;
}
if (is_compressed(ni) && (iocb->ki_flags & IOCB_DIRECT)) {
ntfs_inode_warn(inode, "direct i/o + compressed not supported");
return -EOPNOTSUPP;
}
#ifndef CONFIG_NTFS3_LZX_XPRESS
if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
ntfs_inode_warn(
inode,
"activate CONFIG_NTFS3_LZX_XPRESS to read external compressed files");
return -EOPNOTSUPP;
}
#endif
if (is_dedup(ni)) {
ntfs_inode_warn(inode, "read deduplicated not supported");
return -EOPNOTSUPP;
}
return generic_file_read_iter(iocb, iter);
}
static ssize_t ntfs_file_splice_read(struct file *in, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len, unsigned int flags)
{
struct inode *inode = in->f_mapping->host;
struct ntfs_inode *ni = ntfs_i(inode);
if (is_encrypted(ni)) {
ntfs_inode_warn(inode, "encrypted i/o not supported");
return -EOPNOTSUPP;
}
#ifndef CONFIG_NTFS3_LZX_XPRESS
if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
ntfs_inode_warn(
inode,
"activate CONFIG_NTFS3_LZX_XPRESS to read external compressed files");
return -EOPNOTSUPP;
}
#endif
if (is_dedup(ni)) {
ntfs_inode_warn(inode, "read deduplicated not supported");
return -EOPNOTSUPP;
}
return filemap_splice_read(in, ppos, pipe, len, flags);
}
/*
* ntfs_get_frame_pages
*
* Return: Array of locked pages.
*/
static int ntfs_get_frame_pages(struct address_space *mapping, pgoff_t index,
struct page **pages, u32 pages_per_frame,
bool *frame_uptodate)
{
gfp_t gfp_mask = mapping_gfp_mask(mapping);
u32 npages;
*frame_uptodate = true;
for (npages = 0; npages < pages_per_frame; npages++, index++) {
struct page *page;
page = find_or_create_page(mapping, index, gfp_mask);
if (!page) {
while (npages--) {
page = pages[npages];
unlock_page(page);
put_page(page);
}
return -ENOMEM;
}
if (!PageUptodate(page))
*frame_uptodate = false;
pages[npages] = page;
}
return 0;
}
/*
* ntfs_compress_write - Helper for ntfs_file_write_iter() (compressed files).
*/
static ssize_t ntfs_compress_write(struct kiocb *iocb, struct iov_iter *from)
{
int err;
struct file *file = iocb->ki_filp;
size_t count = iov_iter_count(from);
loff_t pos = iocb->ki_pos;
struct inode *inode = file_inode(file);
loff_t i_size = inode->i_size;
struct address_space *mapping = inode->i_mapping;
struct ntfs_inode *ni = ntfs_i(inode);
u64 valid = ni->i_valid;
struct ntfs_sb_info *sbi = ni->mi.sbi;
struct page *page, **pages = NULL;
size_t written = 0;
u8 frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
u32 frame_size = 1u << frame_bits;
u32 pages_per_frame = frame_size >> PAGE_SHIFT;
u32 ip, off;
CLST frame;
u64 frame_vbo;
pgoff_t index;
bool frame_uptodate;
if (frame_size < PAGE_SIZE) {
/*
* frame_size == 8K if cluster 512
* frame_size == 64K if cluster 4096
*/
ntfs_inode_warn(inode, "page size is bigger than frame size");
return -EOPNOTSUPP;
}
pages = kmalloc_array(pages_per_frame, sizeof(struct page *), GFP_NOFS);
if (!pages)
return -ENOMEM;
err = file_remove_privs(file);
if (err)
goto out;
err = file_update_time(file);
if (err)
goto out;
/* Zero range [valid : pos). */
while (valid < pos) {
CLST lcn, clen;
frame = valid >> frame_bits;
frame_vbo = valid & ~(frame_size - 1);
off = valid & (frame_size - 1);
err = attr_data_get_block(ni, frame << NTFS_LZNT_CUNIT, 1, &lcn,
&clen, NULL, false);
if (err)
goto out;
if (lcn == SPARSE_LCN) {
ni->i_valid = valid =
frame_vbo + ((u64)clen << sbi->cluster_bits);
continue;
}
/* Load full frame. */
err = ntfs_get_frame_pages(mapping, frame_vbo >> PAGE_SHIFT,
pages, pages_per_frame,
&frame_uptodate);
if (err)
goto out;
if (!frame_uptodate && off) {
err = ni_read_frame(ni, frame_vbo, pages,
pages_per_frame);
if (err) {
for (ip = 0; ip < pages_per_frame; ip++) {
page = pages[ip];
unlock_page(page);
put_page(page);
}
goto out;
}
}
ip = off >> PAGE_SHIFT;
off = offset_in_page(valid);
for (; ip < pages_per_frame; ip++, off = 0) {
page = pages[ip];
zero_user_segment(page, off, PAGE_SIZE);
flush_dcache_page(page);
SetPageUptodate(page);
}
ni_lock(ni);
err = ni_write_frame(ni, pages, pages_per_frame);
ni_unlock(ni);
for (ip = 0; ip < pages_per_frame; ip++) {
page = pages[ip];
SetPageUptodate(page);
unlock_page(page);
put_page(page);
}
if (err)
goto out;
ni->i_valid = valid = frame_vbo + frame_size;
}
/* Copy user data [pos : pos + count). */
while (count) {
size_t copied, bytes;
off = pos & (frame_size - 1);
bytes = frame_size - off;
if (bytes > count)
bytes = count;
frame_vbo = pos & ~(frame_size - 1);
index = frame_vbo >> PAGE_SHIFT;
if (unlikely(fault_in_iov_iter_readable(from, bytes))) {
err = -EFAULT;
goto out;
}
/* Load full frame. */
err = ntfs_get_frame_pages(mapping, index, pages,
pages_per_frame, &frame_uptodate);
if (err)
goto out;
if (!frame_uptodate) {
loff_t to = pos + bytes;
if (off || (to < i_size && (to & (frame_size - 1)))) {
err = ni_read_frame(ni, frame_vbo, pages,
pages_per_frame);
if (err) {
for (ip = 0; ip < pages_per_frame;
ip++) {
page = pages[ip];
unlock_page(page);
put_page(page);
}
goto out;
}
}
}
WARN_ON(!bytes);
copied = 0;
ip = off >> PAGE_SHIFT;
off = offset_in_page(pos);
/* Copy user data to pages. */
for (;;) {
size_t cp, tail = PAGE_SIZE - off;
page = pages[ip];
cp = copy_page_from_iter_atomic(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;
}
}
ni_lock(ni);
err = ni_write_frame(ni, pages, pages_per_frame);
ni_unlock(ni);
for (ip = 0; ip < pages_per_frame; ip++) {
page = pages[ip];
ClearPageDirty(page);
SetPageUptodate(page);
unlock_page(page);
put_page(page);
}
if (err)
goto out;
/*
* We can loop for a long time in here. Be nice and allow
* us to schedule out to avoid softlocking if preempt
* is disabled.
*/
cond_resched();
pos += copied;
written += copied;
count = iov_iter_count(from);
}
out:
kfree(pages);
if (err < 0)
return err;
iocb->ki_pos += written;
if (iocb->ki_pos > ni->i_valid)
ni->i_valid = iocb->ki_pos;
return written;
}
/*
* ntfs_file_write_iter - file_operations::write_iter
*/
static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t ret;
struct ntfs_inode *ni = ntfs_i(inode);
if (is_encrypted(ni)) {
ntfs_inode_warn(inode, "encrypted i/o not supported");
return -EOPNOTSUPP;
}
if (is_compressed(ni) && (iocb->ki_flags & IOCB_DIRECT)) {
ntfs_inode_warn(inode, "direct i/o + compressed not supported");
return -EOPNOTSUPP;
}
if (is_dedup(ni)) {
ntfs_inode_warn(inode, "write into deduplicated not supported");
return -EOPNOTSUPP;
}
if (!inode_trylock(inode)) {
if (iocb->ki_flags & IOCB_NOWAIT)
return -EAGAIN;
inode_lock(inode);
}
ret = generic_write_checks(iocb, from);
if (ret <= 0)
goto out;
if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
/* Should never be here, see ntfs_file_open(). */
ret = -EOPNOTSUPP;
goto out;
}
ret = ntfs_extend(inode, iocb->ki_pos, ret, file);
if (ret)
goto out;
ret = is_compressed(ni) ? ntfs_compress_write(iocb, from) :
__generic_file_write_iter(iocb, from);
out:
inode_unlock(inode);
if (ret > 0)
ret = generic_write_sync(iocb, ret);
return ret;
}
/*
* ntfs_file_open - file_operations::open
*/
int ntfs_file_open(struct inode *inode, struct file *file)
{
struct ntfs_inode *ni = ntfs_i(inode);
if (unlikely((is_compressed(ni) || is_encrypted(ni)) &&
(file->f_flags & O_DIRECT))) {
return -EOPNOTSUPP;
}
/* Decompress "external compressed" file if opened for rw. */
if ((ni->ni_flags & NI_FLAG_COMPRESSED_MASK) &&
(file->f_flags & (O_WRONLY | O_RDWR | O_TRUNC))) {
#ifdef CONFIG_NTFS3_LZX_XPRESS
int err = ni_decompress_file(ni);
if (err)
return err;
#else
ntfs_inode_warn(
inode,
"activate CONFIG_NTFS3_LZX_XPRESS to write external compressed files");
return -EOPNOTSUPP;
#endif
}
return generic_file_open(inode, file);
}
/*
* ntfs_file_release - file_operations::release
*/
static int ntfs_file_release(struct inode *inode, struct file *file)
{
struct ntfs_inode *ni = ntfs_i(inode);
struct ntfs_sb_info *sbi = ni->mi.sbi;
int err = 0;
/* If we are last writer on the inode, drop the block reservation. */
if (sbi->options->prealloc &&
((file->f_mode & FMODE_WRITE) &&
atomic_read(&inode->i_writecount) == 1)) {
ni_lock(ni);
down_write(&ni->file.run_lock);
err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run,
inode->i_size, &ni->i_valid, false, NULL);
up_write(&ni->file.run_lock);
ni_unlock(ni);
}
return err;
}
/*
* ntfs_fiemap - file_operations::fiemap
*/
int ntfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
int err;
struct ntfs_inode *ni = ntfs_i(inode);
err = fiemap_prep(inode, fieinfo, start, &len, ~FIEMAP_FLAG_XATTR);
if (err)
return err;
ni_lock(ni);
err = ni_fiemap(ni, fieinfo, start, len);
ni_unlock(ni);
return err;
}
// clang-format off
const struct inode_operations ntfs_file_inode_operations = {
.getattr = ntfs_getattr,
.setattr = ntfs3_setattr,
.listxattr = ntfs_listxattr,
.get_acl = ntfs_get_acl,
.set_acl = ntfs_set_acl,
.fiemap = ntfs_fiemap,
};
const struct file_operations ntfs_file_operations = {
.llseek = generic_file_llseek,
.read_iter = ntfs_file_read_iter,
.write_iter = ntfs_file_write_iter,
.unlocked_ioctl = ntfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ntfs_compat_ioctl,
#endif
.splice_read = ntfs_file_splice_read,
.mmap = ntfs_file_mmap,
.open = ntfs_file_open,
.fsync = generic_file_fsync,
.splice_write = iter_file_splice_write,
.fallocate = ntfs_fallocate,
.release = ntfs_file_release,
};
// clang-format on
| linux-master | fs/ntfs3/file.c |
// SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include "ntfs_fs.h"
static inline u16 upcase_unicode_char(const u16 *upcase, u16 chr)
{
if (chr < 'a')
return chr;
if (chr <= 'z')
return chr - ('a' - 'A');
return upcase[chr];
}
/*
* ntfs_cmp_names
*
* Thanks Kari Argillander <[email protected]> for idea and implementation 'bothcase'
*
* Straight way to compare names:
* - Case insensitive
* - If name equals and 'bothcases' then
* - Case sensitive
* 'Straight way' code scans input names twice in worst case.
* Optimized code scans input names only once.
*/
int ntfs_cmp_names(const __le16 *s1, size_t l1, const __le16 *s2, size_t l2,
const u16 *upcase, bool bothcase)
{
int diff1 = 0;
int diff2;
size_t len = min(l1, l2);
if (!bothcase && upcase)
goto case_insentive;
for (; len; s1++, s2++, len--) {
diff1 = le16_to_cpu(*s1) - le16_to_cpu(*s2);
if (diff1) {
if (bothcase && upcase)
goto case_insentive;
return diff1;
}
}
return l1 - l2;
case_insentive:
for (; len; s1++, s2++, len--) {
diff2 = upcase_unicode_char(upcase, le16_to_cpu(*s1)) -
upcase_unicode_char(upcase, le16_to_cpu(*s2));
if (diff2)
return diff2;
}
diff2 = l1 - l2;
return diff2 ? diff2 : diff1;
}
int ntfs_cmp_names_cpu(const struct cpu_str *uni1, const struct le_str *uni2,
const u16 *upcase, bool bothcase)
{
const u16 *s1 = uni1->name;
const __le16 *s2 = uni2->name;
size_t l1 = uni1->len;
size_t l2 = uni2->len;
size_t len = min(l1, l2);
int diff1 = 0;
int diff2;
if (!bothcase && upcase)
goto case_insentive;
for (; len; s1++, s2++, len--) {
diff1 = *s1 - le16_to_cpu(*s2);
if (diff1) {
if (bothcase && upcase)
goto case_insentive;
return diff1;
}
}
return l1 - l2;
case_insentive:
for (; len; s1++, s2++, len--) {
diff2 = upcase_unicode_char(upcase, *s1) -
upcase_unicode_char(upcase, le16_to_cpu(*s2));
if (diff2)
return diff2;
}
diff2 = l1 - l2;
return diff2 ? diff2 : diff1;
}
/* Helper function for ntfs_d_hash. */
unsigned long ntfs_names_hash(const u16 *name, size_t len, const u16 *upcase,
unsigned long hash)
{
while (len--) {
unsigned int c = upcase_unicode_char(upcase, *name++);
hash = partial_name_hash(c, hash);
}
return hash;
}
| linux-master | fs/ntfs3/upcase.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* lzx_decompress.c - A decompressor for the LZX compression format, which can
* be used in "System Compressed" files. This is based on the code from wimlib.
* This code only supports a window size (dictionary size) of 32768 bytes, since
* this is the only size used in System Compression.
*
* Copyright (C) 2015 Eric Biggers
*/
#include "decompress_common.h"
#include "lib.h"
/* Number of literal byte values */
#define LZX_NUM_CHARS 256
/* The smallest and largest allowed match lengths */
#define LZX_MIN_MATCH_LEN 2
#define LZX_MAX_MATCH_LEN 257
/* Number of distinct match lengths that can be represented */
#define LZX_NUM_LENS (LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1)
/* Number of match lengths for which no length symbol is required */
#define LZX_NUM_PRIMARY_LENS 7
#define LZX_NUM_LEN_HEADERS (LZX_NUM_PRIMARY_LENS + 1)
/* Valid values of the 3-bit block type field */
#define LZX_BLOCKTYPE_VERBATIM 1
#define LZX_BLOCKTYPE_ALIGNED 2
#define LZX_BLOCKTYPE_UNCOMPRESSED 3
/* Number of offset slots for a window size of 32768 */
#define LZX_NUM_OFFSET_SLOTS 30
/* Number of symbols in the main code for a window size of 32768 */
#define LZX_MAINCODE_NUM_SYMBOLS \
(LZX_NUM_CHARS + (LZX_NUM_OFFSET_SLOTS * LZX_NUM_LEN_HEADERS))
/* Number of symbols in the length code */
#define LZX_LENCODE_NUM_SYMBOLS (LZX_NUM_LENS - LZX_NUM_PRIMARY_LENS)
/* Number of symbols in the precode */
#define LZX_PRECODE_NUM_SYMBOLS 20
/* Number of bits in which each precode codeword length is represented */
#define LZX_PRECODE_ELEMENT_SIZE 4
/* Number of low-order bits of each match offset that are entropy-encoded in
* aligned offset blocks
*/
#define LZX_NUM_ALIGNED_OFFSET_BITS 3
/* Number of symbols in the aligned offset code */
#define LZX_ALIGNEDCODE_NUM_SYMBOLS (1 << LZX_NUM_ALIGNED_OFFSET_BITS)
/* Mask for the match offset bits that are entropy-encoded in aligned offset
* blocks
*/
#define LZX_ALIGNED_OFFSET_BITMASK ((1 << LZX_NUM_ALIGNED_OFFSET_BITS) - 1)
/* Number of bits in which each aligned offset codeword length is represented */
#define LZX_ALIGNEDCODE_ELEMENT_SIZE 3
/* Maximum lengths (in bits) of the codewords in each Huffman code */
#define LZX_MAX_MAIN_CODEWORD_LEN 16
#define LZX_MAX_LEN_CODEWORD_LEN 16
#define LZX_MAX_PRE_CODEWORD_LEN ((1 << LZX_PRECODE_ELEMENT_SIZE) - 1)
#define LZX_MAX_ALIGNED_CODEWORD_LEN ((1 << LZX_ALIGNEDCODE_ELEMENT_SIZE) - 1)
/* The default "filesize" value used in pre/post-processing. In the LZX format
* used in cabinet files this value must be given to the decompressor, whereas
* in the LZX format used in WIM files and system-compressed files this value is
* fixed at 12000000.
*/
#define LZX_DEFAULT_FILESIZE 12000000
/* Assumed block size when the encoded block size begins with a 0 bit. */
#define LZX_DEFAULT_BLOCK_SIZE 32768
/* Number of offsets in the recent (or "repeat") offsets queue. */
#define LZX_NUM_RECENT_OFFSETS 3
/* These values are chosen for fast decompression. */
#define LZX_MAINCODE_TABLEBITS 11
#define LZX_LENCODE_TABLEBITS 10
#define LZX_PRECODE_TABLEBITS 6
#define LZX_ALIGNEDCODE_TABLEBITS 7
#define LZX_READ_LENS_MAX_OVERRUN 50
/* Mapping: offset slot => first match offset that uses that offset slot.
*/
static const u32 lzx_offset_slot_base[LZX_NUM_OFFSET_SLOTS + 1] = {
0, 1, 2, 3, 4, /* 0 --- 4 */
6, 8, 12, 16, 24, /* 5 --- 9 */
32, 48, 64, 96, 128, /* 10 --- 14 */
192, 256, 384, 512, 768, /* 15 --- 19 */
1024, 1536, 2048, 3072, 4096, /* 20 --- 24 */
6144, 8192, 12288, 16384, 24576, /* 25 --- 29 */
32768, /* extra */
};
/* Mapping: offset slot => how many extra bits must be read and added to the
* corresponding offset slot base to decode the match offset.
*/
static const u8 lzx_extra_offset_bits[LZX_NUM_OFFSET_SLOTS] = {
0, 0, 0, 0, 1,
1, 2, 2, 3, 3,
4, 4, 5, 5, 6,
6, 7, 7, 8, 8,
9, 9, 10, 10, 11,
11, 12, 12, 13, 13,
};
/* Reusable heap-allocated memory for LZX decompression */
struct lzx_decompressor {
/* Huffman decoding tables, and arrays that map symbols to codeword
* lengths
*/
u16 maincode_decode_table[(1 << LZX_MAINCODE_TABLEBITS) +
(LZX_MAINCODE_NUM_SYMBOLS * 2)];
u8 maincode_lens[LZX_MAINCODE_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
u16 lencode_decode_table[(1 << LZX_LENCODE_TABLEBITS) +
(LZX_LENCODE_NUM_SYMBOLS * 2)];
u8 lencode_lens[LZX_LENCODE_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
u16 alignedcode_decode_table[(1 << LZX_ALIGNEDCODE_TABLEBITS) +
(LZX_ALIGNEDCODE_NUM_SYMBOLS * 2)];
u8 alignedcode_lens[LZX_ALIGNEDCODE_NUM_SYMBOLS];
u16 precode_decode_table[(1 << LZX_PRECODE_TABLEBITS) +
(LZX_PRECODE_NUM_SYMBOLS * 2)];
u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
/* Temporary space for make_huffman_decode_table() */
u16 working_space[2 * (1 + LZX_MAX_MAIN_CODEWORD_LEN) +
LZX_MAINCODE_NUM_SYMBOLS];
};
static void undo_e8_translation(void *target, s32 input_pos)
{
s32 abs_offset, rel_offset;
abs_offset = get_unaligned_le32(target);
if (abs_offset >= 0) {
if (abs_offset < LZX_DEFAULT_FILESIZE) {
/* "good translation" */
rel_offset = abs_offset - input_pos;
put_unaligned_le32(rel_offset, target);
}
} else {
if (abs_offset >= -input_pos) {
/* "compensating translation" */
rel_offset = abs_offset + LZX_DEFAULT_FILESIZE;
put_unaligned_le32(rel_offset, target);
}
}
}
/*
* Undo the 'E8' preprocessing used in LZX. Before compression, the
* uncompressed data was preprocessed by changing the targets of suspected x86
* CALL instructions from relative offsets to absolute offsets. After
* match/literal decoding, the decompressor must undo the translation.
*/
static void lzx_postprocess(u8 *data, u32 size)
{
/*
* A worthwhile optimization is to push the end-of-buffer check into the
* relatively rare E8 case. This is possible if we replace the last six
* bytes of data with E8 bytes; then we are guaranteed to hit an E8 byte
* before reaching end-of-buffer. In addition, this scheme guarantees
* that no translation can begin following an E8 byte in the last 10
* bytes because a 4-byte offset containing E8 as its high byte is a
* large negative number that is not valid for translation. That is
* exactly what we need.
*/
u8 *tail;
u8 saved_bytes[6];
u8 *p;
if (size <= 10)
return;
tail = &data[size - 6];
memcpy(saved_bytes, tail, 6);
memset(tail, 0xE8, 6);
p = data;
for (;;) {
while (*p != 0xE8)
p++;
if (p >= tail)
break;
undo_e8_translation(p + 1, p - data);
p += 5;
}
memcpy(tail, saved_bytes, 6);
}
/* Read a Huffman-encoded symbol using the precode. */
static forceinline u32 read_presym(const struct lzx_decompressor *d,
struct input_bitstream *is)
{
return read_huffsym(is, d->precode_decode_table,
LZX_PRECODE_TABLEBITS, LZX_MAX_PRE_CODEWORD_LEN);
}
/* Read a Huffman-encoded symbol using the main code. */
static forceinline u32 read_mainsym(const struct lzx_decompressor *d,
struct input_bitstream *is)
{
return read_huffsym(is, d->maincode_decode_table,
LZX_MAINCODE_TABLEBITS, LZX_MAX_MAIN_CODEWORD_LEN);
}
/* Read a Huffman-encoded symbol using the length code. */
static forceinline u32 read_lensym(const struct lzx_decompressor *d,
struct input_bitstream *is)
{
return read_huffsym(is, d->lencode_decode_table,
LZX_LENCODE_TABLEBITS, LZX_MAX_LEN_CODEWORD_LEN);
}
/* Read a Huffman-encoded symbol using the aligned offset code. */
static forceinline u32 read_alignedsym(const struct lzx_decompressor *d,
struct input_bitstream *is)
{
return read_huffsym(is, d->alignedcode_decode_table,
LZX_ALIGNEDCODE_TABLEBITS,
LZX_MAX_ALIGNED_CODEWORD_LEN);
}
/*
* Read the precode from the compressed input bitstream, then use it to decode
* @num_lens codeword length values.
*
* @is: The input bitstream.
*
* @lens: An array that contains the length values from the previous time
* the codeword lengths for this Huffman code were read, or all 0's
* if this is the first time. This array must have at least
* (@num_lens + LZX_READ_LENS_MAX_OVERRUN) entries.
*
* @num_lens: Number of length values to decode.
*
* Returns 0 on success, or -1 if the data was invalid.
*/
static int lzx_read_codeword_lens(struct lzx_decompressor *d,
struct input_bitstream *is,
u8 *lens, u32 num_lens)
{
u8 *len_ptr = lens;
u8 *lens_end = lens + num_lens;
int i;
/* Read the lengths of the precode codewords. These are given
* explicitly.
*/
for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++) {
d->precode_lens[i] =
bitstream_read_bits(is, LZX_PRECODE_ELEMENT_SIZE);
}
/* Make the decoding table for the precode. */
if (make_huffman_decode_table(d->precode_decode_table,
LZX_PRECODE_NUM_SYMBOLS,
LZX_PRECODE_TABLEBITS,
d->precode_lens,
LZX_MAX_PRE_CODEWORD_LEN,
d->working_space))
return -1;
/* Decode the codeword lengths. */
do {
u32 presym;
u8 len;
/* Read the next precode symbol. */
presym = read_presym(d, is);
if (presym < 17) {
/* Difference from old length */
len = *len_ptr - presym;
if ((s8)len < 0)
len += 17;
*len_ptr++ = len;
} else {
/* Special RLE values */
u32 run_len;
if (presym == 17) {
/* Run of 0's */
run_len = 4 + bitstream_read_bits(is, 4);
len = 0;
} else if (presym == 18) {
/* Longer run of 0's */
run_len = 20 + bitstream_read_bits(is, 5);
len = 0;
} else {
/* Run of identical lengths */
run_len = 4 + bitstream_read_bits(is, 1);
presym = read_presym(d, is);
if (presym > 17)
return -1;
len = *len_ptr - presym;
if ((s8)len < 0)
len += 17;
}
do {
*len_ptr++ = len;
} while (--run_len);
/* Worst case overrun is when presym == 18,
* run_len == 20 + 31, and only 1 length was remaining.
* So LZX_READ_LENS_MAX_OVERRUN == 50.
*
* Overrun while reading the first half of maincode_lens
* can corrupt the previous values in the second half.
* This doesn't really matter because the resulting
* lengths will still be in range, and data that
* generates overruns is invalid anyway.
*/
}
} while (len_ptr < lens_end);
return 0;
}
/*
* Read the header of an LZX block and save the block type and (uncompressed)
* size in *block_type_ret and *block_size_ret, respectively.
*
* If the block is compressed, also update the Huffman decode @tables with the
* new Huffman codes. If the block is uncompressed, also update the match
* offset @queue with the new match offsets.
*
* Return 0 on success, or -1 if the data was invalid.
*/
static int lzx_read_block_header(struct lzx_decompressor *d,
struct input_bitstream *is,
int *block_type_ret,
u32 *block_size_ret,
u32 recent_offsets[])
{
int block_type;
u32 block_size;
int i;
bitstream_ensure_bits(is, 4);
/* The first three bits tell us what kind of block it is, and should be
* one of the LZX_BLOCKTYPE_* values.
*/
block_type = bitstream_pop_bits(is, 3);
/* Read the block size. */
if (bitstream_pop_bits(is, 1)) {
block_size = LZX_DEFAULT_BLOCK_SIZE;
} else {
block_size = 0;
block_size |= bitstream_read_bits(is, 8);
block_size <<= 8;
block_size |= bitstream_read_bits(is, 8);
}
switch (block_type) {
case LZX_BLOCKTYPE_ALIGNED:
/* Read the aligned offset code and prepare its decode table.
*/
for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
d->alignedcode_lens[i] =
bitstream_read_bits(is,
LZX_ALIGNEDCODE_ELEMENT_SIZE);
}
if (make_huffman_decode_table(d->alignedcode_decode_table,
LZX_ALIGNEDCODE_NUM_SYMBOLS,
LZX_ALIGNEDCODE_TABLEBITS,
d->alignedcode_lens,
LZX_MAX_ALIGNED_CODEWORD_LEN,
d->working_space))
return -1;
/* Fall though, since the rest of the header for aligned offset
* blocks is the same as that for verbatim blocks.
*/
fallthrough;
case LZX_BLOCKTYPE_VERBATIM:
/* Read the main code and prepare its decode table.
*
* Note that the codeword lengths in the main code are encoded
* in two parts: one part for literal symbols, and one part for
* match symbols.
*/
if (lzx_read_codeword_lens(d, is, d->maincode_lens,
LZX_NUM_CHARS))
return -1;
if (lzx_read_codeword_lens(d, is,
d->maincode_lens + LZX_NUM_CHARS,
LZX_MAINCODE_NUM_SYMBOLS - LZX_NUM_CHARS))
return -1;
if (make_huffman_decode_table(d->maincode_decode_table,
LZX_MAINCODE_NUM_SYMBOLS,
LZX_MAINCODE_TABLEBITS,
d->maincode_lens,
LZX_MAX_MAIN_CODEWORD_LEN,
d->working_space))
return -1;
/* Read the length code and prepare its decode table. */
if (lzx_read_codeword_lens(d, is, d->lencode_lens,
LZX_LENCODE_NUM_SYMBOLS))
return -1;
if (make_huffman_decode_table(d->lencode_decode_table,
LZX_LENCODE_NUM_SYMBOLS,
LZX_LENCODE_TABLEBITS,
d->lencode_lens,
LZX_MAX_LEN_CODEWORD_LEN,
d->working_space))
return -1;
break;
case LZX_BLOCKTYPE_UNCOMPRESSED:
/* Before reading the three recent offsets from the uncompressed
* block header, the stream must be aligned on a 16-bit
* boundary. But if the stream is *already* aligned, then the
* next 16 bits must be discarded.
*/
bitstream_ensure_bits(is, 1);
bitstream_align(is);
recent_offsets[0] = bitstream_read_u32(is);
recent_offsets[1] = bitstream_read_u32(is);
recent_offsets[2] = bitstream_read_u32(is);
/* Offsets of 0 are invalid. */
if (recent_offsets[0] == 0 || recent_offsets[1] == 0 ||
recent_offsets[2] == 0)
return -1;
break;
default:
/* Unrecognized block type. */
return -1;
}
*block_type_ret = block_type;
*block_size_ret = block_size;
return 0;
}
/* Decompress a block of LZX-compressed data. */
static int lzx_decompress_block(const struct lzx_decompressor *d,
struct input_bitstream *is,
int block_type, u32 block_size,
u8 * const out_begin, u8 *out_next,
u32 recent_offsets[])
{
u8 * const block_end = out_next + block_size;
u32 ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
do {
u32 mainsym;
u32 match_len;
u32 match_offset;
u32 offset_slot;
u32 num_extra_bits;
mainsym = read_mainsym(d, is);
if (mainsym < LZX_NUM_CHARS) {
/* Literal */
*out_next++ = mainsym;
continue;
}
/* Match */
/* Decode the length header and offset slot. */
mainsym -= LZX_NUM_CHARS;
match_len = mainsym % LZX_NUM_LEN_HEADERS;
offset_slot = mainsym / LZX_NUM_LEN_HEADERS;
/* If needed, read a length symbol to decode the full length. */
if (match_len == LZX_NUM_PRIMARY_LENS)
match_len += read_lensym(d, is);
match_len += LZX_MIN_MATCH_LEN;
if (offset_slot < LZX_NUM_RECENT_OFFSETS) {
/* Repeat offset */
/* Note: This isn't a real LRU queue, since using the R2
* offset doesn't bump the R1 offset down to R2. This
* quirk allows all 3 recent offsets to be handled by
* the same code. (For R0, the swap is a no-op.)
*/
match_offset = recent_offsets[offset_slot];
recent_offsets[offset_slot] = recent_offsets[0];
recent_offsets[0] = match_offset;
} else {
/* Explicit offset */
/* Look up the number of extra bits that need to be read
* to decode offsets with this offset slot.
*/
num_extra_bits = lzx_extra_offset_bits[offset_slot];
/* Start with the offset slot base value. */
match_offset = lzx_offset_slot_base[offset_slot];
/* In aligned offset blocks, the low-order 3 bits of
* each offset are encoded using the aligned offset
* code. Otherwise, all the extra bits are literal.
*/
if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
match_offset +=
bitstream_read_bits(is, num_extra_bits -
LZX_NUM_ALIGNED_OFFSET_BITS)
<< LZX_NUM_ALIGNED_OFFSET_BITS;
match_offset += read_alignedsym(d, is);
} else {
match_offset += bitstream_read_bits(is, num_extra_bits);
}
/* Adjust the offset. */
match_offset -= (LZX_NUM_RECENT_OFFSETS - 1);
/* Update the recent offsets. */
recent_offsets[2] = recent_offsets[1];
recent_offsets[1] = recent_offsets[0];
recent_offsets[0] = match_offset;
}
/* Validate the match, then copy it to the current position. */
if (match_len > (size_t)(block_end - out_next))
return -1;
if (match_offset > (size_t)(out_next - out_begin))
return -1;
out_next = lz_copy(out_next, match_len, match_offset,
block_end, LZX_MIN_MATCH_LEN);
} while (out_next != block_end);
return 0;
}
/*
* lzx_allocate_decompressor - Allocate an LZX decompressor
*
* Return the pointer to the decompressor on success, or return NULL and set
* errno on failure.
*/
struct lzx_decompressor *lzx_allocate_decompressor(void)
{
return kmalloc(sizeof(struct lzx_decompressor), GFP_NOFS);
}
/*
* lzx_decompress - Decompress a buffer of LZX-compressed data
*
* @decompressor: A decompressor allocated with lzx_allocate_decompressor()
* @compressed_data: The buffer of data to decompress
* @compressed_size: Number of bytes of compressed data
* @uncompressed_data: The buffer in which to store the decompressed data
* @uncompressed_size: The number of bytes the data decompresses into
*
* Return 0 on success, or return -1 and set errno on failure.
*/
int lzx_decompress(struct lzx_decompressor *decompressor,
const void *compressed_data, size_t compressed_size,
void *uncompressed_data, size_t uncompressed_size)
{
struct lzx_decompressor *d = decompressor;
u8 * const out_begin = uncompressed_data;
u8 *out_next = out_begin;
u8 * const out_end = out_begin + uncompressed_size;
struct input_bitstream is;
u32 recent_offsets[LZX_NUM_RECENT_OFFSETS] = {1, 1, 1};
int e8_status = 0;
init_input_bitstream(&is, compressed_data, compressed_size);
/* Codeword lengths begin as all 0's for delta encoding purposes. */
memset(d->maincode_lens, 0, LZX_MAINCODE_NUM_SYMBOLS);
memset(d->lencode_lens, 0, LZX_LENCODE_NUM_SYMBOLS);
/* Decompress blocks until we have all the uncompressed data. */
while (out_next != out_end) {
int block_type;
u32 block_size;
if (lzx_read_block_header(d, &is, &block_type, &block_size,
recent_offsets))
goto invalid;
if (block_size < 1 || block_size > (size_t)(out_end - out_next))
goto invalid;
if (block_type != LZX_BLOCKTYPE_UNCOMPRESSED) {
/* Compressed block */
if (lzx_decompress_block(d,
&is,
block_type,
block_size,
out_begin,
out_next,
recent_offsets))
goto invalid;
e8_status |= d->maincode_lens[0xe8];
out_next += block_size;
} else {
/* Uncompressed block */
out_next = bitstream_read_bytes(&is, out_next,
block_size);
if (!out_next)
goto invalid;
if (block_size & 1)
bitstream_read_byte(&is);
e8_status = 1;
}
}
/* Postprocess the data unless it cannot possibly contain 0xe8 bytes. */
if (e8_status)
lzx_postprocess(uncompressed_data, uncompressed_size);
return 0;
invalid:
return -1;
}
/*
* lzx_free_decompressor - Free an LZX decompressor
*
* @decompressor: A decompressor that was allocated with
* lzx_allocate_decompressor(), or NULL.
*/
void lzx_free_decompressor(struct lzx_decompressor *decompressor)
{
kfree(decompressor);
}
| linux-master | fs/ntfs3/lib/lzx_decompress.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* xpress_decompress.c - A decompressor for the XPRESS compression format
* (Huffman variant), which can be used in "System Compressed" files. This is
* based on the code from wimlib.
*
* Copyright (C) 2015 Eric Biggers
*/
#include "decompress_common.h"
#include "lib.h"
#define XPRESS_NUM_SYMBOLS 512
#define XPRESS_MAX_CODEWORD_LEN 15
#define XPRESS_MIN_MATCH_LEN 3
/* This value is chosen for fast decompression. */
#define XPRESS_TABLEBITS 12
/* Reusable heap-allocated memory for XPRESS decompression */
struct xpress_decompressor {
/* The Huffman decoding table */
u16 decode_table[(1 << XPRESS_TABLEBITS) + 2 * XPRESS_NUM_SYMBOLS];
/* An array that maps symbols to codeword lengths */
u8 lens[XPRESS_NUM_SYMBOLS];
/* Temporary space for make_huffman_decode_table() */
u16 working_space[2 * (1 + XPRESS_MAX_CODEWORD_LEN) +
XPRESS_NUM_SYMBOLS];
};
/*
* xpress_allocate_decompressor - Allocate an XPRESS decompressor
*
* Return the pointer to the decompressor on success, or return NULL and set
* errno on failure.
*/
struct xpress_decompressor *xpress_allocate_decompressor(void)
{
return kmalloc(sizeof(struct xpress_decompressor), GFP_NOFS);
}
/*
* xpress_decompress - Decompress a buffer of XPRESS-compressed data
*
* @decompressor: A decompressor that was allocated with
* xpress_allocate_decompressor()
* @compressed_data: The buffer of data to decompress
* @compressed_size: Number of bytes of compressed data
* @uncompressed_data: The buffer in which to store the decompressed data
* @uncompressed_size: The number of bytes the data decompresses into
*
* Return 0 on success, or return -1 and set errno on failure.
*/
int xpress_decompress(struct xpress_decompressor *decompressor,
const void *compressed_data, size_t compressed_size,
void *uncompressed_data, size_t uncompressed_size)
{
struct xpress_decompressor *d = decompressor;
const u8 * const in_begin = compressed_data;
u8 * const out_begin = uncompressed_data;
u8 *out_next = out_begin;
u8 * const out_end = out_begin + uncompressed_size;
struct input_bitstream is;
u32 i;
/* Read the Huffman codeword lengths. */
if (compressed_size < XPRESS_NUM_SYMBOLS / 2)
goto invalid;
for (i = 0; i < XPRESS_NUM_SYMBOLS / 2; i++) {
d->lens[i*2 + 0] = in_begin[i] & 0xF;
d->lens[i*2 + 1] = in_begin[i] >> 4;
}
/* Build a decoding table for the Huffman code. */
if (make_huffman_decode_table(d->decode_table, XPRESS_NUM_SYMBOLS,
XPRESS_TABLEBITS, d->lens,
XPRESS_MAX_CODEWORD_LEN,
d->working_space))
goto invalid;
/* Decode the matches and literals. */
init_input_bitstream(&is, in_begin + XPRESS_NUM_SYMBOLS / 2,
compressed_size - XPRESS_NUM_SYMBOLS / 2);
while (out_next != out_end) {
u32 sym;
u32 log2_offset;
u32 length;
u32 offset;
sym = read_huffsym(&is, d->decode_table,
XPRESS_TABLEBITS, XPRESS_MAX_CODEWORD_LEN);
if (sym < 256) {
/* Literal */
*out_next++ = sym;
} else {
/* Match */
length = sym & 0xf;
log2_offset = (sym >> 4) & 0xf;
bitstream_ensure_bits(&is, 16);
offset = ((u32)1 << log2_offset) |
bitstream_pop_bits(&is, log2_offset);
if (length == 0xf) {
length += bitstream_read_byte(&is);
if (length == 0xf + 0xff)
length = bitstream_read_u16(&is);
}
length += XPRESS_MIN_MATCH_LEN;
if (offset > (size_t)(out_next - out_begin))
goto invalid;
if (length > (size_t)(out_end - out_next))
goto invalid;
out_next = lz_copy(out_next, length, offset, out_end,
XPRESS_MIN_MATCH_LEN);
}
}
return 0;
invalid:
return -1;
}
/*
* xpress_free_decompressor - Free an XPRESS decompressor
*
* @decompressor: A decompressor that was allocated with
* xpress_allocate_decompressor(), or NULL.
*/
void xpress_free_decompressor(struct xpress_decompressor *decompressor)
{
kfree(decompressor);
}
| linux-master | fs/ntfs3/lib/xpress_decompress.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* decompress_common.c - Code shared by the XPRESS and LZX decompressors
*
* Copyright (C) 2015 Eric Biggers
*/
#include "decompress_common.h"
/*
* make_huffman_decode_table() -
*
* Build a decoding table for a canonical prefix code, or "Huffman code".
*
* This is an internal function, not part of the library API!
*
* This takes as input the length of the codeword for each symbol in the
* alphabet and produces as output a table that can be used for fast
* decoding of prefix-encoded symbols using read_huffsym().
*
* Strictly speaking, a canonical prefix code might not be a Huffman
* code. But this algorithm will work either way; and in fact, since
* Huffman codes are defined in terms of symbol frequencies, there is no
* way for the decompressor to know whether the code is a true Huffman
* code or not until all symbols have been decoded.
*
* Because the prefix code is assumed to be "canonical", it can be
* reconstructed directly from the codeword lengths. A prefix code is
* canonical if and only if a longer codeword never lexicographically
* precedes a shorter codeword, and the lexicographic ordering of
* codewords of the same length is the same as the lexicographic ordering
* of the corresponding symbols. Consequently, we can sort the symbols
* primarily by codeword length and secondarily by symbol value, then
* reconstruct the prefix code by generating codewords lexicographically
* in that order.
*
* This function does not, however, generate the prefix code explicitly.
* Instead, it directly builds a table for decoding symbols using the
* code. The basic idea is this: given the next 'max_codeword_len' bits
* in the input, we can look up the decoded symbol by indexing a table
* containing 2**max_codeword_len entries. A codeword with length
* 'max_codeword_len' will have exactly one entry in this table, whereas
* a codeword shorter than 'max_codeword_len' will have multiple entries
* in this table. Precisely, a codeword of length n will be represented
* by 2**(max_codeword_len - n) entries in this table. The 0-based index
* of each such entry will contain the corresponding codeword as a prefix
* when zero-padded on the left to 'max_codeword_len' binary digits.
*
* That's the basic idea, but we implement two optimizations regarding
* the format of the decode table itself:
*
* - For many compression formats, the maximum codeword length is too
* long for it to be efficient to build the full decoding table
* whenever a new prefix code is used. Instead, we can build the table
* using only 2**table_bits entries, where 'table_bits' is some number
* less than or equal to 'max_codeword_len'. Then, only codewords of
* length 'table_bits' and shorter can be directly looked up. For
* longer codewords, the direct lookup instead produces the root of a
* binary tree. Using this tree, the decoder can do traditional
* bit-by-bit decoding of the remainder of the codeword. Child nodes
* are allocated in extra entries at the end of the table; leaf nodes
* contain symbols. Note that the long-codeword case is, in general,
* not performance critical, since in Huffman codes the most frequently
* used symbols are assigned the shortest codeword lengths.
*
* - When we decode a symbol using a direct lookup of the table, we still
* need to know its length so that the bitstream can be advanced by the
* appropriate number of bits. The simple solution is to simply retain
* the 'lens' array and use the decoded symbol as an index into it.
* However, this requires two separate array accesses in the fast path.
* The optimization is to store the length directly in the decode
* table. We use the bottom 11 bits for the symbol and the top 5 bits
* for the length. In addition, to combine this optimization with the
* previous one, we introduce a special case where the top 2 bits of
* the length are both set if the entry is actually the root of a
* binary tree.
*
* @decode_table:
* The array in which to create the decoding table. This must have
* a length of at least ((2**table_bits) + 2 * num_syms) entries.
*
* @num_syms:
* The number of symbols in the alphabet; also, the length of the
* 'lens' array. Must be less than or equal to 2048.
*
* @table_bits:
* The order of the decode table size, as explained above. Must be
* less than or equal to 13.
*
* @lens:
* An array of length @num_syms, indexable by symbol, that gives the
* length of the codeword, in bits, for that symbol. The length can
* be 0, which means that the symbol does not have a codeword
* assigned.
*
* @max_codeword_len:
* The longest codeword length allowed in the compression format.
* All entries in 'lens' must be less than or equal to this value.
* This must be less than or equal to 23.
*
* @working_space
* A temporary array of length '2 * (max_codeword_len + 1) +
* num_syms'.
*
* Returns 0 on success, or -1 if the lengths do not form a valid prefix
* code.
*/
int make_huffman_decode_table(u16 decode_table[], const u32 num_syms,
const u32 table_bits, const u8 lens[],
const u32 max_codeword_len,
u16 working_space[])
{
const u32 table_num_entries = 1 << table_bits;
u16 * const len_counts = &working_space[0];
u16 * const offsets = &working_space[1 * (max_codeword_len + 1)];
u16 * const sorted_syms = &working_space[2 * (max_codeword_len + 1)];
int left;
void *decode_table_ptr;
u32 sym_idx;
u32 codeword_len;
u32 stores_per_loop;
u32 decode_table_pos;
u32 len;
u32 sym;
/* Count how many symbols have each possible codeword length.
* Note that a length of 0 indicates the corresponding symbol is not
* used in the code and therefore does not have a codeword.
*/
for (len = 0; len <= max_codeword_len; len++)
len_counts[len] = 0;
for (sym = 0; sym < num_syms; sym++)
len_counts[lens[sym]]++;
/* We can assume all lengths are <= max_codeword_len, but we
* cannot assume they form a valid prefix code. A codeword of
* length n should require a proportion of the codespace equaling
* (1/2)^n. The code is valid if and only if the codespace is
* exactly filled by the lengths, by this measure.
*/
left = 1;
for (len = 1; len <= max_codeword_len; len++) {
left <<= 1;
left -= len_counts[len];
if (left < 0) {
/* The lengths overflow the codespace; that is, the code
* is over-subscribed.
*/
return -1;
}
}
if (left) {
/* The lengths do not fill the codespace; that is, they form an
* incomplete set.
*/
if (left == (1 << max_codeword_len)) {
/* The code is completely empty. This is arguably
* invalid, but in fact it is valid in LZX and XPRESS,
* so we must allow it. By definition, no symbols can
* be decoded with an empty code. Consequently, we
* technically don't even need to fill in the decode
* table. However, to avoid accessing uninitialized
* memory if the algorithm nevertheless attempts to
* decode symbols using such a code, we zero out the
* decode table.
*/
memset(decode_table, 0,
table_num_entries * sizeof(decode_table[0]));
return 0;
}
return -1;
}
/* Sort the symbols primarily by length and secondarily by symbol order.
*/
/* Initialize 'offsets' so that offsets[len] for 1 <= len <=
* max_codeword_len is the number of codewords shorter than 'len' bits.
*/
offsets[1] = 0;
for (len = 1; len < max_codeword_len; len++)
offsets[len + 1] = offsets[len] + len_counts[len];
/* Use the 'offsets' array to sort the symbols. Note that we do not
* include symbols that are not used in the code. Consequently, fewer
* than 'num_syms' entries in 'sorted_syms' may be filled.
*/
for (sym = 0; sym < num_syms; sym++)
if (lens[sym])
sorted_syms[offsets[lens[sym]]++] = sym;
/* Fill entries for codewords with length <= table_bits
* --- that is, those short enough for a direct mapping.
*
* The table will start with entries for the shortest codeword(s), which
* have the most entries. From there, the number of entries per
* codeword will decrease.
*/
decode_table_ptr = decode_table;
sym_idx = 0;
codeword_len = 1;
stores_per_loop = (1 << (table_bits - codeword_len));
for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
u32 end_sym_idx = sym_idx + len_counts[codeword_len];
for (; sym_idx < end_sym_idx; sym_idx++) {
u16 entry;
u16 *p;
u32 n;
entry = ((u32)codeword_len << 11) | sorted_syms[sym_idx];
p = (u16 *)decode_table_ptr;
n = stores_per_loop;
do {
*p++ = entry;
} while (--n);
decode_table_ptr = p;
}
}
/* If we've filled in the entire table, we are done. Otherwise,
* there are codewords longer than table_bits for which we must
* generate binary trees.
*/
decode_table_pos = (u16 *)decode_table_ptr - decode_table;
if (decode_table_pos != table_num_entries) {
u32 j;
u32 next_free_tree_slot;
u32 cur_codeword;
/* First, zero out the remaining entries. This is
* necessary so that these entries appear as
* "unallocated" in the next part. Each of these entries
* will eventually be filled with the representation of
* the root node of a binary tree.
*/
j = decode_table_pos;
do {
decode_table[j] = 0;
} while (++j != table_num_entries);
/* We allocate child nodes starting at the end of the
* direct lookup table. Note that there should be
* 2*num_syms extra entries for this purpose, although
* fewer than this may actually be needed.
*/
next_free_tree_slot = table_num_entries;
/* Iterate through each codeword with length greater than
* 'table_bits', primarily in order of codeword length
* and secondarily in order of symbol.
*/
for (cur_codeword = decode_table_pos << 1;
codeword_len <= max_codeword_len;
codeword_len++, cur_codeword <<= 1) {
u32 end_sym_idx = sym_idx + len_counts[codeword_len];
for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++) {
/* 'sorted_sym' is the symbol represented by the
* codeword.
*/
u32 sorted_sym = sorted_syms[sym_idx];
u32 extra_bits = codeword_len - table_bits;
u32 node_idx = cur_codeword >> extra_bits;
/* Go through each bit of the current codeword
* beyond the prefix of length @table_bits and
* walk the appropriate binary tree, allocating
* any slots that have not yet been allocated.
*
* Note that the 'pointer' entry to the binary
* tree, which is stored in the direct lookup
* portion of the table, is represented
* identically to other internal (non-leaf)
* nodes of the binary tree; it can be thought
* of as simply the root of the tree. The
* representation of these internal nodes is
* simply the index of the left child combined
* with the special bits 0xC000 to distinguish
* the entry from direct mapping and leaf node
* entries.
*/
do {
/* At least one bit remains in the
* codeword, but the current node is an
* unallocated leaf. Change it to an
* internal node.
*/
if (decode_table[node_idx] == 0) {
decode_table[node_idx] =
next_free_tree_slot | 0xC000;
decode_table[next_free_tree_slot++] = 0;
decode_table[next_free_tree_slot++] = 0;
}
/* Go to the left child if the next bit
* in the codeword is 0; otherwise go to
* the right child.
*/
node_idx = decode_table[node_idx] & 0x3FFF;
--extra_bits;
node_idx += (cur_codeword >> extra_bits) & 1;
} while (extra_bits != 0);
/* We've traversed the tree using the entire
* codeword, and we're now at the entry where
* the actual symbol will be stored. This is
* distinguished from internal nodes by not
* having its high two bits set.
*/
decode_table[node_idx] = sorted_sym;
}
}
}
return 0;
}
| linux-master | fs/ntfs3/lib/decompress_common.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/bio.h>
#include <linux/sched/signal.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/statfs.h>
#include <linux/seq_file.h>
#include <linux/mount.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/kernel.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "dir.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "recovery.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "util.h"
#include "sys.h"
#include "xattr.h"
#include "lops.h"
enum dinode_demise {
SHOULD_DELETE_DINODE,
SHOULD_NOT_DELETE_DINODE,
SHOULD_DEFER_EVICTION,
};
/**
* gfs2_jindex_free - Clear all the journal index information
* @sdp: The GFS2 superblock
*
*/
void gfs2_jindex_free(struct gfs2_sbd *sdp)
{
struct list_head list;
struct gfs2_jdesc *jd;
spin_lock(&sdp->sd_jindex_spin);
list_add(&list, &sdp->sd_jindex_list);
list_del_init(&sdp->sd_jindex_list);
sdp->sd_journals = 0;
spin_unlock(&sdp->sd_jindex_spin);
sdp->sd_jdesc = NULL;
while (!list_empty(&list)) {
jd = list_first_entry(&list, struct gfs2_jdesc, jd_list);
gfs2_free_journal_extents(jd);
list_del(&jd->jd_list);
iput(jd->jd_inode);
jd->jd_inode = NULL;
kfree(jd);
}
}
static struct gfs2_jdesc *jdesc_find_i(struct list_head *head, unsigned int jid)
{
struct gfs2_jdesc *jd;
list_for_each_entry(jd, head, jd_list) {
if (jd->jd_jid == jid)
return jd;
}
return NULL;
}
struct gfs2_jdesc *gfs2_jdesc_find(struct gfs2_sbd *sdp, unsigned int jid)
{
struct gfs2_jdesc *jd;
spin_lock(&sdp->sd_jindex_spin);
jd = jdesc_find_i(&sdp->sd_jindex_list, jid);
spin_unlock(&sdp->sd_jindex_spin);
return jd;
}
int gfs2_jdesc_check(struct gfs2_jdesc *jd)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
u64 size = i_size_read(jd->jd_inode);
if (gfs2_check_internal_file_size(jd->jd_inode, 8 << 20, BIT(30)))
return -EIO;
jd->jd_blocks = size >> sdp->sd_sb.sb_bsize_shift;
if (gfs2_write_alloc_required(ip, 0, size)) {
gfs2_consist_inode(ip);
return -EIO;
}
return 0;
}
/**
* gfs2_make_fs_rw - Turn a Read-Only FS into a Read-Write one
* @sdp: the filesystem
*
* Returns: errno
*/
int gfs2_make_fs_rw(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_jdesc->jd_inode);
struct gfs2_glock *j_gl = ip->i_gl;
struct gfs2_log_header_host head;
int error;
j_gl->gl_ops->go_inval(j_gl, DIO_METADATA);
if (gfs2_withdrawn(sdp))
return -EIO;
error = gfs2_find_jhead(sdp->sd_jdesc, &head, false);
if (error) {
gfs2_consist(sdp);
return error;
}
if (!(head.lh_flags & GFS2_LOG_HEAD_UNMOUNT)) {
gfs2_consist(sdp);
return -EIO;
}
/* Initialize some head of the log stuff */
sdp->sd_log_sequence = head.lh_sequence + 1;
gfs2_log_pointers_init(sdp, head.lh_blkno);
error = gfs2_quota_init(sdp);
if (!error && gfs2_withdrawn(sdp))
error = -EIO;
if (!error)
set_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags);
return error;
}
void gfs2_statfs_change_in(struct gfs2_statfs_change_host *sc, const void *buf)
{
const struct gfs2_statfs_change *str = buf;
sc->sc_total = be64_to_cpu(str->sc_total);
sc->sc_free = be64_to_cpu(str->sc_free);
sc->sc_dinodes = be64_to_cpu(str->sc_dinodes);
}
void gfs2_statfs_change_out(const struct gfs2_statfs_change_host *sc, void *buf)
{
struct gfs2_statfs_change *str = buf;
str->sc_total = cpu_to_be64(sc->sc_total);
str->sc_free = cpu_to_be64(sc->sc_free);
str->sc_dinodes = cpu_to_be64(sc->sc_dinodes);
}
int gfs2_statfs_init(struct gfs2_sbd *sdp)
{
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct buffer_head *m_bh;
struct gfs2_holder gh;
int error;
error = gfs2_glock_nq_init(m_ip->i_gl, LM_ST_EXCLUSIVE, GL_NOCACHE,
&gh);
if (error)
return error;
error = gfs2_meta_inode_buffer(m_ip, &m_bh);
if (error)
goto out;
if (sdp->sd_args.ar_spectator) {
spin_lock(&sdp->sd_statfs_spin);
gfs2_statfs_change_in(m_sc, m_bh->b_data +
sizeof(struct gfs2_dinode));
spin_unlock(&sdp->sd_statfs_spin);
} else {
spin_lock(&sdp->sd_statfs_spin);
gfs2_statfs_change_in(m_sc, m_bh->b_data +
sizeof(struct gfs2_dinode));
gfs2_statfs_change_in(l_sc, sdp->sd_sc_bh->b_data +
sizeof(struct gfs2_dinode));
spin_unlock(&sdp->sd_statfs_spin);
}
brelse(m_bh);
out:
gfs2_glock_dq_uninit(&gh);
return 0;
}
void gfs2_statfs_change(struct gfs2_sbd *sdp, s64 total, s64 free,
s64 dinodes)
{
struct gfs2_inode *l_ip = GFS2_I(sdp->sd_sc_inode);
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
s64 x, y;
int need_sync = 0;
gfs2_trans_add_meta(l_ip->i_gl, sdp->sd_sc_bh);
spin_lock(&sdp->sd_statfs_spin);
l_sc->sc_total += total;
l_sc->sc_free += free;
l_sc->sc_dinodes += dinodes;
gfs2_statfs_change_out(l_sc, sdp->sd_sc_bh->b_data +
sizeof(struct gfs2_dinode));
if (sdp->sd_args.ar_statfs_percent) {
x = 100 * l_sc->sc_free;
y = m_sc->sc_free * sdp->sd_args.ar_statfs_percent;
if (x >= y || x <= -y)
need_sync = 1;
}
spin_unlock(&sdp->sd_statfs_spin);
if (need_sync)
gfs2_wake_up_statfs(sdp);
}
void update_statfs(struct gfs2_sbd *sdp, struct buffer_head *m_bh)
{
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct gfs2_inode *l_ip = GFS2_I(sdp->sd_sc_inode);
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
gfs2_trans_add_meta(l_ip->i_gl, sdp->sd_sc_bh);
gfs2_trans_add_meta(m_ip->i_gl, m_bh);
spin_lock(&sdp->sd_statfs_spin);
m_sc->sc_total += l_sc->sc_total;
m_sc->sc_free += l_sc->sc_free;
m_sc->sc_dinodes += l_sc->sc_dinodes;
memset(l_sc, 0, sizeof(struct gfs2_statfs_change));
memset(sdp->sd_sc_bh->b_data + sizeof(struct gfs2_dinode),
0, sizeof(struct gfs2_statfs_change));
gfs2_statfs_change_out(m_sc, m_bh->b_data + sizeof(struct gfs2_dinode));
spin_unlock(&sdp->sd_statfs_spin);
}
int gfs2_statfs_sync(struct super_block *sb, int type)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct gfs2_holder gh;
struct buffer_head *m_bh;
int error;
error = gfs2_glock_nq_init(m_ip->i_gl, LM_ST_EXCLUSIVE, GL_NOCACHE,
&gh);
if (error)
goto out;
error = gfs2_meta_inode_buffer(m_ip, &m_bh);
if (error)
goto out_unlock;
spin_lock(&sdp->sd_statfs_spin);
gfs2_statfs_change_in(m_sc, m_bh->b_data +
sizeof(struct gfs2_dinode));
if (!l_sc->sc_total && !l_sc->sc_free && !l_sc->sc_dinodes) {
spin_unlock(&sdp->sd_statfs_spin);
goto out_bh;
}
spin_unlock(&sdp->sd_statfs_spin);
error = gfs2_trans_begin(sdp, 2 * RES_DINODE, 0);
if (error)
goto out_bh;
update_statfs(sdp, m_bh);
sdp->sd_statfs_force_sync = 0;
gfs2_trans_end(sdp);
out_bh:
brelse(m_bh);
out_unlock:
gfs2_glock_dq_uninit(&gh);
out:
return error;
}
struct lfcc {
struct list_head list;
struct gfs2_holder gh;
};
/**
* gfs2_lock_fs_check_clean - Stop all writes to the FS and check that all
* journals are clean
* @sdp: the file system
*
* Returns: errno
*/
static int gfs2_lock_fs_check_clean(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip;
struct gfs2_jdesc *jd;
struct lfcc *lfcc;
LIST_HEAD(list);
struct gfs2_log_header_host lh;
int error, error2;
/*
* Grab all the journal glocks in SH mode. We are *probably* doing
* that to prevent recovery.
*/
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
lfcc = kmalloc(sizeof(struct lfcc), GFP_KERNEL);
if (!lfcc) {
error = -ENOMEM;
goto out;
}
ip = GFS2_I(jd->jd_inode);
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &lfcc->gh);
if (error) {
kfree(lfcc);
goto out;
}
list_add(&lfcc->list, &list);
}
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
error = gfs2_glock_nq_init(sdp->sd_freeze_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NOEXP | GL_NOPID,
&sdp->sd_freeze_gh);
if (error)
goto relock_shared;
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
error = gfs2_jdesc_check(jd);
if (error)
break;
error = gfs2_find_jhead(jd, &lh, false);
if (error)
break;
if (!(lh.lh_flags & GFS2_LOG_HEAD_UNMOUNT)) {
error = -EBUSY;
break;
}
}
if (!error)
goto out; /* success */
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
relock_shared:
error2 = gfs2_freeze_lock_shared(sdp);
gfs2_assert_withdraw(sdp, !error2);
out:
while (!list_empty(&list)) {
lfcc = list_first_entry(&list, struct lfcc, list);
list_del(&lfcc->list);
gfs2_glock_dq_uninit(&lfcc->gh);
kfree(lfcc);
}
return error;
}
void gfs2_dinode_out(const struct gfs2_inode *ip, void *buf)
{
const struct inode *inode = &ip->i_inode;
struct gfs2_dinode *str = buf;
str->di_header.mh_magic = cpu_to_be32(GFS2_MAGIC);
str->di_header.mh_type = cpu_to_be32(GFS2_METATYPE_DI);
str->di_header.mh_format = cpu_to_be32(GFS2_FORMAT_DI);
str->di_num.no_addr = cpu_to_be64(ip->i_no_addr);
str->di_num.no_formal_ino = cpu_to_be64(ip->i_no_formal_ino);
str->di_mode = cpu_to_be32(inode->i_mode);
str->di_uid = cpu_to_be32(i_uid_read(inode));
str->di_gid = cpu_to_be32(i_gid_read(inode));
str->di_nlink = cpu_to_be32(inode->i_nlink);
str->di_size = cpu_to_be64(i_size_read(inode));
str->di_blocks = cpu_to_be64(gfs2_get_inode_blocks(inode));
str->di_atime = cpu_to_be64(inode->i_atime.tv_sec);
str->di_mtime = cpu_to_be64(inode->i_mtime.tv_sec);
str->di_ctime = cpu_to_be64(inode_get_ctime(inode).tv_sec);
str->di_goal_meta = cpu_to_be64(ip->i_goal);
str->di_goal_data = cpu_to_be64(ip->i_goal);
str->di_generation = cpu_to_be64(ip->i_generation);
str->di_flags = cpu_to_be32(ip->i_diskflags);
str->di_height = cpu_to_be16(ip->i_height);
str->di_payload_format = cpu_to_be32(S_ISDIR(inode->i_mode) &&
!(ip->i_diskflags & GFS2_DIF_EXHASH) ?
GFS2_FORMAT_DE : 0);
str->di_depth = cpu_to_be16(ip->i_depth);
str->di_entries = cpu_to_be32(ip->i_entries);
str->di_eattr = cpu_to_be64(ip->i_eattr);
str->di_atime_nsec = cpu_to_be32(inode->i_atime.tv_nsec);
str->di_mtime_nsec = cpu_to_be32(inode->i_mtime.tv_nsec);
str->di_ctime_nsec = cpu_to_be32(inode_get_ctime(inode).tv_nsec);
}
/**
* gfs2_write_inode - Make sure the inode is stable on the disk
* @inode: The inode
* @wbc: The writeback control structure
*
* Returns: errno
*/
static int gfs2_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct address_space *metamapping = gfs2_glock2aspace(ip->i_gl);
struct backing_dev_info *bdi = inode_to_bdi(metamapping->host);
int ret = 0;
bool flush_all = (wbc->sync_mode == WB_SYNC_ALL || gfs2_is_jdata(ip));
if (flush_all)
gfs2_log_flush(GFS2_SB(inode), ip->i_gl,
GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_WRITE_INODE);
if (bdi->wb.dirty_exceeded)
gfs2_ail1_flush(sdp, wbc);
else
filemap_fdatawrite(metamapping);
if (flush_all)
ret = filemap_fdatawait(metamapping);
if (ret)
mark_inode_dirty_sync(inode);
else {
spin_lock(&inode->i_lock);
if (!(inode->i_flags & I_DIRTY))
gfs2_ordered_del_inode(ip);
spin_unlock(&inode->i_lock);
}
return ret;
}
/**
* gfs2_dirty_inode - check for atime updates
* @inode: The inode in question
* @flags: The type of dirty
*
* Unfortunately it can be called under any combination of inode
* glock and freeze glock, so we have to check carefully.
*
* At the moment this deals only with atime - it should be possible
* to expand that role in future, once a review of the locking has
* been carried out.
*/
static void gfs2_dirty_inode(struct inode *inode, int flags)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *bh;
struct gfs2_holder gh;
int need_unlock = 0;
int need_endtrans = 0;
int ret;
if (unlikely(!ip->i_gl)) {
/* This can only happen during incomplete inode creation. */
BUG_ON(!test_bit(GIF_ALLOC_FAILED, &ip->i_flags));
return;
}
if (unlikely(gfs2_withdrawn(sdp)))
return;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (ret) {
fs_err(sdp, "dirty_inode: glock %d\n", ret);
gfs2_dump_glock(NULL, ip->i_gl, true);
return;
}
need_unlock = 1;
} else if (WARN_ON_ONCE(ip->i_gl->gl_state != LM_ST_EXCLUSIVE))
return;
if (current->journal_info == NULL) {
ret = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (ret) {
fs_err(sdp, "dirty_inode: gfs2_trans_begin %d\n", ret);
goto out;
}
need_endtrans = 1;
}
ret = gfs2_meta_inode_buffer(ip, &bh);
if (ret == 0) {
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_dinode_out(ip, bh->b_data);
brelse(bh);
}
if (need_endtrans)
gfs2_trans_end(sdp);
out:
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
}
/**
* gfs2_make_fs_ro - Turn a Read-Write FS into a Read-Only one
* @sdp: the filesystem
*
* Returns: errno
*/
void gfs2_make_fs_ro(struct gfs2_sbd *sdp)
{
int log_write_allowed = test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags);
if (!test_bit(SDF_KILL, &sdp->sd_flags))
gfs2_flush_delete_work(sdp);
gfs2_destroy_threads(sdp);
if (log_write_allowed) {
gfs2_quota_sync(sdp->sd_vfs, 0);
gfs2_statfs_sync(sdp->sd_vfs, 0);
/* We do two log flushes here. The first one commits dirty inodes
* and rgrps to the journal, but queues up revokes to the ail list.
* The second flush writes out and removes the revokes.
*
* The first must be done before the FLUSH_SHUTDOWN code
* clears the LIVE flag, otherwise it will not be able to start
* a transaction to write its revokes, and the error will cause
* a withdraw of the file system. */
gfs2_log_flush(sdp, NULL, GFS2_LFC_MAKE_FS_RO);
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_SHUTDOWN |
GFS2_LFC_MAKE_FS_RO);
wait_event_timeout(sdp->sd_log_waitq,
gfs2_log_is_empty(sdp),
HZ * 5);
gfs2_assert_warn(sdp, gfs2_log_is_empty(sdp));
}
gfs2_quota_cleanup(sdp);
}
/**
* gfs2_put_super - Unmount the filesystem
* @sb: The VFS superblock
*
*/
static void gfs2_put_super(struct super_block *sb)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_jdesc *jd;
/* No more recovery requests */
set_bit(SDF_NORECOVERY, &sdp->sd_flags);
smp_mb();
/* Wait on outstanding recovery */
restart:
spin_lock(&sdp->sd_jindex_spin);
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
if (!test_bit(JDF_RECOVERY, &jd->jd_flags))
continue;
spin_unlock(&sdp->sd_jindex_spin);
wait_on_bit(&jd->jd_flags, JDF_RECOVERY,
TASK_UNINTERRUPTIBLE);
goto restart;
}
spin_unlock(&sdp->sd_jindex_spin);
if (!sb_rdonly(sb)) {
gfs2_make_fs_ro(sdp);
}
if (gfs2_withdrawn(sdp)) {
gfs2_destroy_threads(sdp);
gfs2_quota_cleanup(sdp);
}
WARN_ON(gfs2_withdrawing(sdp));
/* At this point, we're through modifying the disk */
/* Release stuff */
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
iput(sdp->sd_jindex);
iput(sdp->sd_statfs_inode);
iput(sdp->sd_rindex);
iput(sdp->sd_quota_inode);
gfs2_glock_put(sdp->sd_rename_gl);
gfs2_glock_put(sdp->sd_freeze_gl);
if (!sdp->sd_args.ar_spectator) {
if (gfs2_holder_initialized(&sdp->sd_journal_gh))
gfs2_glock_dq_uninit(&sdp->sd_journal_gh);
if (gfs2_holder_initialized(&sdp->sd_jinode_gh))
gfs2_glock_dq_uninit(&sdp->sd_jinode_gh);
brelse(sdp->sd_sc_bh);
gfs2_glock_dq_uninit(&sdp->sd_sc_gh);
gfs2_glock_dq_uninit(&sdp->sd_qc_gh);
free_local_statfs_inodes(sdp);
iput(sdp->sd_qc_inode);
}
gfs2_glock_dq_uninit(&sdp->sd_live_gh);
gfs2_clear_rgrpd(sdp);
gfs2_jindex_free(sdp);
/* Take apart glock structures and buffer lists */
gfs2_gl_hash_clear(sdp);
truncate_inode_pages_final(&sdp->sd_aspace);
gfs2_delete_debugfs_file(sdp);
/* Unmount the locking protocol */
gfs2_lm_unmount(sdp);
/* At this point, we're through participating in the lockspace */
gfs2_sys_fs_del(sdp);
free_sbd(sdp);
}
/**
* gfs2_sync_fs - sync the filesystem
* @sb: the superblock
* @wait: true to wait for completion
*
* Flushes the log to disk.
*/
static int gfs2_sync_fs(struct super_block *sb, int wait)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
gfs2_quota_sync(sb, -1);
if (wait)
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_SYNC_FS);
return sdp->sd_log_error;
}
static int gfs2_freeze_locally(struct gfs2_sbd *sdp)
{
struct super_block *sb = sdp->sd_vfs;
int error;
error = freeze_super(sb, FREEZE_HOLDER_USERSPACE);
if (error)
return error;
if (test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags)) {
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_FREEZE |
GFS2_LFC_FREEZE_GO_SYNC);
if (gfs2_withdrawn(sdp)) {
error = thaw_super(sb, FREEZE_HOLDER_USERSPACE);
if (error)
return error;
return -EIO;
}
}
return 0;
}
static int gfs2_do_thaw(struct gfs2_sbd *sdp)
{
struct super_block *sb = sdp->sd_vfs;
int error;
error = gfs2_freeze_lock_shared(sdp);
if (error)
goto fail;
error = thaw_super(sb, FREEZE_HOLDER_USERSPACE);
if (!error)
return 0;
fail:
fs_info(sdp, "GFS2: couldn't thaw filesystem: %d\n", error);
gfs2_assert_withdraw(sdp, 0);
return error;
}
void gfs2_freeze_func(struct work_struct *work)
{
struct gfs2_sbd *sdp = container_of(work, struct gfs2_sbd, sd_freeze_work);
struct super_block *sb = sdp->sd_vfs;
int error;
mutex_lock(&sdp->sd_freeze_mutex);
error = -EBUSY;
if (test_bit(SDF_FROZEN, &sdp->sd_flags))
goto freeze_failed;
error = gfs2_freeze_locally(sdp);
if (error)
goto freeze_failed;
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
set_bit(SDF_FROZEN, &sdp->sd_flags);
error = gfs2_do_thaw(sdp);
if (error)
goto out;
clear_bit(SDF_FROZEN, &sdp->sd_flags);
goto out;
freeze_failed:
fs_info(sdp, "GFS2: couldn't freeze filesystem: %d\n", error);
out:
mutex_unlock(&sdp->sd_freeze_mutex);
deactivate_super(sb);
}
/**
* gfs2_freeze_super - prevent further writes to the filesystem
* @sb: the VFS structure for the filesystem
*
*/
static int gfs2_freeze_super(struct super_block *sb, enum freeze_holder who)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
int error;
if (!mutex_trylock(&sdp->sd_freeze_mutex))
return -EBUSY;
error = -EBUSY;
if (test_bit(SDF_FROZEN, &sdp->sd_flags))
goto out;
for (;;) {
error = gfs2_freeze_locally(sdp);
if (error) {
fs_info(sdp, "GFS2: couldn't freeze filesystem: %d\n",
error);
goto out;
}
error = gfs2_lock_fs_check_clean(sdp);
if (!error)
break; /* success */
error = gfs2_do_thaw(sdp);
if (error)
goto out;
if (error == -EBUSY)
fs_err(sdp, "waiting for recovery before freeze\n");
else if (error == -EIO) {
fs_err(sdp, "Fatal IO error: cannot freeze gfs2 due "
"to recovery error.\n");
goto out;
} else {
fs_err(sdp, "error freezing FS: %d\n", error);
}
fs_err(sdp, "retrying...\n");
msleep(1000);
}
out:
if (!error) {
set_bit(SDF_FREEZE_INITIATOR, &sdp->sd_flags);
set_bit(SDF_FROZEN, &sdp->sd_flags);
}
mutex_unlock(&sdp->sd_freeze_mutex);
return error;
}
/**
* gfs2_thaw_super - reallow writes to the filesystem
* @sb: the VFS structure for the filesystem
*
*/
static int gfs2_thaw_super(struct super_block *sb, enum freeze_holder who)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
int error;
if (!mutex_trylock(&sdp->sd_freeze_mutex))
return -EBUSY;
error = -EINVAL;
if (!test_bit(SDF_FREEZE_INITIATOR, &sdp->sd_flags))
goto out;
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
error = gfs2_do_thaw(sdp);
if (!error) {
clear_bit(SDF_FREEZE_INITIATOR, &sdp->sd_flags);
clear_bit(SDF_FROZEN, &sdp->sd_flags);
}
out:
mutex_unlock(&sdp->sd_freeze_mutex);
return error;
}
void gfs2_thaw_freeze_initiator(struct super_block *sb)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
mutex_lock(&sdp->sd_freeze_mutex);
if (!test_bit(SDF_FREEZE_INITIATOR, &sdp->sd_flags))
goto out;
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
out:
mutex_unlock(&sdp->sd_freeze_mutex);
}
/**
* statfs_slow_fill - fill in the sg for a given RG
* @rgd: the RG
* @sc: the sc structure
*
* Returns: 0 on success, -ESTALE if the LVB is invalid
*/
static int statfs_slow_fill(struct gfs2_rgrpd *rgd,
struct gfs2_statfs_change_host *sc)
{
gfs2_rgrp_verify(rgd);
sc->sc_total += rgd->rd_data;
sc->sc_free += rgd->rd_free;
sc->sc_dinodes += rgd->rd_dinodes;
return 0;
}
/**
* gfs2_statfs_slow - Stat a filesystem using asynchronous locking
* @sdp: the filesystem
* @sc: the sc info that will be returned
*
* Any error (other than a signal) will cause this routine to fall back
* to the synchronous version.
*
* FIXME: This really shouldn't busy wait like this.
*
* Returns: errno
*/
static int gfs2_statfs_slow(struct gfs2_sbd *sdp, struct gfs2_statfs_change_host *sc)
{
struct gfs2_rgrpd *rgd_next;
struct gfs2_holder *gha, *gh;
unsigned int slots = 64;
unsigned int x;
int done;
int error = 0, err;
memset(sc, 0, sizeof(struct gfs2_statfs_change_host));
gha = kmalloc_array(slots, sizeof(struct gfs2_holder), GFP_KERNEL);
if (!gha)
return -ENOMEM;
for (x = 0; x < slots; x++)
gfs2_holder_mark_uninitialized(gha + x);
rgd_next = gfs2_rgrpd_get_first(sdp);
for (;;) {
done = 1;
for (x = 0; x < slots; x++) {
gh = gha + x;
if (gfs2_holder_initialized(gh) && gfs2_glock_poll(gh)) {
err = gfs2_glock_wait(gh);
if (err) {
gfs2_holder_uninit(gh);
error = err;
} else {
if (!error) {
struct gfs2_rgrpd *rgd =
gfs2_glock2rgrp(gh->gh_gl);
error = statfs_slow_fill(rgd, sc);
}
gfs2_glock_dq_uninit(gh);
}
}
if (gfs2_holder_initialized(gh))
done = 0;
else if (rgd_next && !error) {
error = gfs2_glock_nq_init(rgd_next->rd_gl,
LM_ST_SHARED,
GL_ASYNC,
gh);
rgd_next = gfs2_rgrpd_get_next(rgd_next);
done = 0;
}
if (signal_pending(current))
error = -ERESTARTSYS;
}
if (done)
break;
yield();
}
kfree(gha);
return error;
}
/**
* gfs2_statfs_i - Do a statfs
* @sdp: the filesystem
* @sc: the sc structure
*
* Returns: errno
*/
static int gfs2_statfs_i(struct gfs2_sbd *sdp, struct gfs2_statfs_change_host *sc)
{
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
spin_lock(&sdp->sd_statfs_spin);
*sc = *m_sc;
sc->sc_total += l_sc->sc_total;
sc->sc_free += l_sc->sc_free;
sc->sc_dinodes += l_sc->sc_dinodes;
spin_unlock(&sdp->sd_statfs_spin);
if (sc->sc_free < 0)
sc->sc_free = 0;
if (sc->sc_free > sc->sc_total)
sc->sc_free = sc->sc_total;
if (sc->sc_dinodes < 0)
sc->sc_dinodes = 0;
return 0;
}
/**
* gfs2_statfs - Gather and return stats about the filesystem
* @dentry: The name of the link
* @buf: The buffer
*
* Returns: 0 on success or error code
*/
static int gfs2_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_statfs_change_host sc;
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
if (gfs2_tune_get(sdp, gt_statfs_slow))
error = gfs2_statfs_slow(sdp, &sc);
else
error = gfs2_statfs_i(sdp, &sc);
if (error)
return error;
buf->f_type = GFS2_MAGIC;
buf->f_bsize = sdp->sd_sb.sb_bsize;
buf->f_blocks = sc.sc_total;
buf->f_bfree = sc.sc_free;
buf->f_bavail = sc.sc_free;
buf->f_files = sc.sc_dinodes + sc.sc_free;
buf->f_ffree = sc.sc_free;
buf->f_namelen = GFS2_FNAMESIZE;
return 0;
}
/**
* gfs2_drop_inode - Drop an inode (test for remote unlink)
* @inode: The inode to drop
*
* If we've received a callback on an iopen lock then it's because a
* remote node tried to deallocate the inode but failed due to this node
* still having the inode open. Here we mark the link count zero
* since we know that it must have reached zero if the GLF_DEMOTE flag
* is set on the iopen glock. If we didn't do a disk read since the
* remote node removed the final link then we might otherwise miss
* this event. This check ensures that this node will deallocate the
* inode's blocks, or alternatively pass the baton on to another
* node for later deallocation.
*/
static int gfs2_drop_inode(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
if (inode->i_nlink &&
gfs2_holder_initialized(&ip->i_iopen_gh)) {
struct gfs2_glock *gl = ip->i_iopen_gh.gh_gl;
if (test_bit(GLF_DEMOTE, &gl->gl_flags))
clear_nlink(inode);
}
/*
* When under memory pressure when an inode's link count has dropped to
* zero, defer deleting the inode to the delete workqueue. This avoids
* calling into DLM under memory pressure, which can deadlock.
*/
if (!inode->i_nlink &&
unlikely(current->flags & PF_MEMALLOC) &&
gfs2_holder_initialized(&ip->i_iopen_gh)) {
struct gfs2_glock *gl = ip->i_iopen_gh.gh_gl;
gfs2_glock_hold(gl);
if (!gfs2_queue_try_to_evict(gl))
gfs2_glock_queue_put(gl);
return 0;
}
/*
* No longer cache inodes when trying to evict them all.
*/
if (test_bit(SDF_EVICTING, &sdp->sd_flags))
return 1;
return generic_drop_inode(inode);
}
static int is_ancestor(const struct dentry *d1, const struct dentry *d2)
{
do {
if (d1 == d2)
return 1;
d1 = d1->d_parent;
} while (!IS_ROOT(d1));
return 0;
}
/**
* gfs2_show_options - Show mount options for /proc/mounts
* @s: seq_file structure
* @root: root of this (sub)tree
*
* Returns: 0 on success or error code
*/
static int gfs2_show_options(struct seq_file *s, struct dentry *root)
{
struct gfs2_sbd *sdp = root->d_sb->s_fs_info;
struct gfs2_args *args = &sdp->sd_args;
unsigned int logd_secs, statfs_slow, statfs_quantum, quota_quantum;
spin_lock(&sdp->sd_tune.gt_spin);
logd_secs = sdp->sd_tune.gt_logd_secs;
quota_quantum = sdp->sd_tune.gt_quota_quantum;
statfs_quantum = sdp->sd_tune.gt_statfs_quantum;
statfs_slow = sdp->sd_tune.gt_statfs_slow;
spin_unlock(&sdp->sd_tune.gt_spin);
if (is_ancestor(root, sdp->sd_master_dir))
seq_puts(s, ",meta");
if (args->ar_lockproto[0])
seq_show_option(s, "lockproto", args->ar_lockproto);
if (args->ar_locktable[0])
seq_show_option(s, "locktable", args->ar_locktable);
if (args->ar_hostdata[0])
seq_show_option(s, "hostdata", args->ar_hostdata);
if (args->ar_spectator)
seq_puts(s, ",spectator");
if (args->ar_localflocks)
seq_puts(s, ",localflocks");
if (args->ar_debug)
seq_puts(s, ",debug");
if (args->ar_posix_acl)
seq_puts(s, ",acl");
if (args->ar_quota != GFS2_QUOTA_DEFAULT) {
char *state;
switch (args->ar_quota) {
case GFS2_QUOTA_OFF:
state = "off";
break;
case GFS2_QUOTA_ACCOUNT:
state = "account";
break;
case GFS2_QUOTA_ON:
state = "on";
break;
case GFS2_QUOTA_QUIET:
state = "quiet";
break;
default:
state = "unknown";
break;
}
seq_printf(s, ",quota=%s", state);
}
if (args->ar_suiddir)
seq_puts(s, ",suiddir");
if (args->ar_data != GFS2_DATA_DEFAULT) {
char *state;
switch (args->ar_data) {
case GFS2_DATA_WRITEBACK:
state = "writeback";
break;
case GFS2_DATA_ORDERED:
state = "ordered";
break;
default:
state = "unknown";
break;
}
seq_printf(s, ",data=%s", state);
}
if (args->ar_discard)
seq_puts(s, ",discard");
if (logd_secs != 30)
seq_printf(s, ",commit=%d", logd_secs);
if (statfs_quantum != 30)
seq_printf(s, ",statfs_quantum=%d", statfs_quantum);
else if (statfs_slow)
seq_puts(s, ",statfs_quantum=0");
if (quota_quantum != 60)
seq_printf(s, ",quota_quantum=%d", quota_quantum);
if (args->ar_statfs_percent)
seq_printf(s, ",statfs_percent=%d", args->ar_statfs_percent);
if (args->ar_errors != GFS2_ERRORS_DEFAULT) {
const char *state;
switch (args->ar_errors) {
case GFS2_ERRORS_WITHDRAW:
state = "withdraw";
break;
case GFS2_ERRORS_PANIC:
state = "panic";
break;
default:
state = "unknown";
break;
}
seq_printf(s, ",errors=%s", state);
}
if (test_bit(SDF_NOBARRIERS, &sdp->sd_flags))
seq_puts(s, ",nobarrier");
if (test_bit(SDF_DEMOTE, &sdp->sd_flags))
seq_puts(s, ",demote_interface_used");
if (args->ar_rgrplvb)
seq_puts(s, ",rgrplvb");
if (args->ar_loccookie)
seq_puts(s, ",loccookie");
return 0;
}
static void gfs2_final_release_pages(struct gfs2_inode *ip)
{
struct inode *inode = &ip->i_inode;
struct gfs2_glock *gl = ip->i_gl;
if (unlikely(!gl)) {
/* This can only happen during incomplete inode creation. */
BUG_ON(!test_bit(GIF_ALLOC_FAILED, &ip->i_flags));
return;
}
truncate_inode_pages(gfs2_glock2aspace(gl), 0);
truncate_inode_pages(&inode->i_data, 0);
if (atomic_read(&gl->gl_revokes) == 0) {
clear_bit(GLF_LFLUSH, &gl->gl_flags);
clear_bit(GLF_DIRTY, &gl->gl_flags);
}
}
static int gfs2_dinode_dealloc(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *rgd;
struct gfs2_holder gh;
int error;
if (gfs2_get_inode_blocks(&ip->i_inode) != 1) {
gfs2_consist_inode(ip);
return -EIO;
}
gfs2_rindex_update(sdp);
error = gfs2_quota_hold(ip, NO_UID_QUOTA_CHANGE, NO_GID_QUOTA_CHANGE);
if (error)
return error;
rgd = gfs2_blk2rgrpd(sdp, ip->i_no_addr, 1);
if (!rgd) {
gfs2_consist_inode(ip);
error = -EIO;
goto out_qs;
}
error = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, &gh);
if (error)
goto out_qs;
error = gfs2_trans_begin(sdp, RES_RG_BIT + RES_STATFS + RES_QUOTA,
sdp->sd_jdesc->jd_blocks);
if (error)
goto out_rg_gunlock;
gfs2_free_di(rgd, ip);
gfs2_final_release_pages(ip);
gfs2_trans_end(sdp);
out_rg_gunlock:
gfs2_glock_dq_uninit(&gh);
out_qs:
gfs2_quota_unhold(ip);
return error;
}
/**
* gfs2_glock_put_eventually
* @gl: The glock to put
*
* When under memory pressure, trigger a deferred glock put to make sure we
* won't call into DLM and deadlock. Otherwise, put the glock directly.
*/
static void gfs2_glock_put_eventually(struct gfs2_glock *gl)
{
if (current->flags & PF_MEMALLOC)
gfs2_glock_queue_put(gl);
else
gfs2_glock_put(gl);
}
static bool gfs2_upgrade_iopen_glock(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_holder *gh = &ip->i_iopen_gh;
long timeout = 5 * HZ;
int error;
gh->gh_flags |= GL_NOCACHE;
gfs2_glock_dq_wait(gh);
/*
* If there are no other lock holders, we will immediately get
* exclusive access to the iopen glock here.
*
* Otherwise, the other nodes holding the lock will be notified about
* our locking request. If they do not have the inode open, they are
* expected to evict the cached inode and release the lock, allowing us
* to proceed.
*
* Otherwise, if they cannot evict the inode, they are expected to poke
* the inode glock (note: not the iopen glock). We will notice that
* and stop waiting for the iopen glock immediately. The other node(s)
* are then expected to take care of deleting the inode when they no
* longer use it.
*
* As a last resort, if another node keeps holding the iopen glock
* without showing any activity on the inode glock, we will eventually
* time out and fail the iopen glock upgrade.
*
* Note that we're passing the LM_FLAG_TRY_1CB flag to the first
* locking request as an optimization to notify lock holders as soon as
* possible. Without that flag, they'd be notified implicitly by the
* second locking request.
*/
gfs2_holder_reinit(LM_ST_EXCLUSIVE, LM_FLAG_TRY_1CB | GL_NOCACHE, gh);
error = gfs2_glock_nq(gh);
if (error != GLR_TRYFAILED)
return !error;
gfs2_holder_reinit(LM_ST_EXCLUSIVE, GL_ASYNC | GL_NOCACHE, gh);
error = gfs2_glock_nq(gh);
if (error)
return false;
timeout = wait_event_interruptible_timeout(sdp->sd_async_glock_wait,
!test_bit(HIF_WAIT, &gh->gh_iflags) ||
test_bit(GLF_DEMOTE, &ip->i_gl->gl_flags),
timeout);
if (!test_bit(HIF_HOLDER, &gh->gh_iflags)) {
gfs2_glock_dq(gh);
return false;
}
return gfs2_glock_holder_ready(gh) == 0;
}
/**
* evict_should_delete - determine whether the inode is eligible for deletion
* @inode: The inode to evict
* @gh: The glock holder structure
*
* This function determines whether the evicted inode is eligible to be deleted
* and locks the inode glock.
*
* Returns: the fate of the dinode
*/
static enum dinode_demise evict_should_delete(struct inode *inode,
struct gfs2_holder *gh)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct super_block *sb = inode->i_sb;
struct gfs2_sbd *sdp = sb->s_fs_info;
int ret;
if (unlikely(test_bit(GIF_ALLOC_FAILED, &ip->i_flags)))
goto should_delete;
if (test_bit(GIF_DEFERRED_DELETE, &ip->i_flags))
return SHOULD_DEFER_EVICTION;
/* Deletes should never happen under memory pressure anymore. */
if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
return SHOULD_DEFER_EVICTION;
/* Must not read inode block until block type has been verified */
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, GL_SKIP, gh);
if (unlikely(ret)) {
glock_clear_object(ip->i_iopen_gh.gh_gl, ip);
ip->i_iopen_gh.gh_flags |= GL_NOCACHE;
gfs2_glock_dq_uninit(&ip->i_iopen_gh);
return SHOULD_DEFER_EVICTION;
}
if (gfs2_inode_already_deleted(ip->i_gl, ip->i_no_formal_ino))
return SHOULD_NOT_DELETE_DINODE;
ret = gfs2_check_blk_type(sdp, ip->i_no_addr, GFS2_BLKST_UNLINKED);
if (ret)
return SHOULD_NOT_DELETE_DINODE;
ret = gfs2_instantiate(gh);
if (ret)
return SHOULD_NOT_DELETE_DINODE;
/*
* The inode may have been recreated in the meantime.
*/
if (inode->i_nlink)
return SHOULD_NOT_DELETE_DINODE;
should_delete:
if (gfs2_holder_initialized(&ip->i_iopen_gh) &&
test_bit(HIF_HOLDER, &ip->i_iopen_gh.gh_iflags)) {
if (!gfs2_upgrade_iopen_glock(inode)) {
gfs2_holder_uninit(&ip->i_iopen_gh);
return SHOULD_NOT_DELETE_DINODE;
}
}
return SHOULD_DELETE_DINODE;
}
/**
* evict_unlinked_inode - delete the pieces of an unlinked evicted inode
* @inode: The inode to evict
*/
static int evict_unlinked_inode(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
int ret;
if (S_ISDIR(inode->i_mode) &&
(ip->i_diskflags & GFS2_DIF_EXHASH)) {
ret = gfs2_dir_exhash_dealloc(ip);
if (ret)
goto out;
}
if (ip->i_eattr) {
ret = gfs2_ea_dealloc(ip);
if (ret)
goto out;
}
if (!gfs2_is_stuffed(ip)) {
ret = gfs2_file_dealloc(ip);
if (ret)
goto out;
}
/*
* As soon as we clear the bitmap for the dinode, gfs2_create_inode()
* can get called to recreate it, or even gfs2_inode_lookup() if the
* inode was recreated on another node in the meantime.
*
* However, inserting the new inode into the inode hash table will not
* succeed until the old inode is removed, and that only happens after
* ->evict_inode() returns. The new inode is attached to its inode and
* iopen glocks after inserting it into the inode hash table, so at
* that point we can be sure that both glocks are unused.
*/
ret = gfs2_dinode_dealloc(ip);
if (!ret && ip->i_gl)
gfs2_inode_remember_delete(ip->i_gl, ip->i_no_formal_ino);
out:
return ret;
}
/*
* evict_linked_inode - evict an inode whose dinode has not been unlinked
* @inode: The inode to evict
*/
static int evict_linked_inode(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_inode *ip = GFS2_I(inode);
struct address_space *metamapping;
int ret;
gfs2_log_flush(sdp, ip->i_gl, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_EVICT_INODE);
metamapping = gfs2_glock2aspace(ip->i_gl);
if (test_bit(GLF_DIRTY, &ip->i_gl->gl_flags)) {
filemap_fdatawrite(metamapping);
filemap_fdatawait(metamapping);
}
write_inode_now(inode, 1);
gfs2_ail_flush(ip->i_gl, 0);
ret = gfs2_trans_begin(sdp, 0, sdp->sd_jdesc->jd_blocks);
if (ret)
return ret;
/* Needs to be done before glock release & also in a transaction */
truncate_inode_pages(&inode->i_data, 0);
truncate_inode_pages(metamapping, 0);
gfs2_trans_end(sdp);
return 0;
}
/**
* gfs2_evict_inode - Remove an inode from cache
* @inode: The inode to evict
*
* There are three cases to consider:
* 1. i_nlink == 0, we are final opener (and must deallocate)
* 2. i_nlink == 0, we are not the final opener (and cannot deallocate)
* 3. i_nlink > 0
*
* If the fs is read only, then we have to treat all cases as per #3
* since we are unable to do any deallocation. The inode will be
* deallocated by the next read/write node to attempt an allocation
* in the same resource group
*
* We have to (at the moment) hold the inodes main lock to cover
* the gap between unlocking the shared lock on the iopen lock and
* taking the exclusive lock. I'd rather do a shared -> exclusive
* conversion on the iopen lock, but we can change that later. This
* is safe, just less efficient.
*/
static void gfs2_evict_inode(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int ret;
if (inode->i_nlink || sb_rdonly(sb) || !ip->i_no_addr)
goto out;
/*
* In case of an incomplete mount, gfs2_evict_inode() may be called for
* system files without having an active journal to write to. In that
* case, skip the filesystem evict.
*/
if (!sdp->sd_jdesc)
goto out;
gfs2_holder_mark_uninitialized(&gh);
ret = evict_should_delete(inode, &gh);
if (ret == SHOULD_DEFER_EVICTION)
goto out;
if (ret == SHOULD_DELETE_DINODE)
ret = evict_unlinked_inode(inode);
else
ret = evict_linked_inode(inode);
if (gfs2_rs_active(&ip->i_res))
gfs2_rs_deltree(&ip->i_res);
if (gfs2_holder_initialized(&gh))
gfs2_glock_dq_uninit(&gh);
if (ret && ret != GLR_TRYFAILED && ret != -EROFS)
fs_warn(sdp, "gfs2_evict_inode: %d\n", ret);
out:
truncate_inode_pages_final(&inode->i_data);
if (ip->i_qadata)
gfs2_assert_warn(sdp, ip->i_qadata->qa_ref == 0);
gfs2_rs_deltree(&ip->i_res);
gfs2_ordered_del_inode(ip);
clear_inode(inode);
gfs2_dir_hash_inval(ip);
if (gfs2_holder_initialized(&ip->i_iopen_gh)) {
struct gfs2_glock *gl = ip->i_iopen_gh.gh_gl;
glock_clear_object(gl, ip);
gfs2_glock_hold(gl);
ip->i_iopen_gh.gh_flags |= GL_NOCACHE;
gfs2_glock_dq_uninit(&ip->i_iopen_gh);
gfs2_glock_put_eventually(gl);
}
if (ip->i_gl) {
glock_clear_object(ip->i_gl, ip);
wait_on_bit_io(&ip->i_flags, GIF_GLOP_PENDING, TASK_UNINTERRUPTIBLE);
gfs2_glock_add_to_lru(ip->i_gl);
gfs2_glock_put_eventually(ip->i_gl);
ip->i_gl = NULL;
}
}
static struct inode *gfs2_alloc_inode(struct super_block *sb)
{
struct gfs2_inode *ip;
ip = alloc_inode_sb(sb, gfs2_inode_cachep, GFP_KERNEL);
if (!ip)
return NULL;
ip->i_no_addr = 0;
ip->i_flags = 0;
ip->i_gl = NULL;
gfs2_holder_mark_uninitialized(&ip->i_iopen_gh);
memset(&ip->i_res, 0, sizeof(ip->i_res));
RB_CLEAR_NODE(&ip->i_res.rs_node);
ip->i_rahead = 0;
return &ip->i_inode;
}
static void gfs2_free_inode(struct inode *inode)
{
kmem_cache_free(gfs2_inode_cachep, GFS2_I(inode));
}
extern void free_local_statfs_inodes(struct gfs2_sbd *sdp)
{
struct local_statfs_inode *lsi, *safe;
/* Run through the statfs inodes list to iput and free memory */
list_for_each_entry_safe(lsi, safe, &sdp->sd_sc_inodes_list, si_list) {
if (lsi->si_jid == sdp->sd_jdesc->jd_jid)
sdp->sd_sc_inode = NULL; /* belongs to this node */
if (lsi->si_sc_inode)
iput(lsi->si_sc_inode);
list_del(&lsi->si_list);
kfree(lsi);
}
}
extern struct inode *find_local_statfs_inode(struct gfs2_sbd *sdp,
unsigned int index)
{
struct local_statfs_inode *lsi;
/* Return the local (per node) statfs inode in the
* sdp->sd_sc_inodes_list corresponding to the 'index'. */
list_for_each_entry(lsi, &sdp->sd_sc_inodes_list, si_list) {
if (lsi->si_jid == index)
return lsi->si_sc_inode;
}
return NULL;
}
const struct super_operations gfs2_super_ops = {
.alloc_inode = gfs2_alloc_inode,
.free_inode = gfs2_free_inode,
.write_inode = gfs2_write_inode,
.dirty_inode = gfs2_dirty_inode,
.evict_inode = gfs2_evict_inode,
.put_super = gfs2_put_super,
.sync_fs = gfs2_sync_fs,
.freeze_super = gfs2_freeze_super,
.thaw_super = gfs2_thaw_super,
.statfs = gfs2_statfs,
.drop_inode = gfs2_drop_inode,
.show_options = gfs2_show_options,
};
| linux-master | fs/gfs2/super.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/crc32c.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/writeback.h>
#include <linux/list_sort.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "util.h"
#include "dir.h"
#include "trace_gfs2.h"
#include "trans.h"
static void gfs2_log_shutdown(struct gfs2_sbd *sdp);
/**
* gfs2_struct2blk - compute stuff
* @sdp: the filesystem
* @nstruct: the number of structures
*
* Compute the number of log descriptor blocks needed to hold a certain number
* of structures of a certain size.
*
* Returns: the number of blocks needed (minimum is always 1)
*/
unsigned int gfs2_struct2blk(struct gfs2_sbd *sdp, unsigned int nstruct)
{
unsigned int blks;
unsigned int first, second;
/* The initial struct gfs2_log_descriptor block */
blks = 1;
first = sdp->sd_ldptrs;
if (nstruct > first) {
/* Subsequent struct gfs2_meta_header blocks */
second = sdp->sd_inptrs;
blks += DIV_ROUND_UP(nstruct - first, second);
}
return blks;
}
/**
* gfs2_remove_from_ail - Remove an entry from the ail lists, updating counters
* @bd: The gfs2_bufdata to remove
*
* The ail lock _must_ be held when calling this function
*
*/
void gfs2_remove_from_ail(struct gfs2_bufdata *bd)
{
bd->bd_tr = NULL;
list_del_init(&bd->bd_ail_st_list);
list_del_init(&bd->bd_ail_gl_list);
atomic_dec(&bd->bd_gl->gl_ail_count);
brelse(bd->bd_bh);
}
static int __gfs2_writepage(struct folio *folio, struct writeback_control *wbc,
void *data)
{
struct address_space *mapping = data;
int ret = mapping->a_ops->writepage(&folio->page, wbc);
mapping_set_error(mapping, ret);
return ret;
}
/**
* gfs2_ail1_start_one - Start I/O on a transaction
* @sdp: The superblock
* @wbc: The writeback control structure
* @tr: The transaction to start I/O on
* @plug: The block plug currently active
*/
static int gfs2_ail1_start_one(struct gfs2_sbd *sdp,
struct writeback_control *wbc,
struct gfs2_trans *tr, struct blk_plug *plug)
__releases(&sdp->sd_ail_lock)
__acquires(&sdp->sd_ail_lock)
{
struct gfs2_glock *gl = NULL;
struct address_space *mapping;
struct gfs2_bufdata *bd, *s;
struct buffer_head *bh;
int ret = 0;
list_for_each_entry_safe_reverse(bd, s, &tr->tr_ail1_list, bd_ail_st_list) {
bh = bd->bd_bh;
gfs2_assert(sdp, bd->bd_tr == tr);
if (!buffer_busy(bh)) {
if (buffer_uptodate(bh)) {
list_move(&bd->bd_ail_st_list,
&tr->tr_ail2_list);
continue;
}
if (!cmpxchg(&sdp->sd_log_error, 0, -EIO)) {
gfs2_io_error_bh(sdp, bh);
gfs2_withdraw_delayed(sdp);
}
}
if (gfs2_withdrawn(sdp)) {
gfs2_remove_from_ail(bd);
continue;
}
if (!buffer_dirty(bh))
continue;
if (gl == bd->bd_gl)
continue;
gl = bd->bd_gl;
list_move(&bd->bd_ail_st_list, &tr->tr_ail1_list);
mapping = bh->b_folio->mapping;
if (!mapping)
continue;
spin_unlock(&sdp->sd_ail_lock);
ret = write_cache_pages(mapping, wbc, __gfs2_writepage, mapping);
if (need_resched()) {
blk_finish_plug(plug);
cond_resched();
blk_start_plug(plug);
}
spin_lock(&sdp->sd_ail_lock);
if (ret == -ENODATA) /* if a jdata write into a new hole */
ret = 0; /* ignore it */
if (ret || wbc->nr_to_write <= 0)
break;
return -EBUSY;
}
return ret;
}
static void dump_ail_list(struct gfs2_sbd *sdp)
{
struct gfs2_trans *tr;
struct gfs2_bufdata *bd;
struct buffer_head *bh;
list_for_each_entry_reverse(tr, &sdp->sd_ail1_list, tr_list) {
list_for_each_entry_reverse(bd, &tr->tr_ail1_list,
bd_ail_st_list) {
bh = bd->bd_bh;
fs_err(sdp, "bd %p: blk:0x%llx bh=%p ", bd,
(unsigned long long)bd->bd_blkno, bh);
if (!bh) {
fs_err(sdp, "\n");
continue;
}
fs_err(sdp, "0x%llx up2:%d dirt:%d lkd:%d req:%d "
"map:%d new:%d ar:%d aw:%d delay:%d "
"io err:%d unwritten:%d dfr:%d pin:%d esc:%d\n",
(unsigned long long)bh->b_blocknr,
buffer_uptodate(bh), buffer_dirty(bh),
buffer_locked(bh), buffer_req(bh),
buffer_mapped(bh), buffer_new(bh),
buffer_async_read(bh), buffer_async_write(bh),
buffer_delay(bh), buffer_write_io_error(bh),
buffer_unwritten(bh),
buffer_defer_completion(bh),
buffer_pinned(bh), buffer_escaped(bh));
}
}
}
/**
* gfs2_ail1_flush - start writeback of some ail1 entries
* @sdp: The super block
* @wbc: The writeback control structure
*
* Writes back some ail1 entries, according to the limits in the
* writeback control structure
*/
void gfs2_ail1_flush(struct gfs2_sbd *sdp, struct writeback_control *wbc)
{
struct list_head *head = &sdp->sd_ail1_list;
struct gfs2_trans *tr;
struct blk_plug plug;
int ret;
unsigned long flush_start = jiffies;
trace_gfs2_ail_flush(sdp, wbc, 1);
blk_start_plug(&plug);
spin_lock(&sdp->sd_ail_lock);
restart:
ret = 0;
if (time_after(jiffies, flush_start + (HZ * 600))) {
fs_err(sdp, "Error: In %s for ten minutes! t=%d\n",
__func__, current->journal_info ? 1 : 0);
dump_ail_list(sdp);
goto out;
}
list_for_each_entry_reverse(tr, head, tr_list) {
if (wbc->nr_to_write <= 0)
break;
ret = gfs2_ail1_start_one(sdp, wbc, tr, &plug);
if (ret) {
if (ret == -EBUSY)
goto restart;
break;
}
}
out:
spin_unlock(&sdp->sd_ail_lock);
blk_finish_plug(&plug);
if (ret) {
gfs2_lm(sdp, "gfs2_ail1_start_one returned: %d\n", ret);
gfs2_withdraw(sdp);
}
trace_gfs2_ail_flush(sdp, wbc, 0);
}
/**
* gfs2_ail1_start - start writeback of all ail1 entries
* @sdp: The superblock
*/
static void gfs2_ail1_start(struct gfs2_sbd *sdp)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = LONG_MAX,
.range_start = 0,
.range_end = LLONG_MAX,
};
return gfs2_ail1_flush(sdp, &wbc);
}
static void gfs2_log_update_flush_tail(struct gfs2_sbd *sdp)
{
unsigned int new_flush_tail = sdp->sd_log_head;
struct gfs2_trans *tr;
if (!list_empty(&sdp->sd_ail1_list)) {
tr = list_last_entry(&sdp->sd_ail1_list,
struct gfs2_trans, tr_list);
new_flush_tail = tr->tr_first;
}
sdp->sd_log_flush_tail = new_flush_tail;
}
static void gfs2_log_update_head(struct gfs2_sbd *sdp)
{
unsigned int new_head = sdp->sd_log_flush_head;
if (sdp->sd_log_flush_tail == sdp->sd_log_head)
sdp->sd_log_flush_tail = new_head;
sdp->sd_log_head = new_head;
}
/*
* gfs2_ail_empty_tr - empty one of the ail lists of a transaction
*/
static void gfs2_ail_empty_tr(struct gfs2_sbd *sdp, struct gfs2_trans *tr,
struct list_head *head)
{
struct gfs2_bufdata *bd;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata,
bd_ail_st_list);
gfs2_assert(sdp, bd->bd_tr == tr);
gfs2_remove_from_ail(bd);
}
}
/**
* gfs2_ail1_empty_one - Check whether or not a trans in the AIL has been synced
* @sdp: the filesystem
* @tr: the transaction
* @max_revokes: If nonzero, issue revokes for the bd items for written buffers
*
* returns: the transaction's count of remaining active items
*/
static int gfs2_ail1_empty_one(struct gfs2_sbd *sdp, struct gfs2_trans *tr,
int *max_revokes)
{
struct gfs2_bufdata *bd, *s;
struct buffer_head *bh;
int active_count = 0;
list_for_each_entry_safe_reverse(bd, s, &tr->tr_ail1_list,
bd_ail_st_list) {
bh = bd->bd_bh;
gfs2_assert(sdp, bd->bd_tr == tr);
/*
* If another process flagged an io error, e.g. writing to the
* journal, error all other bhs and move them off the ail1 to
* prevent a tight loop when unmount tries to flush ail1,
* regardless of whether they're still busy. If no outside
* errors were found and the buffer is busy, move to the next.
* If the ail buffer is not busy and caught an error, flag it
* for others.
*/
if (!sdp->sd_log_error && buffer_busy(bh)) {
active_count++;
continue;
}
if (!buffer_uptodate(bh) &&
!cmpxchg(&sdp->sd_log_error, 0, -EIO)) {
gfs2_io_error_bh(sdp, bh);
gfs2_withdraw_delayed(sdp);
}
/*
* If we have space for revokes and the bd is no longer on any
* buf list, we can just add a revoke for it immediately and
* avoid having to put it on the ail2 list, where it would need
* to be revoked later.
*/
if (*max_revokes && list_empty(&bd->bd_list)) {
gfs2_add_revoke(sdp, bd);
(*max_revokes)--;
continue;
}
list_move(&bd->bd_ail_st_list, &tr->tr_ail2_list);
}
return active_count;
}
/**
* gfs2_ail1_empty - Try to empty the ail1 lists
* @sdp: The superblock
* @max_revokes: If non-zero, add revokes where appropriate
*
* Tries to empty the ail1 lists, starting with the oldest first
*/
static int gfs2_ail1_empty(struct gfs2_sbd *sdp, int max_revokes)
{
struct gfs2_trans *tr, *s;
int oldest_tr = 1;
int ret;
spin_lock(&sdp->sd_ail_lock);
list_for_each_entry_safe_reverse(tr, s, &sdp->sd_ail1_list, tr_list) {
if (!gfs2_ail1_empty_one(sdp, tr, &max_revokes) && oldest_tr)
list_move(&tr->tr_list, &sdp->sd_ail2_list);
else
oldest_tr = 0;
}
gfs2_log_update_flush_tail(sdp);
ret = list_empty(&sdp->sd_ail1_list);
spin_unlock(&sdp->sd_ail_lock);
if (test_bit(SDF_WITHDRAWING, &sdp->sd_flags)) {
gfs2_lm(sdp, "fatal: I/O error(s)\n");
gfs2_withdraw(sdp);
}
return ret;
}
static void gfs2_ail1_wait(struct gfs2_sbd *sdp)
{
struct gfs2_trans *tr;
struct gfs2_bufdata *bd;
struct buffer_head *bh;
spin_lock(&sdp->sd_ail_lock);
list_for_each_entry_reverse(tr, &sdp->sd_ail1_list, tr_list) {
list_for_each_entry(bd, &tr->tr_ail1_list, bd_ail_st_list) {
bh = bd->bd_bh;
if (!buffer_locked(bh))
continue;
get_bh(bh);
spin_unlock(&sdp->sd_ail_lock);
wait_on_buffer(bh);
brelse(bh);
return;
}
}
spin_unlock(&sdp->sd_ail_lock);
}
static void __ail2_empty(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
gfs2_ail_empty_tr(sdp, tr, &tr->tr_ail2_list);
list_del(&tr->tr_list);
gfs2_assert_warn(sdp, list_empty(&tr->tr_ail1_list));
gfs2_assert_warn(sdp, list_empty(&tr->tr_ail2_list));
gfs2_trans_free(sdp, tr);
}
static void ail2_empty(struct gfs2_sbd *sdp, unsigned int new_tail)
{
struct list_head *ail2_list = &sdp->sd_ail2_list;
unsigned int old_tail = sdp->sd_log_tail;
struct gfs2_trans *tr, *safe;
spin_lock(&sdp->sd_ail_lock);
if (old_tail <= new_tail) {
list_for_each_entry_safe(tr, safe, ail2_list, tr_list) {
if (old_tail <= tr->tr_first && tr->tr_first < new_tail)
__ail2_empty(sdp, tr);
}
} else {
list_for_each_entry_safe(tr, safe, ail2_list, tr_list) {
if (old_tail <= tr->tr_first || tr->tr_first < new_tail)
__ail2_empty(sdp, tr);
}
}
spin_unlock(&sdp->sd_ail_lock);
}
/**
* gfs2_log_is_empty - Check if the log is empty
* @sdp: The GFS2 superblock
*/
bool gfs2_log_is_empty(struct gfs2_sbd *sdp) {
return atomic_read(&sdp->sd_log_blks_free) == sdp->sd_jdesc->jd_blocks;
}
static bool __gfs2_log_try_reserve_revokes(struct gfs2_sbd *sdp, unsigned int revokes)
{
unsigned int available;
available = atomic_read(&sdp->sd_log_revokes_available);
while (available >= revokes) {
if (atomic_try_cmpxchg(&sdp->sd_log_revokes_available,
&available, available - revokes))
return true;
}
return false;
}
/**
* gfs2_log_release_revokes - Release a given number of revokes
* @sdp: The GFS2 superblock
* @revokes: The number of revokes to release
*
* sdp->sd_log_flush_lock must be held.
*/
void gfs2_log_release_revokes(struct gfs2_sbd *sdp, unsigned int revokes)
{
if (revokes)
atomic_add(revokes, &sdp->sd_log_revokes_available);
}
/**
* gfs2_log_release - Release a given number of log blocks
* @sdp: The GFS2 superblock
* @blks: The number of blocks
*
*/
void gfs2_log_release(struct gfs2_sbd *sdp, unsigned int blks)
{
atomic_add(blks, &sdp->sd_log_blks_free);
trace_gfs2_log_blocks(sdp, blks);
gfs2_assert_withdraw(sdp, atomic_read(&sdp->sd_log_blks_free) <=
sdp->sd_jdesc->jd_blocks);
if (atomic_read(&sdp->sd_log_blks_needed))
wake_up(&sdp->sd_log_waitq);
}
/**
* __gfs2_log_try_reserve - Try to make a log reservation
* @sdp: The GFS2 superblock
* @blks: The number of blocks to reserve
* @taboo_blks: The number of blocks to leave free
*
* Try to do the same as __gfs2_log_reserve(), but fail if no more log
* space is immediately available.
*/
static bool __gfs2_log_try_reserve(struct gfs2_sbd *sdp, unsigned int blks,
unsigned int taboo_blks)
{
unsigned wanted = blks + taboo_blks;
unsigned int free_blocks;
free_blocks = atomic_read(&sdp->sd_log_blks_free);
while (free_blocks >= wanted) {
if (atomic_try_cmpxchg(&sdp->sd_log_blks_free, &free_blocks,
free_blocks - blks)) {
trace_gfs2_log_blocks(sdp, -blks);
return true;
}
}
return false;
}
/**
* __gfs2_log_reserve - Make a log reservation
* @sdp: The GFS2 superblock
* @blks: The number of blocks to reserve
* @taboo_blks: The number of blocks to leave free
*
* @taboo_blks is set to 0 for logd, and to GFS2_LOG_FLUSH_MIN_BLOCKS
* for all other processes. This ensures that when the log is almost full,
* logd will still be able to call gfs2_log_flush one more time without
* blocking, which will advance the tail and make some more log space
* available.
*
* We no longer flush the log here, instead we wake up logd to do that
* for us. To avoid the thundering herd and to ensure that we deal fairly
* with queued waiters, we use an exclusive wait. This means that when we
* get woken with enough journal space to get our reservation, we need to
* wake the next waiter on the list.
*/
static void __gfs2_log_reserve(struct gfs2_sbd *sdp, unsigned int blks,
unsigned int taboo_blks)
{
unsigned wanted = blks + taboo_blks;
unsigned int free_blocks;
atomic_add(blks, &sdp->sd_log_blks_needed);
for (;;) {
if (current != sdp->sd_logd_process)
wake_up(&sdp->sd_logd_waitq);
io_wait_event(sdp->sd_log_waitq,
(free_blocks = atomic_read(&sdp->sd_log_blks_free),
free_blocks >= wanted));
do {
if (atomic_try_cmpxchg(&sdp->sd_log_blks_free,
&free_blocks,
free_blocks - blks))
goto reserved;
} while (free_blocks >= wanted);
}
reserved:
trace_gfs2_log_blocks(sdp, -blks);
if (atomic_sub_return(blks, &sdp->sd_log_blks_needed))
wake_up(&sdp->sd_log_waitq);
}
/**
* gfs2_log_try_reserve - Try to make a log reservation
* @sdp: The GFS2 superblock
* @tr: The transaction
* @extra_revokes: The number of additional revokes reserved (output)
*
* This is similar to gfs2_log_reserve, but sdp->sd_log_flush_lock must be
* held for correct revoke accounting.
*/
bool gfs2_log_try_reserve(struct gfs2_sbd *sdp, struct gfs2_trans *tr,
unsigned int *extra_revokes)
{
unsigned int blks = tr->tr_reserved;
unsigned int revokes = tr->tr_revokes;
unsigned int revoke_blks = 0;
*extra_revokes = 0;
if (revokes && !__gfs2_log_try_reserve_revokes(sdp, revokes)) {
revoke_blks = DIV_ROUND_UP(revokes, sdp->sd_inptrs);
*extra_revokes = revoke_blks * sdp->sd_inptrs - revokes;
blks += revoke_blks;
}
if (!blks)
return true;
if (__gfs2_log_try_reserve(sdp, blks, GFS2_LOG_FLUSH_MIN_BLOCKS))
return true;
if (!revoke_blks)
gfs2_log_release_revokes(sdp, revokes);
return false;
}
/**
* gfs2_log_reserve - Make a log reservation
* @sdp: The GFS2 superblock
* @tr: The transaction
* @extra_revokes: The number of additional revokes reserved (output)
*
* sdp->sd_log_flush_lock must not be held.
*/
void gfs2_log_reserve(struct gfs2_sbd *sdp, struct gfs2_trans *tr,
unsigned int *extra_revokes)
{
unsigned int blks = tr->tr_reserved;
unsigned int revokes = tr->tr_revokes;
unsigned int revoke_blks;
*extra_revokes = 0;
if (revokes) {
revoke_blks = DIV_ROUND_UP(revokes, sdp->sd_inptrs);
*extra_revokes = revoke_blks * sdp->sd_inptrs - revokes;
blks += revoke_blks;
}
__gfs2_log_reserve(sdp, blks, GFS2_LOG_FLUSH_MIN_BLOCKS);
}
/**
* log_distance - Compute distance between two journal blocks
* @sdp: The GFS2 superblock
* @newer: The most recent journal block of the pair
* @older: The older journal block of the pair
*
* Compute the distance (in the journal direction) between two
* blocks in the journal
*
* Returns: the distance in blocks
*/
static inline unsigned int log_distance(struct gfs2_sbd *sdp, unsigned int newer,
unsigned int older)
{
int dist;
dist = newer - older;
if (dist < 0)
dist += sdp->sd_jdesc->jd_blocks;
return dist;
}
/**
* calc_reserved - Calculate the number of blocks to keep reserved
* @sdp: The GFS2 superblock
*
* This is complex. We need to reserve room for all our currently used
* metadata blocks (e.g. normal file I/O rewriting file time stamps) and
* all our journaled data blocks for journaled files (e.g. files in the
* meta_fs like rindex, or files for which chattr +j was done.)
* If we don't reserve enough space, corruption will follow.
*
* We can have metadata blocks and jdata blocks in the same journal. Each
* type gets its own log descriptor, for which we need to reserve a block.
* In fact, each type has the potential for needing more than one log descriptor
* in cases where we have more blocks than will fit in a log descriptor.
* Metadata journal entries take up half the space of journaled buffer entries.
*
* Also, we need to reserve blocks for revoke journal entries and one for an
* overall header for the lot.
*
* Returns: the number of blocks reserved
*/
static unsigned int calc_reserved(struct gfs2_sbd *sdp)
{
unsigned int reserved = GFS2_LOG_FLUSH_MIN_BLOCKS;
unsigned int blocks;
struct gfs2_trans *tr = sdp->sd_log_tr;
if (tr) {
blocks = tr->tr_num_buf_new - tr->tr_num_buf_rm;
reserved += blocks + DIV_ROUND_UP(blocks, buf_limit(sdp));
blocks = tr->tr_num_databuf_new - tr->tr_num_databuf_rm;
reserved += blocks + DIV_ROUND_UP(blocks, databuf_limit(sdp));
}
return reserved;
}
static void log_pull_tail(struct gfs2_sbd *sdp)
{
unsigned int new_tail = sdp->sd_log_flush_tail;
unsigned int dist;
if (new_tail == sdp->sd_log_tail)
return;
dist = log_distance(sdp, new_tail, sdp->sd_log_tail);
ail2_empty(sdp, new_tail);
gfs2_log_release(sdp, dist);
sdp->sd_log_tail = new_tail;
}
void log_flush_wait(struct gfs2_sbd *sdp)
{
DEFINE_WAIT(wait);
if (atomic_read(&sdp->sd_log_in_flight)) {
do {
prepare_to_wait(&sdp->sd_log_flush_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (atomic_read(&sdp->sd_log_in_flight))
io_schedule();
} while(atomic_read(&sdp->sd_log_in_flight));
finish_wait(&sdp->sd_log_flush_wait, &wait);
}
}
static int ip_cmp(void *priv, const struct list_head *a, const struct list_head *b)
{
struct gfs2_inode *ipa, *ipb;
ipa = list_entry(a, struct gfs2_inode, i_ordered);
ipb = list_entry(b, struct gfs2_inode, i_ordered);
if (ipa->i_no_addr < ipb->i_no_addr)
return -1;
if (ipa->i_no_addr > ipb->i_no_addr)
return 1;
return 0;
}
static void __ordered_del_inode(struct gfs2_inode *ip)
{
if (!list_empty(&ip->i_ordered))
list_del_init(&ip->i_ordered);
}
static void gfs2_ordered_write(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip;
LIST_HEAD(written);
spin_lock(&sdp->sd_ordered_lock);
list_sort(NULL, &sdp->sd_log_ordered, &ip_cmp);
while (!list_empty(&sdp->sd_log_ordered)) {
ip = list_first_entry(&sdp->sd_log_ordered, struct gfs2_inode, i_ordered);
if (ip->i_inode.i_mapping->nrpages == 0) {
__ordered_del_inode(ip);
continue;
}
list_move(&ip->i_ordered, &written);
spin_unlock(&sdp->sd_ordered_lock);
filemap_fdatawrite(ip->i_inode.i_mapping);
spin_lock(&sdp->sd_ordered_lock);
}
list_splice(&written, &sdp->sd_log_ordered);
spin_unlock(&sdp->sd_ordered_lock);
}
static void gfs2_ordered_wait(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip;
spin_lock(&sdp->sd_ordered_lock);
while (!list_empty(&sdp->sd_log_ordered)) {
ip = list_first_entry(&sdp->sd_log_ordered, struct gfs2_inode, i_ordered);
__ordered_del_inode(ip);
if (ip->i_inode.i_mapping->nrpages == 0)
continue;
spin_unlock(&sdp->sd_ordered_lock);
filemap_fdatawait(ip->i_inode.i_mapping);
spin_lock(&sdp->sd_ordered_lock);
}
spin_unlock(&sdp->sd_ordered_lock);
}
void gfs2_ordered_del_inode(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
spin_lock(&sdp->sd_ordered_lock);
__ordered_del_inode(ip);
spin_unlock(&sdp->sd_ordered_lock);
}
void gfs2_add_revoke(struct gfs2_sbd *sdp, struct gfs2_bufdata *bd)
{
struct buffer_head *bh = bd->bd_bh;
struct gfs2_glock *gl = bd->bd_gl;
sdp->sd_log_num_revoke++;
if (atomic_inc_return(&gl->gl_revokes) == 1)
gfs2_glock_hold(gl);
bh->b_private = NULL;
bd->bd_blkno = bh->b_blocknr;
gfs2_remove_from_ail(bd); /* drops ref on bh */
bd->bd_bh = NULL;
set_bit(GLF_LFLUSH, &gl->gl_flags);
list_add(&bd->bd_list, &sdp->sd_log_revokes);
}
void gfs2_glock_remove_revoke(struct gfs2_glock *gl)
{
if (atomic_dec_return(&gl->gl_revokes) == 0) {
clear_bit(GLF_LFLUSH, &gl->gl_flags);
gfs2_glock_queue_put(gl);
}
}
/**
* gfs2_flush_revokes - Add as many revokes to the system transaction as we can
* @sdp: The GFS2 superblock
*
* Our usual strategy is to defer writing revokes as much as we can in the hope
* that we'll eventually overwrite the journal, which will make those revokes
* go away. This changes when we flush the log: at that point, there will
* likely be some left-over space in the last revoke block of that transaction.
* We can fill that space with additional revokes for blocks that have already
* been written back. This will basically come at no cost now, and will save
* us from having to keep track of those blocks on the AIL2 list later.
*/
void gfs2_flush_revokes(struct gfs2_sbd *sdp)
{
/* number of revokes we still have room for */
unsigned int max_revokes = atomic_read(&sdp->sd_log_revokes_available);
gfs2_log_lock(sdp);
gfs2_ail1_empty(sdp, max_revokes);
gfs2_log_unlock(sdp);
}
/**
* gfs2_write_log_header - Write a journal log header buffer at lblock
* @sdp: The GFS2 superblock
* @jd: journal descriptor of the journal to which we are writing
* @seq: sequence number
* @tail: tail of the log
* @lblock: value for lh_blkno (block number relative to start of journal)
* @flags: log header flags GFS2_LOG_HEAD_*
* @op_flags: flags to pass to the bio
*
* Returns: the initialized log buffer descriptor
*/
void gfs2_write_log_header(struct gfs2_sbd *sdp, struct gfs2_jdesc *jd,
u64 seq, u32 tail, u32 lblock, u32 flags,
blk_opf_t op_flags)
{
struct gfs2_log_header *lh;
u32 hash, crc;
struct page *page;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct timespec64 tv;
struct super_block *sb = sdp->sd_vfs;
u64 dblock;
if (gfs2_withdrawn(sdp))
return;
page = mempool_alloc(gfs2_page_pool, GFP_NOIO);
lh = page_address(page);
clear_page(lh);
lh->lh_header.mh_magic = cpu_to_be32(GFS2_MAGIC);
lh->lh_header.mh_type = cpu_to_be32(GFS2_METATYPE_LH);
lh->lh_header.__pad0 = cpu_to_be64(0);
lh->lh_header.mh_format = cpu_to_be32(GFS2_FORMAT_LH);
lh->lh_header.mh_jid = cpu_to_be32(sdp->sd_jdesc->jd_jid);
lh->lh_sequence = cpu_to_be64(seq);
lh->lh_flags = cpu_to_be32(flags);
lh->lh_tail = cpu_to_be32(tail);
lh->lh_blkno = cpu_to_be32(lblock);
hash = ~crc32(~0, lh, LH_V1_SIZE);
lh->lh_hash = cpu_to_be32(hash);
ktime_get_coarse_real_ts64(&tv);
lh->lh_nsec = cpu_to_be32(tv.tv_nsec);
lh->lh_sec = cpu_to_be64(tv.tv_sec);
if (!list_empty(&jd->extent_list))
dblock = gfs2_log_bmap(jd, lblock);
else {
unsigned int extlen;
int ret;
extlen = 1;
ret = gfs2_get_extent(jd->jd_inode, lblock, &dblock, &extlen);
if (gfs2_assert_withdraw(sdp, ret == 0))
return;
}
lh->lh_addr = cpu_to_be64(dblock);
lh->lh_jinode = cpu_to_be64(GFS2_I(jd->jd_inode)->i_no_addr);
/* We may only write local statfs, quota, etc., when writing to our
own journal. The values are left 0 when recovering a journal
different from our own. */
if (!(flags & GFS2_LOG_HEAD_RECOVERY)) {
lh->lh_statfs_addr =
cpu_to_be64(GFS2_I(sdp->sd_sc_inode)->i_no_addr);
lh->lh_quota_addr =
cpu_to_be64(GFS2_I(sdp->sd_qc_inode)->i_no_addr);
spin_lock(&sdp->sd_statfs_spin);
lh->lh_local_total = cpu_to_be64(l_sc->sc_total);
lh->lh_local_free = cpu_to_be64(l_sc->sc_free);
lh->lh_local_dinodes = cpu_to_be64(l_sc->sc_dinodes);
spin_unlock(&sdp->sd_statfs_spin);
}
BUILD_BUG_ON(offsetof(struct gfs2_log_header, lh_crc) != LH_V1_SIZE);
crc = crc32c(~0, (void *)lh + LH_V1_SIZE + 4,
sb->s_blocksize - LH_V1_SIZE - 4);
lh->lh_crc = cpu_to_be32(crc);
gfs2_log_write(sdp, jd, page, sb->s_blocksize, 0, dblock);
gfs2_log_submit_bio(&jd->jd_log_bio, REQ_OP_WRITE | op_flags);
}
/**
* log_write_header - Get and initialize a journal header buffer
* @sdp: The GFS2 superblock
* @flags: The log header flags, including log header origin
*
* Returns: the initialized log buffer descriptor
*/
static void log_write_header(struct gfs2_sbd *sdp, u32 flags)
{
blk_opf_t op_flags = REQ_PREFLUSH | REQ_FUA | REQ_META | REQ_SYNC;
gfs2_assert_withdraw(sdp, !test_bit(SDF_FROZEN, &sdp->sd_flags));
if (test_bit(SDF_NOBARRIERS, &sdp->sd_flags)) {
gfs2_ordered_wait(sdp);
log_flush_wait(sdp);
op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
}
sdp->sd_log_idle = (sdp->sd_log_flush_tail == sdp->sd_log_flush_head);
gfs2_write_log_header(sdp, sdp->sd_jdesc, sdp->sd_log_sequence++,
sdp->sd_log_flush_tail, sdp->sd_log_flush_head,
flags, op_flags);
gfs2_log_incr_head(sdp);
log_flush_wait(sdp);
log_pull_tail(sdp);
gfs2_log_update_head(sdp);
}
/**
* gfs2_ail_drain - drain the ail lists after a withdraw
* @sdp: Pointer to GFS2 superblock
*/
void gfs2_ail_drain(struct gfs2_sbd *sdp)
{
struct gfs2_trans *tr;
spin_lock(&sdp->sd_ail_lock);
/*
* For transactions on the sd_ail1_list we need to drain both the
* ail1 and ail2 lists. That's because function gfs2_ail1_start_one
* (temporarily) moves items from its tr_ail1 list to tr_ail2 list
* before revokes are sent for that block. Items on the sd_ail2_list
* should have already gotten beyond that point, so no need.
*/
while (!list_empty(&sdp->sd_ail1_list)) {
tr = list_first_entry(&sdp->sd_ail1_list, struct gfs2_trans,
tr_list);
gfs2_ail_empty_tr(sdp, tr, &tr->tr_ail1_list);
gfs2_ail_empty_tr(sdp, tr, &tr->tr_ail2_list);
list_del(&tr->tr_list);
gfs2_trans_free(sdp, tr);
}
while (!list_empty(&sdp->sd_ail2_list)) {
tr = list_first_entry(&sdp->sd_ail2_list, struct gfs2_trans,
tr_list);
gfs2_ail_empty_tr(sdp, tr, &tr->tr_ail2_list);
list_del(&tr->tr_list);
gfs2_trans_free(sdp, tr);
}
gfs2_drain_revokes(sdp);
spin_unlock(&sdp->sd_ail_lock);
}
/**
* empty_ail1_list - try to start IO and empty the ail1 list
* @sdp: Pointer to GFS2 superblock
*/
static void empty_ail1_list(struct gfs2_sbd *sdp)
{
unsigned long start = jiffies;
for (;;) {
if (time_after(jiffies, start + (HZ * 600))) {
fs_err(sdp, "Error: In %s for 10 minutes! t=%d\n",
__func__, current->journal_info ? 1 : 0);
dump_ail_list(sdp);
return;
}
gfs2_ail1_start(sdp);
gfs2_ail1_wait(sdp);
if (gfs2_ail1_empty(sdp, 0))
return;
}
}
/**
* trans_drain - drain the buf and databuf queue for a failed transaction
* @tr: the transaction to drain
*
* When this is called, we're taking an error exit for a log write that failed
* but since we bypassed the after_commit functions, we need to remove the
* items from the buf and databuf queue.
*/
static void trans_drain(struct gfs2_trans *tr)
{
struct gfs2_bufdata *bd;
struct list_head *head;
if (!tr)
return;
head = &tr->tr_buf;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
if (!list_empty(&bd->bd_ail_st_list))
gfs2_remove_from_ail(bd);
kmem_cache_free(gfs2_bufdata_cachep, bd);
}
head = &tr->tr_databuf;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
if (!list_empty(&bd->bd_ail_st_list))
gfs2_remove_from_ail(bd);
kmem_cache_free(gfs2_bufdata_cachep, bd);
}
}
/**
* gfs2_log_flush - flush incore transaction(s)
* @sdp: The filesystem
* @gl: The glock structure to flush. If NULL, flush the whole incore log
* @flags: The log header flags: GFS2_LOG_HEAD_FLUSH_* and debug flags
*
*/
void gfs2_log_flush(struct gfs2_sbd *sdp, struct gfs2_glock *gl, u32 flags)
{
struct gfs2_trans *tr = NULL;
unsigned int reserved_blocks = 0, used_blocks = 0;
bool frozen = test_bit(SDF_FROZEN, &sdp->sd_flags);
unsigned int first_log_head;
unsigned int reserved_revokes = 0;
down_write(&sdp->sd_log_flush_lock);
trace_gfs2_log_flush(sdp, 1, flags);
repeat:
/*
* Do this check while holding the log_flush_lock to prevent new
* buffers from being added to the ail via gfs2_pin()
*/
if (gfs2_withdrawn(sdp) || !test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))
goto out;
/* Log might have been flushed while we waited for the flush lock */
if (gl && !test_bit(GLF_LFLUSH, &gl->gl_flags))
goto out;
first_log_head = sdp->sd_log_head;
sdp->sd_log_flush_head = first_log_head;
tr = sdp->sd_log_tr;
if (tr || sdp->sd_log_num_revoke) {
if (reserved_blocks)
gfs2_log_release(sdp, reserved_blocks);
reserved_blocks = sdp->sd_log_blks_reserved;
reserved_revokes = sdp->sd_log_num_revoke;
if (tr) {
sdp->sd_log_tr = NULL;
tr->tr_first = first_log_head;
if (unlikely(frozen)) {
if (gfs2_assert_withdraw_delayed(sdp,
!tr->tr_num_buf_new && !tr->tr_num_databuf_new))
goto out_withdraw;
}
}
} else if (!reserved_blocks) {
unsigned int taboo_blocks = GFS2_LOG_FLUSH_MIN_BLOCKS;
reserved_blocks = GFS2_LOG_FLUSH_MIN_BLOCKS;
if (current == sdp->sd_logd_process)
taboo_blocks = 0;
if (!__gfs2_log_try_reserve(sdp, reserved_blocks, taboo_blocks)) {
up_write(&sdp->sd_log_flush_lock);
__gfs2_log_reserve(sdp, reserved_blocks, taboo_blocks);
down_write(&sdp->sd_log_flush_lock);
goto repeat;
}
BUG_ON(sdp->sd_log_num_revoke);
}
if (flags & GFS2_LOG_HEAD_FLUSH_SHUTDOWN)
clear_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags);
if (unlikely(frozen))
if (gfs2_assert_withdraw_delayed(sdp, !reserved_revokes))
goto out_withdraw;
gfs2_ordered_write(sdp);
if (gfs2_withdrawn(sdp))
goto out_withdraw;
lops_before_commit(sdp, tr);
if (gfs2_withdrawn(sdp))
goto out_withdraw;
gfs2_log_submit_bio(&sdp->sd_jdesc->jd_log_bio, REQ_OP_WRITE);
if (gfs2_withdrawn(sdp))
goto out_withdraw;
if (sdp->sd_log_head != sdp->sd_log_flush_head) {
log_write_header(sdp, flags);
} else if (sdp->sd_log_tail != sdp->sd_log_flush_tail && !sdp->sd_log_idle) {
log_write_header(sdp, flags);
}
if (gfs2_withdrawn(sdp))
goto out_withdraw;
lops_after_commit(sdp, tr);
gfs2_log_lock(sdp);
sdp->sd_log_blks_reserved = 0;
spin_lock(&sdp->sd_ail_lock);
if (tr && !list_empty(&tr->tr_ail1_list)) {
list_add(&tr->tr_list, &sdp->sd_ail1_list);
tr = NULL;
}
spin_unlock(&sdp->sd_ail_lock);
gfs2_log_unlock(sdp);
if (!(flags & GFS2_LOG_HEAD_FLUSH_NORMAL)) {
if (!sdp->sd_log_idle) {
empty_ail1_list(sdp);
if (gfs2_withdrawn(sdp))
goto out_withdraw;
log_write_header(sdp, flags);
}
if (flags & (GFS2_LOG_HEAD_FLUSH_SHUTDOWN |
GFS2_LOG_HEAD_FLUSH_FREEZE))
gfs2_log_shutdown(sdp);
}
out_end:
used_blocks = log_distance(sdp, sdp->sd_log_flush_head, first_log_head);
reserved_revokes += atomic_read(&sdp->sd_log_revokes_available);
atomic_set(&sdp->sd_log_revokes_available, sdp->sd_ldptrs);
gfs2_assert_withdraw(sdp, reserved_revokes % sdp->sd_inptrs == sdp->sd_ldptrs);
if (reserved_revokes > sdp->sd_ldptrs)
reserved_blocks += (reserved_revokes - sdp->sd_ldptrs) / sdp->sd_inptrs;
out:
if (used_blocks != reserved_blocks) {
gfs2_assert_withdraw_delayed(sdp, used_blocks < reserved_blocks);
gfs2_log_release(sdp, reserved_blocks - used_blocks);
}
up_write(&sdp->sd_log_flush_lock);
gfs2_trans_free(sdp, tr);
if (gfs2_withdrawing(sdp))
gfs2_withdraw(sdp);
trace_gfs2_log_flush(sdp, 0, flags);
return;
out_withdraw:
trans_drain(tr);
/**
* If the tr_list is empty, we're withdrawing during a log
* flush that targets a transaction, but the transaction was
* never queued onto any of the ail lists. Here we add it to
* ail1 just so that ail_drain() will find and free it.
*/
spin_lock(&sdp->sd_ail_lock);
if (tr && list_empty(&tr->tr_list))
list_add(&tr->tr_list, &sdp->sd_ail1_list);
spin_unlock(&sdp->sd_ail_lock);
tr = NULL;
goto out_end;
}
/**
* gfs2_merge_trans - Merge a new transaction into a cached transaction
* @sdp: the filesystem
* @new: New transaction to be merged
*/
static void gfs2_merge_trans(struct gfs2_sbd *sdp, struct gfs2_trans *new)
{
struct gfs2_trans *old = sdp->sd_log_tr;
WARN_ON_ONCE(!test_bit(TR_ATTACHED, &old->tr_flags));
old->tr_num_buf_new += new->tr_num_buf_new;
old->tr_num_databuf_new += new->tr_num_databuf_new;
old->tr_num_buf_rm += new->tr_num_buf_rm;
old->tr_num_databuf_rm += new->tr_num_databuf_rm;
old->tr_revokes += new->tr_revokes;
old->tr_num_revoke += new->tr_num_revoke;
list_splice_tail_init(&new->tr_databuf, &old->tr_databuf);
list_splice_tail_init(&new->tr_buf, &old->tr_buf);
spin_lock(&sdp->sd_ail_lock);
list_splice_tail_init(&new->tr_ail1_list, &old->tr_ail1_list);
list_splice_tail_init(&new->tr_ail2_list, &old->tr_ail2_list);
spin_unlock(&sdp->sd_ail_lock);
}
static void log_refund(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
unsigned int reserved;
unsigned int unused;
unsigned int maxres;
gfs2_log_lock(sdp);
if (sdp->sd_log_tr) {
gfs2_merge_trans(sdp, tr);
} else if (tr->tr_num_buf_new || tr->tr_num_databuf_new) {
gfs2_assert_withdraw(sdp, !test_bit(TR_ONSTACK, &tr->tr_flags));
sdp->sd_log_tr = tr;
set_bit(TR_ATTACHED, &tr->tr_flags);
}
reserved = calc_reserved(sdp);
maxres = sdp->sd_log_blks_reserved + tr->tr_reserved;
gfs2_assert_withdraw(sdp, maxres >= reserved);
unused = maxres - reserved;
if (unused)
gfs2_log_release(sdp, unused);
sdp->sd_log_blks_reserved = reserved;
gfs2_log_unlock(sdp);
}
static inline int gfs2_jrnl_flush_reqd(struct gfs2_sbd *sdp)
{
return atomic_read(&sdp->sd_log_pinned) +
atomic_read(&sdp->sd_log_blks_needed) >=
atomic_read(&sdp->sd_log_thresh1);
}
static inline int gfs2_ail_flush_reqd(struct gfs2_sbd *sdp)
{
return sdp->sd_jdesc->jd_blocks -
atomic_read(&sdp->sd_log_blks_free) +
atomic_read(&sdp->sd_log_blks_needed) >=
atomic_read(&sdp->sd_log_thresh2);
}
/**
* gfs2_log_commit - Commit a transaction to the log
* @sdp: the filesystem
* @tr: the transaction
*
* We wake up gfs2_logd if the number of pinned blocks exceed thresh1
* or the total number of used blocks (pinned blocks plus AIL blocks)
* is greater than thresh2.
*
* At mount time thresh1 is 2/5ths of journal size, thresh2 is 4/5ths of
* journal size.
*
* Returns: errno
*/
void gfs2_log_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
log_refund(sdp, tr);
if (gfs2_ail_flush_reqd(sdp) || gfs2_jrnl_flush_reqd(sdp))
wake_up(&sdp->sd_logd_waitq);
}
/**
* gfs2_log_shutdown - write a shutdown header into a journal
* @sdp: the filesystem
*
*/
static void gfs2_log_shutdown(struct gfs2_sbd *sdp)
{
gfs2_assert_withdraw(sdp, !sdp->sd_log_blks_reserved);
gfs2_assert_withdraw(sdp, !sdp->sd_log_num_revoke);
gfs2_assert_withdraw(sdp, list_empty(&sdp->sd_ail1_list));
log_write_header(sdp, GFS2_LOG_HEAD_UNMOUNT | GFS2_LFC_SHUTDOWN);
log_pull_tail(sdp);
gfs2_assert_warn(sdp, sdp->sd_log_head == sdp->sd_log_tail);
gfs2_assert_warn(sdp, list_empty(&sdp->sd_ail2_list));
}
/**
* gfs2_logd - Update log tail as Active Items get flushed to in-place blocks
* @data: Pointer to GFS2 superblock
*
* Also, periodically check to make sure that we're using the most recent
* journal index.
*/
int gfs2_logd(void *data)
{
struct gfs2_sbd *sdp = data;
unsigned long t = 1;
while (!kthread_should_stop()) {
if (gfs2_withdrawn(sdp))
break;
/* Check for errors writing to the journal */
if (sdp->sd_log_error) {
gfs2_lm(sdp,
"GFS2: fsid=%s: error %d: "
"withdrawing the file system to "
"prevent further damage.\n",
sdp->sd_fsname, sdp->sd_log_error);
gfs2_withdraw(sdp);
break;
}
if (gfs2_jrnl_flush_reqd(sdp) || t == 0) {
gfs2_ail1_empty(sdp, 0);
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_LOGD_JFLUSH_REQD);
}
if (test_bit(SDF_FORCE_AIL_FLUSH, &sdp->sd_flags) ||
gfs2_ail_flush_reqd(sdp)) {
clear_bit(SDF_FORCE_AIL_FLUSH, &sdp->sd_flags);
gfs2_ail1_start(sdp);
gfs2_ail1_wait(sdp);
gfs2_ail1_empty(sdp, 0);
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_LOGD_AIL_FLUSH_REQD);
}
t = gfs2_tune_get(sdp, gt_logd_secs) * HZ;
try_to_freeze();
t = wait_event_interruptible_timeout(sdp->sd_logd_waitq,
test_bit(SDF_FORCE_AIL_FLUSH, &sdp->sd_flags) ||
gfs2_ail_flush_reqd(sdp) ||
gfs2_jrnl_flush_reqd(sdp) ||
sdp->sd_log_error ||
gfs2_withdrawn(sdp) ||
kthread_should_stop(),
t);
}
return 0;
}
| linux-master | fs/gfs2/log.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/bio.h>
#include <linux/posix_acl.h>
#include <linux/security.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "recovery.h"
#include "rgrp.h"
#include "util.h"
#include "trans.h"
#include "dir.h"
#include "lops.h"
struct workqueue_struct *gfs2_freeze_wq;
extern struct workqueue_struct *gfs2_control_wq;
static void gfs2_ail_error(struct gfs2_glock *gl, const struct buffer_head *bh)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
fs_err(sdp,
"AIL buffer %p: blocknr %llu state 0x%08lx mapping %p page "
"state 0x%lx\n",
bh, (unsigned long long)bh->b_blocknr, bh->b_state,
bh->b_folio->mapping, bh->b_folio->flags);
fs_err(sdp, "AIL glock %u:%llu mapping %p\n",
gl->gl_name.ln_type, gl->gl_name.ln_number,
gfs2_glock2aspace(gl));
gfs2_lm(sdp, "AIL error\n");
gfs2_withdraw_delayed(sdp);
}
/**
* __gfs2_ail_flush - remove all buffers for a given lock from the AIL
* @gl: the glock
* @fsync: set when called from fsync (not all buffers will be clean)
* @nr_revokes: Number of buffers to revoke
*
* None of the buffers should be dirty, locked, or pinned.
*/
static void __gfs2_ail_flush(struct gfs2_glock *gl, bool fsync,
unsigned int nr_revokes)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct list_head *head = &gl->gl_ail_list;
struct gfs2_bufdata *bd, *tmp;
struct buffer_head *bh;
const unsigned long b_state = (1UL << BH_Dirty)|(1UL << BH_Pinned)|(1UL << BH_Lock);
gfs2_log_lock(sdp);
spin_lock(&sdp->sd_ail_lock);
list_for_each_entry_safe_reverse(bd, tmp, head, bd_ail_gl_list) {
if (nr_revokes == 0)
break;
bh = bd->bd_bh;
if (bh->b_state & b_state) {
if (fsync)
continue;
gfs2_ail_error(gl, bh);
}
gfs2_trans_add_revoke(sdp, bd);
nr_revokes--;
}
GLOCK_BUG_ON(gl, !fsync && atomic_read(&gl->gl_ail_count));
spin_unlock(&sdp->sd_ail_lock);
gfs2_log_unlock(sdp);
}
static int gfs2_ail_empty_gl(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_trans tr;
unsigned int revokes;
int ret = 0;
revokes = atomic_read(&gl->gl_ail_count);
if (!revokes) {
bool have_revokes;
bool log_in_flight;
/*
* We have nothing on the ail, but there could be revokes on
* the sdp revoke queue, in which case, we still want to flush
* the log and wait for it to finish.
*
* If the sdp revoke list is empty too, we might still have an
* io outstanding for writing revokes, so we should wait for
* it before returning.
*
* If none of these conditions are true, our revokes are all
* flushed and we can return.
*/
gfs2_log_lock(sdp);
have_revokes = !list_empty(&sdp->sd_log_revokes);
log_in_flight = atomic_read(&sdp->sd_log_in_flight);
gfs2_log_unlock(sdp);
if (have_revokes)
goto flush;
if (log_in_flight)
log_flush_wait(sdp);
return 0;
}
memset(&tr, 0, sizeof(tr));
set_bit(TR_ONSTACK, &tr.tr_flags);
ret = __gfs2_trans_begin(&tr, sdp, 0, revokes, _RET_IP_);
if (ret) {
fs_err(sdp, "Transaction error %d: Unable to write revokes.", ret);
goto flush;
}
__gfs2_ail_flush(gl, 0, revokes);
gfs2_trans_end(sdp);
flush:
if (!ret)
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_AIL_EMPTY_GL);
return ret;
}
void gfs2_ail_flush(struct gfs2_glock *gl, bool fsync)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
unsigned int revokes = atomic_read(&gl->gl_ail_count);
int ret;
if (!revokes)
return;
ret = gfs2_trans_begin(sdp, 0, revokes);
if (ret)
return;
__gfs2_ail_flush(gl, fsync, revokes);
gfs2_trans_end(sdp);
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_AIL_FLUSH);
}
/**
* gfs2_rgrp_metasync - sync out the metadata of a resource group
* @gl: the glock protecting the resource group
*
*/
static int gfs2_rgrp_metasync(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct address_space *metamapping = &sdp->sd_aspace;
struct gfs2_rgrpd *rgd = gfs2_glock2rgrp(gl);
const unsigned bsize = sdp->sd_sb.sb_bsize;
loff_t start = (rgd->rd_addr * bsize) & PAGE_MASK;
loff_t end = PAGE_ALIGN((rgd->rd_addr + rgd->rd_length) * bsize) - 1;
int error;
filemap_fdatawrite_range(metamapping, start, end);
error = filemap_fdatawait_range(metamapping, start, end);
WARN_ON_ONCE(error && !gfs2_withdrawn(sdp));
mapping_set_error(metamapping, error);
if (error)
gfs2_io_error(sdp);
return error;
}
/**
* rgrp_go_sync - sync out the metadata for this glock
* @gl: the glock
*
* Called when demoting or unlocking an EX glock. We must flush
* to disk all dirty buffers/pages relating to this glock, and must not
* return to caller to demote/unlock the glock until I/O is complete.
*/
static int rgrp_go_sync(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_rgrpd *rgd = gfs2_glock2rgrp(gl);
int error;
if (!rgd || !test_and_clear_bit(GLF_DIRTY, &gl->gl_flags))
return 0;
GLOCK_BUG_ON(gl, gl->gl_state != LM_ST_EXCLUSIVE);
gfs2_log_flush(sdp, gl, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_RGRP_GO_SYNC);
error = gfs2_rgrp_metasync(gl);
if (!error)
error = gfs2_ail_empty_gl(gl);
gfs2_free_clones(rgd);
return error;
}
/**
* rgrp_go_inval - invalidate the metadata for this glock
* @gl: the glock
* @flags:
*
* We never used LM_ST_DEFERRED with resource groups, so that we
* should always see the metadata flag set here.
*
*/
static void rgrp_go_inval(struct gfs2_glock *gl, int flags)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct address_space *mapping = &sdp->sd_aspace;
struct gfs2_rgrpd *rgd = gfs2_glock2rgrp(gl);
const unsigned bsize = sdp->sd_sb.sb_bsize;
loff_t start, end;
if (!rgd)
return;
start = (rgd->rd_addr * bsize) & PAGE_MASK;
end = PAGE_ALIGN((rgd->rd_addr + rgd->rd_length) * bsize) - 1;
gfs2_rgrp_brelse(rgd);
WARN_ON_ONCE(!(flags & DIO_METADATA));
truncate_inode_pages_range(mapping, start, end);
}
static void gfs2_rgrp_go_dump(struct seq_file *seq, const struct gfs2_glock *gl,
const char *fs_id_buf)
{
struct gfs2_rgrpd *rgd = gl->gl_object;
if (rgd)
gfs2_rgrp_dump(seq, rgd, fs_id_buf);
}
static struct gfs2_inode *gfs2_glock2inode(struct gfs2_glock *gl)
{
struct gfs2_inode *ip;
spin_lock(&gl->gl_lockref.lock);
ip = gl->gl_object;
if (ip)
set_bit(GIF_GLOP_PENDING, &ip->i_flags);
spin_unlock(&gl->gl_lockref.lock);
return ip;
}
struct gfs2_rgrpd *gfs2_glock2rgrp(struct gfs2_glock *gl)
{
struct gfs2_rgrpd *rgd;
spin_lock(&gl->gl_lockref.lock);
rgd = gl->gl_object;
spin_unlock(&gl->gl_lockref.lock);
return rgd;
}
static void gfs2_clear_glop_pending(struct gfs2_inode *ip)
{
if (!ip)
return;
clear_bit_unlock(GIF_GLOP_PENDING, &ip->i_flags);
wake_up_bit(&ip->i_flags, GIF_GLOP_PENDING);
}
/**
* gfs2_inode_metasync - sync out the metadata of an inode
* @gl: the glock protecting the inode
*
*/
int gfs2_inode_metasync(struct gfs2_glock *gl)
{
struct address_space *metamapping = gfs2_glock2aspace(gl);
int error;
filemap_fdatawrite(metamapping);
error = filemap_fdatawait(metamapping);
if (error)
gfs2_io_error(gl->gl_name.ln_sbd);
return error;
}
/**
* inode_go_sync - Sync the dirty metadata of an inode
* @gl: the glock protecting the inode
*
*/
static int inode_go_sync(struct gfs2_glock *gl)
{
struct gfs2_inode *ip = gfs2_glock2inode(gl);
int isreg = ip && S_ISREG(ip->i_inode.i_mode);
struct address_space *metamapping = gfs2_glock2aspace(gl);
int error = 0, ret;
if (isreg) {
if (test_and_clear_bit(GIF_SW_PAGED, &ip->i_flags))
unmap_shared_mapping_range(ip->i_inode.i_mapping, 0, 0);
inode_dio_wait(&ip->i_inode);
}
if (!test_and_clear_bit(GLF_DIRTY, &gl->gl_flags))
goto out;
GLOCK_BUG_ON(gl, gl->gl_state != LM_ST_EXCLUSIVE);
gfs2_log_flush(gl->gl_name.ln_sbd, gl, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_INODE_GO_SYNC);
filemap_fdatawrite(metamapping);
if (isreg) {
struct address_space *mapping = ip->i_inode.i_mapping;
filemap_fdatawrite(mapping);
error = filemap_fdatawait(mapping);
mapping_set_error(mapping, error);
}
ret = gfs2_inode_metasync(gl);
if (!error)
error = ret;
ret = gfs2_ail_empty_gl(gl);
if (!error)
error = ret;
/*
* Writeback of the data mapping may cause the dirty flag to be set
* so we have to clear it again here.
*/
smp_mb__before_atomic();
clear_bit(GLF_DIRTY, &gl->gl_flags);
out:
gfs2_clear_glop_pending(ip);
return error;
}
/**
* inode_go_inval - prepare a inode glock to be released
* @gl: the glock
* @flags:
*
* Normally we invalidate everything, but if we are moving into
* LM_ST_DEFERRED from LM_ST_SHARED or LM_ST_EXCLUSIVE then we
* can keep hold of the metadata, since it won't have changed.
*
*/
static void inode_go_inval(struct gfs2_glock *gl, int flags)
{
struct gfs2_inode *ip = gfs2_glock2inode(gl);
if (flags & DIO_METADATA) {
struct address_space *mapping = gfs2_glock2aspace(gl);
truncate_inode_pages(mapping, 0);
if (ip) {
set_bit(GLF_INSTANTIATE_NEEDED, &gl->gl_flags);
forget_all_cached_acls(&ip->i_inode);
security_inode_invalidate_secctx(&ip->i_inode);
gfs2_dir_hash_inval(ip);
}
}
if (ip == GFS2_I(gl->gl_name.ln_sbd->sd_rindex)) {
gfs2_log_flush(gl->gl_name.ln_sbd, NULL,
GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_INODE_GO_INVAL);
gl->gl_name.ln_sbd->sd_rindex_uptodate = 0;
}
if (ip && S_ISREG(ip->i_inode.i_mode))
truncate_inode_pages(ip->i_inode.i_mapping, 0);
gfs2_clear_glop_pending(ip);
}
/**
* inode_go_demote_ok - Check to see if it's ok to unlock an inode glock
* @gl: the glock
*
* Returns: 1 if it's ok
*/
static int inode_go_demote_ok(const struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (sdp->sd_jindex == gl->gl_object || sdp->sd_rindex == gl->gl_object)
return 0;
return 1;
}
static int gfs2_dinode_in(struct gfs2_inode *ip, const void *buf)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
const struct gfs2_dinode *str = buf;
struct timespec64 atime;
u16 height, depth;
umode_t mode = be32_to_cpu(str->di_mode);
struct inode *inode = &ip->i_inode;
bool is_new = inode->i_state & I_NEW;
if (unlikely(ip->i_no_addr != be64_to_cpu(str->di_num.no_addr)))
goto corrupt;
if (unlikely(!is_new && inode_wrong_type(inode, mode)))
goto corrupt;
ip->i_no_formal_ino = be64_to_cpu(str->di_num.no_formal_ino);
inode->i_mode = mode;
if (is_new) {
inode->i_rdev = 0;
switch (mode & S_IFMT) {
case S_IFBLK:
case S_IFCHR:
inode->i_rdev = MKDEV(be32_to_cpu(str->di_major),
be32_to_cpu(str->di_minor));
break;
}
}
i_uid_write(inode, be32_to_cpu(str->di_uid));
i_gid_write(inode, be32_to_cpu(str->di_gid));
set_nlink(inode, be32_to_cpu(str->di_nlink));
i_size_write(inode, be64_to_cpu(str->di_size));
gfs2_set_inode_blocks(inode, be64_to_cpu(str->di_blocks));
atime.tv_sec = be64_to_cpu(str->di_atime);
atime.tv_nsec = be32_to_cpu(str->di_atime_nsec);
if (timespec64_compare(&inode->i_atime, &atime) < 0)
inode->i_atime = atime;
inode->i_mtime.tv_sec = be64_to_cpu(str->di_mtime);
inode->i_mtime.tv_nsec = be32_to_cpu(str->di_mtime_nsec);
inode_set_ctime(inode, be64_to_cpu(str->di_ctime),
be32_to_cpu(str->di_ctime_nsec));
ip->i_goal = be64_to_cpu(str->di_goal_meta);
ip->i_generation = be64_to_cpu(str->di_generation);
ip->i_diskflags = be32_to_cpu(str->di_flags);
ip->i_eattr = be64_to_cpu(str->di_eattr);
/* i_diskflags and i_eattr must be set before gfs2_set_inode_flags() */
gfs2_set_inode_flags(inode);
height = be16_to_cpu(str->di_height);
if (unlikely(height > sdp->sd_max_height))
goto corrupt;
ip->i_height = (u8)height;
depth = be16_to_cpu(str->di_depth);
if (unlikely(depth > GFS2_DIR_MAX_DEPTH))
goto corrupt;
ip->i_depth = (u8)depth;
ip->i_entries = be32_to_cpu(str->di_entries);
if (gfs2_is_stuffed(ip) && inode->i_size > gfs2_max_stuffed_size(ip))
goto corrupt;
if (S_ISREG(inode->i_mode))
gfs2_set_aops(inode);
return 0;
corrupt:
gfs2_consist_inode(ip);
return -EIO;
}
/**
* gfs2_inode_refresh - Refresh the incore copy of the dinode
* @ip: The GFS2 inode
*
* Returns: errno
*/
int gfs2_inode_refresh(struct gfs2_inode *ip)
{
struct buffer_head *dibh;
int error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
error = gfs2_dinode_in(ip, dibh->b_data);
brelse(dibh);
return error;
}
/**
* inode_go_instantiate - read in an inode if necessary
* @gh: The glock holder
*
* Returns: errno
*/
static int inode_go_instantiate(struct gfs2_glock *gl)
{
struct gfs2_inode *ip = gl->gl_object;
if (!ip) /* no inode to populate - read it in later */
return 0;
return gfs2_inode_refresh(ip);
}
static int inode_go_held(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
struct gfs2_inode *ip = gl->gl_object;
int error = 0;
if (!ip) /* no inode to populate - read it in later */
return 0;
if (gh->gh_state != LM_ST_DEFERRED)
inode_dio_wait(&ip->i_inode);
if ((ip->i_diskflags & GFS2_DIF_TRUNC_IN_PROG) &&
(gl->gl_state == LM_ST_EXCLUSIVE) &&
(gh->gh_state == LM_ST_EXCLUSIVE))
error = gfs2_truncatei_resume(ip);
return error;
}
/**
* inode_go_dump - print information about an inode
* @seq: The iterator
* @gl: The glock
* @fs_id_buf: file system id (may be empty)
*
*/
static void inode_go_dump(struct seq_file *seq, const struct gfs2_glock *gl,
const char *fs_id_buf)
{
struct gfs2_inode *ip = gl->gl_object;
const struct inode *inode = &ip->i_inode;
if (ip == NULL)
return;
gfs2_print_dbg(seq, "%s I: n:%llu/%llu t:%u f:0x%02lx d:0x%08x s:%llu "
"p:%lu\n", fs_id_buf,
(unsigned long long)ip->i_no_formal_ino,
(unsigned long long)ip->i_no_addr,
IF2DT(inode->i_mode), ip->i_flags,
(unsigned int)ip->i_diskflags,
(unsigned long long)i_size_read(inode),
inode->i_data.nrpages);
}
/**
* freeze_go_callback - A cluster node is requesting a freeze
* @gl: the glock
* @remote: true if this came from a different cluster node
*/
static void freeze_go_callback(struct gfs2_glock *gl, bool remote)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct super_block *sb = sdp->sd_vfs;
if (!remote ||
(gl->gl_state != LM_ST_SHARED &&
gl->gl_state != LM_ST_UNLOCKED) ||
gl->gl_demote_state != LM_ST_UNLOCKED)
return;
/*
* Try to get an active super block reference to prevent racing with
* unmount (see super_trylock_shared()). But note that unmount isn't
* the only place where a write lock on s_umount is taken, and we can
* fail here because of things like remount as well.
*/
if (down_read_trylock(&sb->s_umount)) {
atomic_inc(&sb->s_active);
up_read(&sb->s_umount);
if (!queue_work(gfs2_freeze_wq, &sdp->sd_freeze_work))
deactivate_super(sb);
}
}
/**
* freeze_go_xmote_bh - After promoting/demoting the freeze glock
* @gl: the glock
*/
static int freeze_go_xmote_bh(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_jdesc->jd_inode);
struct gfs2_glock *j_gl = ip->i_gl;
struct gfs2_log_header_host head;
int error;
if (test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags)) {
j_gl->gl_ops->go_inval(j_gl, DIO_METADATA);
error = gfs2_find_jhead(sdp->sd_jdesc, &head, false);
if (gfs2_assert_withdraw_delayed(sdp, !error))
return error;
if (gfs2_assert_withdraw_delayed(sdp, head.lh_flags &
GFS2_LOG_HEAD_UNMOUNT))
return -EIO;
sdp->sd_log_sequence = head.lh_sequence + 1;
gfs2_log_pointers_init(sdp, head.lh_blkno);
}
return 0;
}
/**
* freeze_go_demote_ok
* @gl: the glock
*
* Always returns 0
*/
static int freeze_go_demote_ok(const struct gfs2_glock *gl)
{
return 0;
}
/**
* iopen_go_callback - schedule the dcache entry for the inode to be deleted
* @gl: the glock
* @remote: true if this came from a different cluster node
*
* gl_lockref.lock lock is held while calling this
*/
static void iopen_go_callback(struct gfs2_glock *gl, bool remote)
{
struct gfs2_inode *ip = gl->gl_object;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (!remote || sb_rdonly(sdp->sd_vfs) ||
test_bit(SDF_KILL, &sdp->sd_flags))
return;
if (gl->gl_demote_state == LM_ST_UNLOCKED &&
gl->gl_state == LM_ST_SHARED && ip) {
gl->gl_lockref.count++;
if (!gfs2_queue_try_to_evict(gl))
gl->gl_lockref.count--;
}
}
/**
* inode_go_free - wake up anyone waiting for dlm's unlock ast to free it
* @gl: glock being freed
*
* For now, this is only used for the journal inode glock. In withdraw
* situations, we need to wait for the glock to be freed so that we know
* other nodes may proceed with recovery / journal replay.
*/
static void inode_go_free(struct gfs2_glock *gl)
{
/* Note that we cannot reference gl_object because it's already set
* to NULL by this point in its lifecycle. */
if (!test_bit(GLF_FREEING, &gl->gl_flags))
return;
clear_bit_unlock(GLF_FREEING, &gl->gl_flags);
wake_up_bit(&gl->gl_flags, GLF_FREEING);
}
/**
* nondisk_go_callback - used to signal when a node did a withdraw
* @gl: the nondisk glock
* @remote: true if this came from a different cluster node
*
*/
static void nondisk_go_callback(struct gfs2_glock *gl, bool remote)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
/* Ignore the callback unless it's from another node, and it's the
live lock. */
if (!remote || gl->gl_name.ln_number != GFS2_LIVE_LOCK)
return;
/* First order of business is to cancel the demote request. We don't
* really want to demote a nondisk glock. At best it's just to inform
* us of another node's withdraw. We'll keep it in SH mode. */
clear_bit(GLF_DEMOTE, &gl->gl_flags);
clear_bit(GLF_PENDING_DEMOTE, &gl->gl_flags);
/* Ignore the unlock if we're withdrawn, unmounting, or in recovery. */
if (test_bit(SDF_NORECOVERY, &sdp->sd_flags) ||
test_bit(SDF_WITHDRAWN, &sdp->sd_flags) ||
test_bit(SDF_REMOTE_WITHDRAW, &sdp->sd_flags))
return;
/* We only care when a node wants us to unlock, because that means
* they want a journal recovered. */
if (gl->gl_demote_state != LM_ST_UNLOCKED)
return;
if (sdp->sd_args.ar_spectator) {
fs_warn(sdp, "Spectator node cannot recover journals.\n");
return;
}
fs_warn(sdp, "Some node has withdrawn; checking for recovery.\n");
set_bit(SDF_REMOTE_WITHDRAW, &sdp->sd_flags);
/*
* We can't call remote_withdraw directly here or gfs2_recover_journal
* because this is called from the glock unlock function and the
* remote_withdraw needs to enqueue and dequeue the same "live" glock
* we were called from. So we queue it to the control work queue in
* lock_dlm.
*/
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work, 0);
}
const struct gfs2_glock_operations gfs2_meta_glops = {
.go_type = LM_TYPE_META,
.go_flags = GLOF_NONDISK,
};
const struct gfs2_glock_operations gfs2_inode_glops = {
.go_sync = inode_go_sync,
.go_inval = inode_go_inval,
.go_demote_ok = inode_go_demote_ok,
.go_instantiate = inode_go_instantiate,
.go_held = inode_go_held,
.go_dump = inode_go_dump,
.go_type = LM_TYPE_INODE,
.go_flags = GLOF_ASPACE | GLOF_LRU | GLOF_LVB,
.go_free = inode_go_free,
};
const struct gfs2_glock_operations gfs2_rgrp_glops = {
.go_sync = rgrp_go_sync,
.go_inval = rgrp_go_inval,
.go_instantiate = gfs2_rgrp_go_instantiate,
.go_dump = gfs2_rgrp_go_dump,
.go_type = LM_TYPE_RGRP,
.go_flags = GLOF_LVB,
};
const struct gfs2_glock_operations gfs2_freeze_glops = {
.go_xmote_bh = freeze_go_xmote_bh,
.go_demote_ok = freeze_go_demote_ok,
.go_callback = freeze_go_callback,
.go_type = LM_TYPE_NONDISK,
.go_flags = GLOF_NONDISK,
};
const struct gfs2_glock_operations gfs2_iopen_glops = {
.go_type = LM_TYPE_IOPEN,
.go_callback = iopen_go_callback,
.go_dump = inode_go_dump,
.go_flags = GLOF_LRU | GLOF_NONDISK,
.go_subclass = 1,
};
const struct gfs2_glock_operations gfs2_flock_glops = {
.go_type = LM_TYPE_FLOCK,
.go_flags = GLOF_LRU | GLOF_NONDISK,
};
const struct gfs2_glock_operations gfs2_nondisk_glops = {
.go_type = LM_TYPE_NONDISK,
.go_flags = GLOF_NONDISK,
.go_callback = nondisk_go_callback,
};
const struct gfs2_glock_operations gfs2_quota_glops = {
.go_type = LM_TYPE_QUOTA,
.go_flags = GLOF_LVB | GLOF_LRU | GLOF_NONDISK,
};
const struct gfs2_glock_operations gfs2_journal_glops = {
.go_type = LM_TYPE_JOURNAL,
.go_flags = GLOF_NONDISK,
};
const struct gfs2_glock_operations *gfs2_glops_list[] = {
[LM_TYPE_META] = &gfs2_meta_glops,
[LM_TYPE_INODE] = &gfs2_inode_glops,
[LM_TYPE_RGRP] = &gfs2_rgrp_glops,
[LM_TYPE_IOPEN] = &gfs2_iopen_glops,
[LM_TYPE_FLOCK] = &gfs2_flock_glops,
[LM_TYPE_NONDISK] = &gfs2_nondisk_glops,
[LM_TYPE_QUOTA] = &gfs2_quota_glops,
[LM_TYPE_JOURNAL] = &gfs2_journal_glops,
};
| linux-master | fs/gfs2/glops.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/crc32c.h>
#include <linux/ktime.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "glops.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "recovery.h"
#include "super.h"
#include "util.h"
#include "dir.h"
struct workqueue_struct *gfs2_recovery_wq;
int gfs2_replay_read_block(struct gfs2_jdesc *jd, unsigned int blk,
struct buffer_head **bh)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_glock *gl = ip->i_gl;
u64 dblock;
u32 extlen;
int error;
extlen = 32;
error = gfs2_get_extent(&ip->i_inode, blk, &dblock, &extlen);
if (error)
return error;
if (!dblock) {
gfs2_consist_inode(ip);
return -EIO;
}
*bh = gfs2_meta_ra(gl, dblock, extlen);
return error;
}
int gfs2_revoke_add(struct gfs2_jdesc *jd, u64 blkno, unsigned int where)
{
struct list_head *head = &jd->jd_revoke_list;
struct gfs2_revoke_replay *rr = NULL, *iter;
list_for_each_entry(iter, head, rr_list) {
if (iter->rr_blkno == blkno) {
rr = iter;
break;
}
}
if (rr) {
rr->rr_where = where;
return 0;
}
rr = kmalloc(sizeof(struct gfs2_revoke_replay), GFP_NOFS);
if (!rr)
return -ENOMEM;
rr->rr_blkno = blkno;
rr->rr_where = where;
list_add(&rr->rr_list, head);
return 1;
}
int gfs2_revoke_check(struct gfs2_jdesc *jd, u64 blkno, unsigned int where)
{
struct gfs2_revoke_replay *rr = NULL, *iter;
int wrap, a, b, revoke;
list_for_each_entry(iter, &jd->jd_revoke_list, rr_list) {
if (iter->rr_blkno == blkno) {
rr = iter;
break;
}
}
if (!rr)
return 0;
wrap = (rr->rr_where < jd->jd_replay_tail);
a = (jd->jd_replay_tail < where);
b = (where < rr->rr_where);
revoke = (wrap) ? (a || b) : (a && b);
return revoke;
}
void gfs2_revoke_clean(struct gfs2_jdesc *jd)
{
struct list_head *head = &jd->jd_revoke_list;
struct gfs2_revoke_replay *rr;
while (!list_empty(head)) {
rr = list_first_entry(head, struct gfs2_revoke_replay, rr_list);
list_del(&rr->rr_list);
kfree(rr);
}
}
int __get_log_header(struct gfs2_sbd *sdp, const struct gfs2_log_header *lh,
unsigned int blkno, struct gfs2_log_header_host *head)
{
u32 hash, crc;
if (lh->lh_header.mh_magic != cpu_to_be32(GFS2_MAGIC) ||
lh->lh_header.mh_type != cpu_to_be32(GFS2_METATYPE_LH) ||
(blkno && be32_to_cpu(lh->lh_blkno) != blkno))
return 1;
hash = crc32(~0, lh, LH_V1_SIZE - 4);
hash = ~crc32_le_shift(hash, 4); /* assume lh_hash is zero */
if (be32_to_cpu(lh->lh_hash) != hash)
return 1;
crc = crc32c(~0, (void *)lh + LH_V1_SIZE + 4,
sdp->sd_sb.sb_bsize - LH_V1_SIZE - 4);
if ((lh->lh_crc != 0 && be32_to_cpu(lh->lh_crc) != crc))
return 1;
head->lh_sequence = be64_to_cpu(lh->lh_sequence);
head->lh_flags = be32_to_cpu(lh->lh_flags);
head->lh_tail = be32_to_cpu(lh->lh_tail);
head->lh_blkno = be32_to_cpu(lh->lh_blkno);
head->lh_local_total = be64_to_cpu(lh->lh_local_total);
head->lh_local_free = be64_to_cpu(lh->lh_local_free);
head->lh_local_dinodes = be64_to_cpu(lh->lh_local_dinodes);
return 0;
}
/**
* get_log_header - read the log header for a given segment
* @jd: the journal
* @blk: the block to look at
* @head: the log header to return
*
* Read the log header for a given segement in a given journal. Do a few
* sanity checks on it.
*
* Returns: 0 on success,
* 1 if the header was invalid or incomplete,
* errno on error
*/
static int get_log_header(struct gfs2_jdesc *jd, unsigned int blk,
struct gfs2_log_header_host *head)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct buffer_head *bh;
int error;
error = gfs2_replay_read_block(jd, blk, &bh);
if (error)
return error;
error = __get_log_header(sdp, (const struct gfs2_log_header *)bh->b_data,
blk, head);
brelse(bh);
return error;
}
/**
* foreach_descriptor - go through the active part of the log
* @jd: the journal
* @start: the first log header in the active region
* @end: the last log header (don't process the contents of this entry))
* @pass: iteration number (foreach_descriptor() is called in a for() loop)
*
* Call a given function once for every log descriptor in the active
* portion of the log.
*
* Returns: errno
*/
static int foreach_descriptor(struct gfs2_jdesc *jd, u32 start,
unsigned int end, int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct buffer_head *bh;
struct gfs2_log_descriptor *ld;
int error = 0;
u32 length;
__be64 *ptr;
unsigned int offset = sizeof(struct gfs2_log_descriptor);
offset += sizeof(__be64) - 1;
offset &= ~(sizeof(__be64) - 1);
while (start != end) {
error = gfs2_replay_read_block(jd, start, &bh);
if (error)
return error;
if (gfs2_meta_check(sdp, bh)) {
brelse(bh);
return -EIO;
}
ld = (struct gfs2_log_descriptor *)bh->b_data;
length = be32_to_cpu(ld->ld_length);
if (be32_to_cpu(ld->ld_header.mh_type) == GFS2_METATYPE_LH) {
struct gfs2_log_header_host lh;
error = get_log_header(jd, start, &lh);
if (!error) {
gfs2_replay_incr_blk(jd, &start);
brelse(bh);
continue;
}
if (error == 1) {
gfs2_consist_inode(GFS2_I(jd->jd_inode));
error = -EIO;
}
brelse(bh);
return error;
} else if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_LD)) {
brelse(bh);
return -EIO;
}
ptr = (__be64 *)(bh->b_data + offset);
error = lops_scan_elements(jd, start, ld, ptr, pass);
if (error) {
brelse(bh);
return error;
}
while (length--)
gfs2_replay_incr_blk(jd, &start);
brelse(bh);
}
return 0;
}
/**
* clean_journal - mark a dirty journal as being clean
* @jd: the journal
* @head: the head journal to start from
*
* Returns: errno
*/
static void clean_journal(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
u32 lblock = head->lh_blkno;
gfs2_replay_incr_blk(jd, &lblock);
gfs2_write_log_header(sdp, jd, head->lh_sequence + 1, 0, lblock,
GFS2_LOG_HEAD_UNMOUNT | GFS2_LOG_HEAD_RECOVERY,
REQ_PREFLUSH | REQ_FUA | REQ_META | REQ_SYNC);
if (jd->jd_jid == sdp->sd_lockstruct.ls_jid) {
sdp->sd_log_flush_head = lblock;
gfs2_log_incr_head(sdp);
}
}
static void gfs2_recovery_done(struct gfs2_sbd *sdp, unsigned int jid,
unsigned int message)
{
char env_jid[20];
char env_status[20];
char *envp[] = { env_jid, env_status, NULL };
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
ls->ls_recover_jid_done = jid;
ls->ls_recover_jid_status = message;
sprintf(env_jid, "JID=%u", jid);
sprintf(env_status, "RECOVERY=%s",
message == LM_RD_SUCCESS ? "Done" : "Failed");
kobject_uevent_env(&sdp->sd_kobj, KOBJ_CHANGE, envp);
if (sdp->sd_lockstruct.ls_ops->lm_recovery_result)
sdp->sd_lockstruct.ls_ops->lm_recovery_result(sdp, jid, message);
}
/**
* update_statfs_inode - Update the master statfs inode or zero out the local
* statfs inode for a given journal.
* @jd: The journal
* @head: If NULL, @inode is the local statfs inode and we need to zero it out.
* Otherwise, it @head contains the statfs change info that needs to be
* synced to the master statfs inode (pointed to by @inode).
* @inode: statfs inode to update.
*/
static int update_statfs_inode(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head,
struct inode *inode)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_inode *ip;
struct buffer_head *bh;
struct gfs2_statfs_change_host sc;
int error = 0;
BUG_ON(!inode);
ip = GFS2_I(inode);
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
goto out;
spin_lock(&sdp->sd_statfs_spin);
if (head) { /* Update the master statfs inode */
gfs2_statfs_change_in(&sc, bh->b_data + sizeof(struct gfs2_dinode));
sc.sc_total += head->lh_local_total;
sc.sc_free += head->lh_local_free;
sc.sc_dinodes += head->lh_local_dinodes;
gfs2_statfs_change_out(&sc, bh->b_data + sizeof(struct gfs2_dinode));
fs_info(sdp, "jid=%u: Updated master statfs Total:%lld, "
"Free:%lld, Dinodes:%lld after change "
"[%+lld,%+lld,%+lld]\n", jd->jd_jid, sc.sc_total,
sc.sc_free, sc.sc_dinodes, head->lh_local_total,
head->lh_local_free, head->lh_local_dinodes);
} else { /* Zero out the local statfs inode */
memset(bh->b_data + sizeof(struct gfs2_dinode), 0,
sizeof(struct gfs2_statfs_change));
/* If it's our own journal, reset any in-memory changes too */
if (jd->jd_jid == sdp->sd_lockstruct.ls_jid) {
memset(&sdp->sd_statfs_local, 0,
sizeof(struct gfs2_statfs_change_host));
}
}
spin_unlock(&sdp->sd_statfs_spin);
mark_buffer_dirty(bh);
brelse(bh);
gfs2_inode_metasync(ip->i_gl);
out:
return error;
}
/**
* recover_local_statfs - Update the master and local statfs changes for this
* journal.
*
* Previously, statfs updates would be read in from the local statfs inode and
* synced to the master statfs inode during recovery.
*
* We now use the statfs updates in the journal head to update the master statfs
* inode instead of reading in from the local statfs inode. To preserve backward
* compatibility with kernels that can't do this, we still need to keep the
* local statfs inode up to date by writing changes to it. At some point in the
* future, we can do away with the local statfs inodes altogether and keep the
* statfs changes solely in the journal.
*
* @jd: the journal
* @head: the journal head
*
* Returns: errno
*/
static void recover_local_statfs(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head)
{
int error;
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (!head->lh_local_total && !head->lh_local_free
&& !head->lh_local_dinodes) /* No change */
goto zero_local;
/* First update the master statfs inode with the changes we
* found in the journal. */
error = update_statfs_inode(jd, head, sdp->sd_statfs_inode);
if (error)
goto out;
zero_local:
/* Zero out the local statfs inode so any changes in there
* are not re-recovered. */
error = update_statfs_inode(jd, NULL,
find_local_statfs_inode(sdp, jd->jd_jid));
out:
return;
}
void gfs2_recover_func(struct work_struct *work)
{
struct gfs2_jdesc *jd = container_of(work, struct gfs2_jdesc, jd_work);
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_log_header_host head;
struct gfs2_holder j_gh, ji_gh;
ktime_t t_start, t_jlck, t_jhd, t_tlck, t_rep;
int ro = 0;
unsigned int pass;
int error = 0;
int jlocked = 0;
if (gfs2_withdrawn(sdp)) {
fs_err(sdp, "jid=%u: Recovery not attempted due to withdraw.\n",
jd->jd_jid);
goto fail;
}
t_start = ktime_get();
if (sdp->sd_args.ar_spectator)
goto fail;
if (jd->jd_jid != sdp->sd_lockstruct.ls_jid) {
fs_info(sdp, "jid=%u: Trying to acquire journal glock...\n",
jd->jd_jid);
jlocked = 1;
/* Acquire the journal glock so we can do recovery */
error = gfs2_glock_nq_num(sdp, jd->jd_jid, &gfs2_journal_glops,
LM_ST_EXCLUSIVE,
LM_FLAG_NOEXP | LM_FLAG_TRY | GL_NOCACHE,
&j_gh);
switch (error) {
case 0:
break;
case GLR_TRYFAILED:
fs_info(sdp, "jid=%u: Busy\n", jd->jd_jid);
error = 0;
goto fail;
default:
goto fail;
}
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED,
LM_FLAG_NOEXP | GL_NOCACHE, &ji_gh);
if (error)
goto fail_gunlock_j;
} else {
fs_info(sdp, "jid=%u, already locked for use\n", jd->jd_jid);
}
t_jlck = ktime_get();
fs_info(sdp, "jid=%u: Looking at journal...\n", jd->jd_jid);
error = gfs2_jdesc_check(jd);
if (error)
goto fail_gunlock_ji;
error = gfs2_find_jhead(jd, &head, true);
if (error)
goto fail_gunlock_ji;
t_jhd = ktime_get();
fs_info(sdp, "jid=%u: Journal head lookup took %lldms\n", jd->jd_jid,
ktime_ms_delta(t_jhd, t_jlck));
if (!(head.lh_flags & GFS2_LOG_HEAD_UNMOUNT)) {
mutex_lock(&sdp->sd_freeze_mutex);
if (test_bit(SDF_FROZEN, &sdp->sd_flags)) {
mutex_unlock(&sdp->sd_freeze_mutex);
fs_warn(sdp, "jid=%u: Can't replay: filesystem "
"is frozen\n", jd->jd_jid);
goto fail_gunlock_ji;
}
if (test_bit(SDF_RORECOVERY, &sdp->sd_flags)) {
ro = 1;
} else if (test_bit(SDF_JOURNAL_CHECKED, &sdp->sd_flags)) {
if (!test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))
ro = 1;
} else {
if (sb_rdonly(sdp->sd_vfs)) {
/* check if device itself is read-only */
ro = bdev_read_only(sdp->sd_vfs->s_bdev);
if (!ro) {
fs_info(sdp, "recovery required on "
"read-only filesystem.\n");
fs_info(sdp, "write access will be "
"enabled during recovery.\n");
}
}
}
if (ro) {
fs_warn(sdp, "jid=%u: Can't replay: read-only block "
"device\n", jd->jd_jid);
error = -EROFS;
goto fail_gunlock_nofreeze;
}
t_tlck = ktime_get();
fs_info(sdp, "jid=%u: Replaying journal...0x%x to 0x%x\n",
jd->jd_jid, head.lh_tail, head.lh_blkno);
/* We take the sd_log_flush_lock here primarily to prevent log
* flushes and simultaneous journal replays from stomping on
* each other wrt jd_log_bio. */
down_read(&sdp->sd_log_flush_lock);
for (pass = 0; pass < 2; pass++) {
lops_before_scan(jd, &head, pass);
error = foreach_descriptor(jd, head.lh_tail,
head.lh_blkno, pass);
lops_after_scan(jd, error, pass);
if (error) {
up_read(&sdp->sd_log_flush_lock);
goto fail_gunlock_nofreeze;
}
}
recover_local_statfs(jd, &head);
clean_journal(jd, &head);
up_read(&sdp->sd_log_flush_lock);
mutex_unlock(&sdp->sd_freeze_mutex);
t_rep = ktime_get();
fs_info(sdp, "jid=%u: Journal replayed in %lldms [jlck:%lldms, "
"jhead:%lldms, tlck:%lldms, replay:%lldms]\n",
jd->jd_jid, ktime_ms_delta(t_rep, t_start),
ktime_ms_delta(t_jlck, t_start),
ktime_ms_delta(t_jhd, t_jlck),
ktime_ms_delta(t_tlck, t_jhd),
ktime_ms_delta(t_rep, t_tlck));
}
gfs2_recovery_done(sdp, jd->jd_jid, LM_RD_SUCCESS);
if (jlocked) {
gfs2_glock_dq_uninit(&ji_gh);
gfs2_glock_dq_uninit(&j_gh);
}
fs_info(sdp, "jid=%u: Done\n", jd->jd_jid);
goto done;
fail_gunlock_nofreeze:
mutex_unlock(&sdp->sd_freeze_mutex);
fail_gunlock_ji:
if (jlocked) {
gfs2_glock_dq_uninit(&ji_gh);
fail_gunlock_j:
gfs2_glock_dq_uninit(&j_gh);
}
fs_info(sdp, "jid=%u: %s\n", jd->jd_jid, (error) ? "Failed" : "Done");
fail:
jd->jd_recover_error = error;
gfs2_recovery_done(sdp, jd->jd_jid, LM_RD_GAVEUP);
done:
clear_bit(JDF_RECOVERY, &jd->jd_flags);
smp_mb__after_atomic();
wake_up_bit(&jd->jd_flags, JDF_RECOVERY);
}
int gfs2_recover_journal(struct gfs2_jdesc *jd, bool wait)
{
int rv;
if (test_and_set_bit(JDF_RECOVERY, &jd->jd_flags))
return -EBUSY;
/* we have JDF_RECOVERY, queue should always succeed */
rv = queue_work(gfs2_recovery_wq, &jd->jd_work);
BUG_ON(!rv);
if (wait)
wait_on_bit(&jd->jd_flags, JDF_RECOVERY,
TASK_UNINTERRUPTIBLE);
return wait ? jd->jd_recover_error : 0;
}
| linux-master | fs/gfs2/recovery.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/delay.h>
#include <linux/bio.h>
#include <linux/gfs2_ondisk.h>
#include "gfs2.h"
#include "incore.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
#include "trace_gfs2.h"
static int gfs2_aspace_writepage(struct page *page, struct writeback_control *wbc)
{
struct buffer_head *bh, *head;
int nr_underway = 0;
blk_opf_t write_flags = REQ_META | REQ_PRIO | wbc_to_write_flags(wbc);
BUG_ON(!PageLocked(page));
BUG_ON(!page_has_buffers(page));
head = page_buffers(page);
bh = head;
do {
if (!buffer_mapped(bh))
continue;
/*
* If it's a fully non-blocking write attempt and we cannot
* lock the buffer then redirty the page. Note that this can
* potentially cause a busy-wait loop from flusher thread and kswapd
* activity, but those code paths have their own higher-level
* throttling.
*/
if (wbc->sync_mode != WB_SYNC_NONE) {
lock_buffer(bh);
} else if (!trylock_buffer(bh)) {
redirty_page_for_writepage(wbc, page);
continue;
}
if (test_clear_buffer_dirty(bh)) {
mark_buffer_async_write(bh);
} else {
unlock_buffer(bh);
}
} while ((bh = bh->b_this_page) != head);
/*
* The page and its buffers are protected by PageWriteback(), so we can
* drop the bh refcounts early.
*/
BUG_ON(PageWriteback(page));
set_page_writeback(page);
do {
struct buffer_head *next = bh->b_this_page;
if (buffer_async_write(bh)) {
submit_bh(REQ_OP_WRITE | write_flags, bh);
nr_underway++;
}
bh = next;
} while (bh != head);
unlock_page(page);
if (nr_underway == 0)
end_page_writeback(page);
return 0;
}
const struct address_space_operations gfs2_meta_aops = {
.dirty_folio = block_dirty_folio,
.invalidate_folio = block_invalidate_folio,
.writepage = gfs2_aspace_writepage,
.release_folio = gfs2_release_folio,
};
const struct address_space_operations gfs2_rgrp_aops = {
.dirty_folio = block_dirty_folio,
.invalidate_folio = block_invalidate_folio,
.writepage = gfs2_aspace_writepage,
.release_folio = gfs2_release_folio,
};
/**
* gfs2_getbuf - Get a buffer with a given address space
* @gl: the glock
* @blkno: the block number (filesystem scope)
* @create: 1 if the buffer should be created
*
* Returns: the buffer
*/
struct buffer_head *gfs2_getbuf(struct gfs2_glock *gl, u64 blkno, int create)
{
struct address_space *mapping = gfs2_glock2aspace(gl);
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct page *page;
struct buffer_head *bh;
unsigned int shift;
unsigned long index;
unsigned int bufnum;
if (mapping == NULL)
mapping = &sdp->sd_aspace;
shift = PAGE_SHIFT - sdp->sd_sb.sb_bsize_shift;
index = blkno >> shift; /* convert block to page */
bufnum = blkno - (index << shift); /* block buf index within page */
if (create) {
for (;;) {
page = grab_cache_page(mapping, index);
if (page)
break;
yield();
}
if (!page_has_buffers(page))
create_empty_buffers(page, sdp->sd_sb.sb_bsize, 0);
} else {
page = find_get_page_flags(mapping, index,
FGP_LOCK|FGP_ACCESSED);
if (!page)
return NULL;
if (!page_has_buffers(page)) {
bh = NULL;
goto out_unlock;
}
}
/* Locate header for our buffer within our page */
for (bh = page_buffers(page); bufnum--; bh = bh->b_this_page)
/* Do nothing */;
get_bh(bh);
if (!buffer_mapped(bh))
map_bh(bh, sdp->sd_vfs, blkno);
out_unlock:
unlock_page(page);
put_page(page);
return bh;
}
static void meta_prep_new(struct buffer_head *bh)
{
struct gfs2_meta_header *mh = (struct gfs2_meta_header *)bh->b_data;
lock_buffer(bh);
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
mh->mh_magic = cpu_to_be32(GFS2_MAGIC);
}
/**
* gfs2_meta_new - Get a block
* @gl: The glock associated with this block
* @blkno: The block number
*
* Returns: The buffer
*/
struct buffer_head *gfs2_meta_new(struct gfs2_glock *gl, u64 blkno)
{
struct buffer_head *bh;
bh = gfs2_getbuf(gl, blkno, CREATE);
meta_prep_new(bh);
return bh;
}
static void gfs2_meta_read_endio(struct bio *bio)
{
struct bio_vec *bvec;
struct bvec_iter_all iter_all;
bio_for_each_segment_all(bvec, bio, iter_all) {
struct page *page = bvec->bv_page;
struct buffer_head *bh = page_buffers(page);
unsigned int len = bvec->bv_len;
while (bh_offset(bh) < bvec->bv_offset)
bh = bh->b_this_page;
do {
struct buffer_head *next = bh->b_this_page;
len -= bh->b_size;
bh->b_end_io(bh, !bio->bi_status);
bh = next;
} while (bh && len);
}
bio_put(bio);
}
/*
* Submit several consecutive buffer head I/O requests as a single bio I/O
* request. (See submit_bh_wbc.)
*/
static void gfs2_submit_bhs(blk_opf_t opf, struct buffer_head *bhs[], int num)
{
while (num > 0) {
struct buffer_head *bh = *bhs;
struct bio *bio;
bio = bio_alloc(bh->b_bdev, num, opf, GFP_NOIO);
bio->bi_iter.bi_sector = bh->b_blocknr * (bh->b_size >> 9);
while (num > 0) {
bh = *bhs;
if (!bio_add_page(bio, bh->b_page, bh->b_size, bh_offset(bh))) {
BUG_ON(bio->bi_iter.bi_size == 0);
break;
}
bhs++;
num--;
}
bio->bi_end_io = gfs2_meta_read_endio;
submit_bio(bio);
}
}
/**
* gfs2_meta_read - Read a block from disk
* @gl: The glock covering the block
* @blkno: The block number
* @flags: flags
* @rahead: Do read-ahead
* @bhp: the place where the buffer is returned (NULL on failure)
*
* Returns: errno
*/
int gfs2_meta_read(struct gfs2_glock *gl, u64 blkno, int flags,
int rahead, struct buffer_head **bhp)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct buffer_head *bh, *bhs[2];
int num = 0;
if (unlikely(gfs2_withdrawn(sdp)) && !gfs2_withdraw_in_prog(sdp)) {
*bhp = NULL;
return -EIO;
}
*bhp = bh = gfs2_getbuf(gl, blkno, CREATE);
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
flags &= ~DIO_WAIT;
} else {
bh->b_end_io = end_buffer_read_sync;
get_bh(bh);
bhs[num++] = bh;
}
if (rahead) {
bh = gfs2_getbuf(gl, blkno + 1, CREATE);
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
brelse(bh);
} else {
bh->b_end_io = end_buffer_read_sync;
bhs[num++] = bh;
}
}
gfs2_submit_bhs(REQ_OP_READ | REQ_META | REQ_PRIO, bhs, num);
if (!(flags & DIO_WAIT))
return 0;
bh = *bhp;
wait_on_buffer(bh);
if (unlikely(!buffer_uptodate(bh))) {
struct gfs2_trans *tr = current->journal_info;
if (tr && test_bit(TR_TOUCHED, &tr->tr_flags))
gfs2_io_error_bh_wd(sdp, bh);
brelse(bh);
*bhp = NULL;
return -EIO;
}
return 0;
}
/**
* gfs2_meta_wait - Reread a block from disk
* @sdp: the filesystem
* @bh: The block to wait for
*
* Returns: errno
*/
int gfs2_meta_wait(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
if (unlikely(gfs2_withdrawn(sdp)) && !gfs2_withdraw_in_prog(sdp))
return -EIO;
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
struct gfs2_trans *tr = current->journal_info;
if (tr && test_bit(TR_TOUCHED, &tr->tr_flags))
gfs2_io_error_bh_wd(sdp, bh);
return -EIO;
}
if (unlikely(gfs2_withdrawn(sdp)) && !gfs2_withdraw_in_prog(sdp))
return -EIO;
return 0;
}
void gfs2_remove_from_journal(struct buffer_head *bh, int meta)
{
struct address_space *mapping = bh->b_folio->mapping;
struct gfs2_sbd *sdp = gfs2_mapping2sbd(mapping);
struct gfs2_bufdata *bd = bh->b_private;
struct gfs2_trans *tr = current->journal_info;
int was_pinned = 0;
if (test_clear_buffer_pinned(bh)) {
trace_gfs2_pin(bd, 0);
atomic_dec(&sdp->sd_log_pinned);
list_del_init(&bd->bd_list);
if (meta == REMOVE_META)
tr->tr_num_buf_rm++;
else
tr->tr_num_databuf_rm++;
set_bit(TR_TOUCHED, &tr->tr_flags);
was_pinned = 1;
brelse(bh);
}
if (bd) {
if (bd->bd_tr) {
gfs2_trans_add_revoke(sdp, bd);
} else if (was_pinned) {
bh->b_private = NULL;
kmem_cache_free(gfs2_bufdata_cachep, bd);
} else if (!list_empty(&bd->bd_ail_st_list) &&
!list_empty(&bd->bd_ail_gl_list)) {
gfs2_remove_from_ail(bd);
}
}
clear_buffer_dirty(bh);
clear_buffer_uptodate(bh);
}
/**
* gfs2_ail1_wipe - remove deleted/freed buffers from the ail1 list
* @sdp: superblock
* @bstart: starting block address of buffers to remove
* @blen: length of buffers to be removed
*
* This function is called from gfs2_journal wipe, whose job is to remove
* buffers, corresponding to deleted blocks, from the journal. If we find any
* bufdata elements on the system ail1 list, they haven't been written to
* the journal yet. So we remove them.
*/
static void gfs2_ail1_wipe(struct gfs2_sbd *sdp, u64 bstart, u32 blen)
{
struct gfs2_trans *tr, *s;
struct gfs2_bufdata *bd, *bs;
struct buffer_head *bh;
u64 end = bstart + blen;
gfs2_log_lock(sdp);
spin_lock(&sdp->sd_ail_lock);
list_for_each_entry_safe(tr, s, &sdp->sd_ail1_list, tr_list) {
list_for_each_entry_safe(bd, bs, &tr->tr_ail1_list,
bd_ail_st_list) {
bh = bd->bd_bh;
if (bh->b_blocknr < bstart || bh->b_blocknr >= end)
continue;
gfs2_remove_from_journal(bh, REMOVE_JDATA);
}
}
spin_unlock(&sdp->sd_ail_lock);
gfs2_log_unlock(sdp);
}
static struct buffer_head *gfs2_getjdatabuf(struct gfs2_inode *ip, u64 blkno)
{
struct address_space *mapping = ip->i_inode.i_mapping;
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct page *page;
struct buffer_head *bh;
unsigned int shift = PAGE_SHIFT - sdp->sd_sb.sb_bsize_shift;
unsigned long index = blkno >> shift; /* convert block to page */
unsigned int bufnum = blkno - (index << shift);
page = find_get_page_flags(mapping, index, FGP_LOCK|FGP_ACCESSED);
if (!page)
return NULL;
if (!page_has_buffers(page)) {
unlock_page(page);
put_page(page);
return NULL;
}
/* Locate header for our buffer within our page */
for (bh = page_buffers(page); bufnum--; bh = bh->b_this_page)
/* Do nothing */;
get_bh(bh);
unlock_page(page);
put_page(page);
return bh;
}
/**
* gfs2_journal_wipe - make inode's buffers so they aren't dirty/pinned anymore
* @ip: the inode who owns the buffers
* @bstart: the first buffer in the run
* @blen: the number of buffers in the run
*
*/
void gfs2_journal_wipe(struct gfs2_inode *ip, u64 bstart, u32 blen)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *bh;
int ty;
if (!ip->i_gl) {
/* This can only happen during incomplete inode creation. */
BUG_ON(!test_bit(GIF_ALLOC_FAILED, &ip->i_flags));
return;
}
gfs2_ail1_wipe(sdp, bstart, blen);
while (blen) {
ty = REMOVE_META;
bh = gfs2_getbuf(ip->i_gl, bstart, NO_CREATE);
if (!bh && gfs2_is_jdata(ip)) {
bh = gfs2_getjdatabuf(ip, bstart);
ty = REMOVE_JDATA;
}
if (bh) {
lock_buffer(bh);
gfs2_log_lock(sdp);
spin_lock(&sdp->sd_ail_lock);
gfs2_remove_from_journal(bh, ty);
spin_unlock(&sdp->sd_ail_lock);
gfs2_log_unlock(sdp);
unlock_buffer(bh);
brelse(bh);
}
bstart++;
blen--;
}
}
/**
* gfs2_meta_buffer - Get a metadata buffer
* @ip: The GFS2 inode
* @mtype: The block type (GFS2_METATYPE_*)
* @num: The block number (device relative) of the buffer
* @bhp: the buffer is returned here
*
* Returns: errno
*/
int gfs2_meta_buffer(struct gfs2_inode *ip, u32 mtype, u64 num,
struct buffer_head **bhp)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_glock *gl = ip->i_gl;
struct buffer_head *bh;
int ret = 0;
int rahead = 0;
if (num == ip->i_no_addr)
rahead = ip->i_rahead;
ret = gfs2_meta_read(gl, num, DIO_WAIT, rahead, &bh);
if (ret == 0 && gfs2_metatype_check(sdp, bh, mtype)) {
brelse(bh);
ret = -EIO;
} else {
*bhp = bh;
}
return ret;
}
/**
* gfs2_meta_ra - start readahead on an extent of a file
* @gl: the glock the blocks belong to
* @dblock: the starting disk block
* @extlen: the number of blocks in the extent
*
* returns: the first buffer in the extent
*/
struct buffer_head *gfs2_meta_ra(struct gfs2_glock *gl, u64 dblock, u32 extlen)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct buffer_head *first_bh, *bh;
u32 max_ra = gfs2_tune_get(sdp, gt_max_readahead) >>
sdp->sd_sb.sb_bsize_shift;
BUG_ON(!extlen);
if (max_ra < 1)
max_ra = 1;
if (extlen > max_ra)
extlen = max_ra;
first_bh = gfs2_getbuf(gl, dblock, CREATE);
if (buffer_uptodate(first_bh))
goto out;
bh_read_nowait(first_bh, REQ_META | REQ_PRIO);
dblock++;
extlen--;
while (extlen) {
bh = gfs2_getbuf(gl, dblock, CREATE);
bh_readahead(bh, REQ_RAHEAD | REQ_META | REQ_PRIO);
brelse(bh);
dblock++;
extlen--;
if (!buffer_locked(first_bh) && buffer_uptodate(first_bh))
goto out;
}
wait_on_buffer(first_bh);
out:
return first_bh;
}
| linux-master | fs/gfs2/meta_io.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/xattr.h>
#include <linux/gfs2_ondisk.h>
#include <linux/posix_acl_xattr.h>
#include <linux/uaccess.h>
#include "gfs2.h"
#include "incore.h"
#include "acl.h"
#include "xattr.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "util.h"
/*
* ea_calc_size - returns the actual number of bytes the request will take up
* (not counting any unstuffed data blocks)
*
* Returns: 1 if the EA should be stuffed
*/
static int ea_calc_size(struct gfs2_sbd *sdp, unsigned int nsize, size_t dsize,
unsigned int *size)
{
unsigned int jbsize = sdp->sd_jbsize;
/* Stuffed */
*size = ALIGN(sizeof(struct gfs2_ea_header) + nsize + dsize, 8);
if (*size <= jbsize)
return 1;
/* Unstuffed */
*size = ALIGN(sizeof(struct gfs2_ea_header) + nsize +
(sizeof(__be64) * DIV_ROUND_UP(dsize, jbsize)), 8);
return 0;
}
static int ea_check_size(struct gfs2_sbd *sdp, unsigned int nsize, size_t dsize)
{
unsigned int size;
if (dsize > GFS2_EA_MAX_DATA_LEN)
return -ERANGE;
ea_calc_size(sdp, nsize, dsize, &size);
/* This can only happen with 512 byte blocks */
if (size > sdp->sd_jbsize)
return -ERANGE;
return 0;
}
static bool gfs2_eatype_valid(struct gfs2_sbd *sdp, u8 type)
{
switch(sdp->sd_sb.sb_fs_format) {
case GFS2_FS_FORMAT_MAX:
return true;
case GFS2_FS_FORMAT_MIN:
return type <= GFS2_EATYPE_SECURITY;
default:
return false;
}
}
typedef int (*ea_call_t) (struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea,
struct gfs2_ea_header *prev, void *private);
static int ea_foreach_i(struct gfs2_inode *ip, struct buffer_head *bh,
ea_call_t ea_call, void *data)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_ea_header *ea, *prev = NULL;
int error = 0;
if (gfs2_metatype_check(GFS2_SB(&ip->i_inode), bh, GFS2_METATYPE_EA))
return -EIO;
for (ea = GFS2_EA_BH2FIRST(bh);; prev = ea, ea = GFS2_EA2NEXT(ea)) {
if (!GFS2_EA_REC_LEN(ea))
goto fail;
if (!(bh->b_data <= (char *)ea && (char *)GFS2_EA2NEXT(ea) <=
bh->b_data + bh->b_size))
goto fail;
if (!gfs2_eatype_valid(sdp, ea->ea_type))
goto fail;
error = ea_call(ip, bh, ea, prev, data);
if (error)
return error;
if (GFS2_EA_IS_LAST(ea)) {
if ((char *)GFS2_EA2NEXT(ea) !=
bh->b_data + bh->b_size)
goto fail;
break;
}
}
return error;
fail:
gfs2_consist_inode(ip);
return -EIO;
}
static int ea_foreach(struct gfs2_inode *ip, ea_call_t ea_call, void *data)
{
struct buffer_head *bh, *eabh;
__be64 *eablk, *end;
int error;
error = gfs2_meta_read(ip->i_gl, ip->i_eattr, DIO_WAIT, 0, &bh);
if (error)
return error;
if (!(ip->i_diskflags & GFS2_DIF_EA_INDIRECT)) {
error = ea_foreach_i(ip, bh, ea_call, data);
goto out;
}
if (gfs2_metatype_check(GFS2_SB(&ip->i_inode), bh, GFS2_METATYPE_IN)) {
error = -EIO;
goto out;
}
eablk = (__be64 *)(bh->b_data + sizeof(struct gfs2_meta_header));
end = eablk + GFS2_SB(&ip->i_inode)->sd_inptrs;
for (; eablk < end; eablk++) {
u64 bn;
if (!*eablk)
break;
bn = be64_to_cpu(*eablk);
error = gfs2_meta_read(ip->i_gl, bn, DIO_WAIT, 0, &eabh);
if (error)
break;
error = ea_foreach_i(ip, eabh, ea_call, data);
brelse(eabh);
if (error)
break;
}
out:
brelse(bh);
return error;
}
struct ea_find {
int type;
const char *name;
size_t namel;
struct gfs2_ea_location *ef_el;
};
static int ea_find_i(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea, struct gfs2_ea_header *prev,
void *private)
{
struct ea_find *ef = private;
if (ea->ea_type == GFS2_EATYPE_UNUSED)
return 0;
if (ea->ea_type == ef->type) {
if (ea->ea_name_len == ef->namel &&
!memcmp(GFS2_EA2NAME(ea), ef->name, ea->ea_name_len)) {
struct gfs2_ea_location *el = ef->ef_el;
get_bh(bh);
el->el_bh = bh;
el->el_ea = ea;
el->el_prev = prev;
return 1;
}
}
return 0;
}
static int gfs2_ea_find(struct gfs2_inode *ip, int type, const char *name,
struct gfs2_ea_location *el)
{
struct ea_find ef;
int error;
ef.type = type;
ef.name = name;
ef.namel = strlen(name);
ef.ef_el = el;
memset(el, 0, sizeof(struct gfs2_ea_location));
error = ea_foreach(ip, ea_find_i, &ef);
if (error > 0)
return 0;
return error;
}
/*
* ea_dealloc_unstuffed
*
* Take advantage of the fact that all unstuffed blocks are
* allocated from the same RG. But watch, this may not always
* be true.
*
* Returns: errno
*/
static int ea_dealloc_unstuffed(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea,
struct gfs2_ea_header *prev, void *private)
{
int *leave = private;
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *rgd;
struct gfs2_holder rg_gh;
__be64 *dataptrs;
u64 bn = 0;
u64 bstart = 0;
unsigned int blen = 0;
unsigned int blks = 0;
unsigned int x;
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
if (GFS2_EA_IS_STUFFED(ea))
return 0;
dataptrs = GFS2_EA2DATAPTRS(ea);
for (x = 0; x < ea->ea_num_ptrs; x++, dataptrs++) {
if (*dataptrs) {
blks++;
bn = be64_to_cpu(*dataptrs);
}
}
if (!blks)
return 0;
rgd = gfs2_blk2rgrpd(sdp, bn, 1);
if (!rgd) {
gfs2_consist_inode(ip);
return -EIO;
}
error = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, &rg_gh);
if (error)
return error;
error = gfs2_trans_begin(sdp, rgd->rd_length + RES_DINODE +
RES_EATTR + RES_STATFS + RES_QUOTA, blks);
if (error)
goto out_gunlock;
gfs2_trans_add_meta(ip->i_gl, bh);
dataptrs = GFS2_EA2DATAPTRS(ea);
for (x = 0; x < ea->ea_num_ptrs; x++, dataptrs++) {
if (!*dataptrs)
break;
bn = be64_to_cpu(*dataptrs);
if (bstart + blen == bn)
blen++;
else {
if (bstart)
gfs2_free_meta(ip, rgd, bstart, blen);
bstart = bn;
blen = 1;
}
*dataptrs = 0;
gfs2_add_inode_blocks(&ip->i_inode, -1);
}
if (bstart)
gfs2_free_meta(ip, rgd, bstart, blen);
if (prev && !leave) {
u32 len;
len = GFS2_EA_REC_LEN(prev) + GFS2_EA_REC_LEN(ea);
prev->ea_rec_len = cpu_to_be32(len);
if (GFS2_EA_IS_LAST(ea))
prev->ea_flags |= GFS2_EAFLAG_LAST;
} else {
ea->ea_type = GFS2_EATYPE_UNUSED;
ea->ea_num_ptrs = 0;
}
inode_set_ctime_current(&ip->i_inode);
__mark_inode_dirty(&ip->i_inode, I_DIRTY_DATASYNC);
gfs2_trans_end(sdp);
out_gunlock:
gfs2_glock_dq_uninit(&rg_gh);
return error;
}
static int ea_remove_unstuffed(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea,
struct gfs2_ea_header *prev, int leave)
{
int error;
error = gfs2_rindex_update(GFS2_SB(&ip->i_inode));
if (error)
return error;
error = gfs2_quota_hold(ip, NO_UID_QUOTA_CHANGE, NO_GID_QUOTA_CHANGE);
if (error)
goto out_alloc;
error = ea_dealloc_unstuffed(ip, bh, ea, prev, (leave) ? &error : NULL);
gfs2_quota_unhold(ip);
out_alloc:
return error;
}
struct ea_list {
struct gfs2_ea_request *ei_er;
unsigned int ei_size;
};
static int ea_list_i(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea, struct gfs2_ea_header *prev,
void *private)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct ea_list *ei = private;
struct gfs2_ea_request *er = ei->ei_er;
unsigned int ea_size;
char *prefix;
unsigned int l;
if (ea->ea_type == GFS2_EATYPE_UNUSED)
return 0;
BUG_ON(ea->ea_type > GFS2_EATYPE_SECURITY &&
sdp->sd_sb.sb_fs_format == GFS2_FS_FORMAT_MIN);
switch (ea->ea_type) {
case GFS2_EATYPE_USR:
prefix = "user.";
l = 5;
break;
case GFS2_EATYPE_SYS:
prefix = "system.";
l = 7;
break;
case GFS2_EATYPE_SECURITY:
prefix = "security.";
l = 9;
break;
case GFS2_EATYPE_TRUSTED:
prefix = "trusted.";
l = 8;
break;
default:
return 0;
}
ea_size = l + ea->ea_name_len + 1;
if (er->er_data_len) {
if (ei->ei_size + ea_size > er->er_data_len)
return -ERANGE;
memcpy(er->er_data + ei->ei_size, prefix, l);
memcpy(er->er_data + ei->ei_size + l, GFS2_EA2NAME(ea),
ea->ea_name_len);
er->er_data[ei->ei_size + ea_size - 1] = 0;
}
ei->ei_size += ea_size;
return 0;
}
/**
* gfs2_listxattr - List gfs2 extended attributes
* @dentry: The dentry whose inode we are interested in
* @buffer: The buffer to write the results
* @size: The size of the buffer
*
* Returns: actual size of data on success, -errno on error
*/
ssize_t gfs2_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
struct gfs2_inode *ip = GFS2_I(d_inode(dentry));
struct gfs2_ea_request er;
struct gfs2_holder i_gh;
int error;
memset(&er, 0, sizeof(struct gfs2_ea_request));
if (size) {
er.er_data = buffer;
er.er_data_len = size;
}
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh);
if (error)
return error;
if (ip->i_eattr) {
struct ea_list ei = { .ei_er = &er, .ei_size = 0 };
error = ea_foreach(ip, ea_list_i, &ei);
if (!error)
error = ei.ei_size;
}
gfs2_glock_dq_uninit(&i_gh);
return error;
}
/**
* gfs2_iter_unstuffed - copies the unstuffed xattr data to/from the
* request buffer
* @ip: The GFS2 inode
* @ea: The extended attribute header structure
* @din: The data to be copied in
* @dout: The data to be copied out (one of din,dout will be NULL)
*
* Returns: errno
*/
static int gfs2_iter_unstuffed(struct gfs2_inode *ip, struct gfs2_ea_header *ea,
const char *din, char *dout)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head **bh;
unsigned int amount = GFS2_EA_DATA_LEN(ea);
unsigned int nptrs = DIV_ROUND_UP(amount, sdp->sd_jbsize);
__be64 *dataptrs = GFS2_EA2DATAPTRS(ea);
unsigned int x;
int error = 0;
unsigned char *pos;
unsigned cp_size;
bh = kcalloc(nptrs, sizeof(struct buffer_head *), GFP_NOFS);
if (!bh)
return -ENOMEM;
for (x = 0; x < nptrs; x++) {
error = gfs2_meta_read(ip->i_gl, be64_to_cpu(*dataptrs), 0, 0,
bh + x);
if (error) {
while (x--)
brelse(bh[x]);
goto out;
}
dataptrs++;
}
for (x = 0; x < nptrs; x++) {
error = gfs2_meta_wait(sdp, bh[x]);
if (error) {
for (; x < nptrs; x++)
brelse(bh[x]);
goto out;
}
if (gfs2_metatype_check(sdp, bh[x], GFS2_METATYPE_ED)) {
for (; x < nptrs; x++)
brelse(bh[x]);
error = -EIO;
goto out;
}
pos = bh[x]->b_data + sizeof(struct gfs2_meta_header);
cp_size = (sdp->sd_jbsize > amount) ? amount : sdp->sd_jbsize;
if (dout) {
memcpy(dout, pos, cp_size);
dout += sdp->sd_jbsize;
}
if (din) {
gfs2_trans_add_meta(ip->i_gl, bh[x]);
memcpy(pos, din, cp_size);
din += sdp->sd_jbsize;
}
amount -= sdp->sd_jbsize;
brelse(bh[x]);
}
out:
kfree(bh);
return error;
}
static int gfs2_ea_get_copy(struct gfs2_inode *ip, struct gfs2_ea_location *el,
char *data, size_t size)
{
int ret;
size_t len = GFS2_EA_DATA_LEN(el->el_ea);
if (len > size)
return -ERANGE;
if (GFS2_EA_IS_STUFFED(el->el_ea)) {
memcpy(data, GFS2_EA2DATA(el->el_ea), len);
return len;
}
ret = gfs2_iter_unstuffed(ip, el->el_ea, NULL, data);
if (ret < 0)
return ret;
return len;
}
int gfs2_xattr_acl_get(struct gfs2_inode *ip, const char *name, char **ppdata)
{
struct gfs2_ea_location el;
int error;
int len;
char *data;
error = gfs2_ea_find(ip, GFS2_EATYPE_SYS, name, &el);
if (error)
return error;
if (!el.el_ea)
goto out;
if (!GFS2_EA_DATA_LEN(el.el_ea))
goto out;
len = GFS2_EA_DATA_LEN(el.el_ea);
data = kmalloc(len, GFP_NOFS);
error = -ENOMEM;
if (data == NULL)
goto out;
error = gfs2_ea_get_copy(ip, &el, data, len);
if (error < 0)
kfree(data);
else
*ppdata = data;
out:
brelse(el.el_bh);
return error;
}
/**
* __gfs2_xattr_get - Get a GFS2 extended attribute
* @inode: The inode
* @name: The name of the extended attribute
* @buffer: The buffer to write the result into
* @size: The size of the buffer
* @type: The type of extended attribute
*
* Returns: actual size of data on success, -errno on error
*/
static int __gfs2_xattr_get(struct inode *inode, const char *name,
void *buffer, size_t size, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_ea_location el;
int error;
if (!ip->i_eattr)
return -ENODATA;
if (strlen(name) > GFS2_EA_MAX_NAME_LEN)
return -EINVAL;
error = gfs2_ea_find(ip, type, name, &el);
if (error)
return error;
if (!el.el_ea)
return -ENODATA;
if (size)
error = gfs2_ea_get_copy(ip, &el, buffer, size);
else
error = GFS2_EA_DATA_LEN(el.el_ea);
brelse(el.el_bh);
return error;
}
static int gfs2_xattr_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int ret;
/* During lookup, SELinux calls this function with the glock locked. */
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &gh);
if (ret)
return ret;
} else {
gfs2_holder_mark_uninitialized(&gh);
}
ret = __gfs2_xattr_get(inode, name, buffer, size, handler->flags);
if (gfs2_holder_initialized(&gh))
gfs2_glock_dq_uninit(&gh);
return ret;
}
/**
* ea_alloc_blk - allocates a new block for extended attributes.
* @ip: A pointer to the inode that's getting extended attributes
* @bhp: Pointer to pointer to a struct buffer_head
*
* Returns: errno
*/
static int ea_alloc_blk(struct gfs2_inode *ip, struct buffer_head **bhp)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_ea_header *ea;
unsigned int n = 1;
u64 block;
int error;
error = gfs2_alloc_blocks(ip, &block, &n, 0, NULL);
if (error)
return error;
gfs2_trans_remove_revoke(sdp, block, 1);
*bhp = gfs2_meta_new(ip->i_gl, block);
gfs2_trans_add_meta(ip->i_gl, *bhp);
gfs2_metatype_set(*bhp, GFS2_METATYPE_EA, GFS2_FORMAT_EA);
gfs2_buffer_clear_tail(*bhp, sizeof(struct gfs2_meta_header));
ea = GFS2_EA_BH2FIRST(*bhp);
ea->ea_rec_len = cpu_to_be32(sdp->sd_jbsize);
ea->ea_type = GFS2_EATYPE_UNUSED;
ea->ea_flags = GFS2_EAFLAG_LAST;
ea->ea_num_ptrs = 0;
gfs2_add_inode_blocks(&ip->i_inode, 1);
return 0;
}
/**
* ea_write - writes the request info to an ea, creating new blocks if
* necessary
* @ip: inode that is being modified
* @ea: the location of the new ea in a block
* @er: the write request
*
* Note: does not update ea_rec_len or the GFS2_EAFLAG_LAST bin of ea_flags
*
* returns : errno
*/
static int ea_write(struct gfs2_inode *ip, struct gfs2_ea_header *ea,
struct gfs2_ea_request *er)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
int error;
ea->ea_data_len = cpu_to_be32(er->er_data_len);
ea->ea_name_len = er->er_name_len;
ea->ea_type = er->er_type;
ea->__pad = 0;
memcpy(GFS2_EA2NAME(ea), er->er_name, er->er_name_len);
if (GFS2_EAREQ_SIZE_STUFFED(er) <= sdp->sd_jbsize) {
ea->ea_num_ptrs = 0;
memcpy(GFS2_EA2DATA(ea), er->er_data, er->er_data_len);
} else {
__be64 *dataptr = GFS2_EA2DATAPTRS(ea);
const char *data = er->er_data;
unsigned int data_len = er->er_data_len;
unsigned int copy;
unsigned int x;
ea->ea_num_ptrs = DIV_ROUND_UP(er->er_data_len, sdp->sd_jbsize);
for (x = 0; x < ea->ea_num_ptrs; x++) {
struct buffer_head *bh;
u64 block;
int mh_size = sizeof(struct gfs2_meta_header);
unsigned int n = 1;
error = gfs2_alloc_blocks(ip, &block, &n, 0, NULL);
if (error)
return error;
gfs2_trans_remove_revoke(sdp, block, 1);
bh = gfs2_meta_new(ip->i_gl, block);
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_metatype_set(bh, GFS2_METATYPE_ED, GFS2_FORMAT_ED);
gfs2_add_inode_blocks(&ip->i_inode, 1);
copy = data_len > sdp->sd_jbsize ? sdp->sd_jbsize :
data_len;
memcpy(bh->b_data + mh_size, data, copy);
if (copy < sdp->sd_jbsize)
memset(bh->b_data + mh_size + copy, 0,
sdp->sd_jbsize - copy);
*dataptr++ = cpu_to_be64(bh->b_blocknr);
data += copy;
data_len -= copy;
brelse(bh);
}
gfs2_assert_withdraw(sdp, !data_len);
}
return 0;
}
typedef int (*ea_skeleton_call_t) (struct gfs2_inode *ip,
struct gfs2_ea_request *er, void *private);
static int ea_alloc_skeleton(struct gfs2_inode *ip, struct gfs2_ea_request *er,
unsigned int blks,
ea_skeleton_call_t skeleton_call, void *private)
{
struct gfs2_alloc_parms ap = { .target = blks };
int error;
error = gfs2_rindex_update(GFS2_SB(&ip->i_inode));
if (error)
return error;
error = gfs2_quota_lock_check(ip, &ap);
if (error)
return error;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto out_gunlock_q;
error = gfs2_trans_begin(GFS2_SB(&ip->i_inode),
blks + gfs2_rg_blocks(ip, blks) +
RES_DINODE + RES_STATFS + RES_QUOTA, 0);
if (error)
goto out_ipres;
error = skeleton_call(ip, er, private);
if (error)
goto out_end_trans;
inode_set_ctime_current(&ip->i_inode);
__mark_inode_dirty(&ip->i_inode, I_DIRTY_DATASYNC);
out_end_trans:
gfs2_trans_end(GFS2_SB(&ip->i_inode));
out_ipres:
gfs2_inplace_release(ip);
out_gunlock_q:
gfs2_quota_unlock(ip);
return error;
}
static int ea_init_i(struct gfs2_inode *ip, struct gfs2_ea_request *er,
void *private)
{
struct buffer_head *bh;
int error;
error = ea_alloc_blk(ip, &bh);
if (error)
return error;
ip->i_eattr = bh->b_blocknr;
error = ea_write(ip, GFS2_EA_BH2FIRST(bh), er);
brelse(bh);
return error;
}
/*
* ea_init - initializes a new eattr block
*
* Returns: errno
*/
static int ea_init(struct gfs2_inode *ip, int type, const char *name,
const void *data, size_t size)
{
struct gfs2_ea_request er;
unsigned int jbsize = GFS2_SB(&ip->i_inode)->sd_jbsize;
unsigned int blks = 1;
er.er_type = type;
er.er_name = name;
er.er_name_len = strlen(name);
er.er_data = (void *)data;
er.er_data_len = size;
if (GFS2_EAREQ_SIZE_STUFFED(&er) > jbsize)
blks += DIV_ROUND_UP(er.er_data_len, jbsize);
return ea_alloc_skeleton(ip, &er, blks, ea_init_i, NULL);
}
static struct gfs2_ea_header *ea_split_ea(struct gfs2_ea_header *ea)
{
u32 ea_size = GFS2_EA_SIZE(ea);
struct gfs2_ea_header *new = (struct gfs2_ea_header *)((char *)ea +
ea_size);
u32 new_size = GFS2_EA_REC_LEN(ea) - ea_size;
int last = ea->ea_flags & GFS2_EAFLAG_LAST;
ea->ea_rec_len = cpu_to_be32(ea_size);
ea->ea_flags ^= last;
new->ea_rec_len = cpu_to_be32(new_size);
new->ea_flags = last;
return new;
}
static void ea_set_remove_stuffed(struct gfs2_inode *ip,
struct gfs2_ea_location *el)
{
struct gfs2_ea_header *ea = el->el_ea;
struct gfs2_ea_header *prev = el->el_prev;
u32 len;
gfs2_trans_add_meta(ip->i_gl, el->el_bh);
if (!prev || !GFS2_EA_IS_STUFFED(ea)) {
ea->ea_type = GFS2_EATYPE_UNUSED;
return;
} else if (GFS2_EA2NEXT(prev) != ea) {
prev = GFS2_EA2NEXT(prev);
gfs2_assert_withdraw(GFS2_SB(&ip->i_inode), GFS2_EA2NEXT(prev) == ea);
}
len = GFS2_EA_REC_LEN(prev) + GFS2_EA_REC_LEN(ea);
prev->ea_rec_len = cpu_to_be32(len);
if (GFS2_EA_IS_LAST(ea))
prev->ea_flags |= GFS2_EAFLAG_LAST;
}
struct ea_set {
int ea_split;
struct gfs2_ea_request *es_er;
struct gfs2_ea_location *es_el;
struct buffer_head *es_bh;
struct gfs2_ea_header *es_ea;
};
static int ea_set_simple_noalloc(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea, struct ea_set *es)
{
struct gfs2_ea_request *er = es->es_er;
int error;
error = gfs2_trans_begin(GFS2_SB(&ip->i_inode), RES_DINODE + 2 * RES_EATTR, 0);
if (error)
return error;
gfs2_trans_add_meta(ip->i_gl, bh);
if (es->ea_split)
ea = ea_split_ea(ea);
ea_write(ip, ea, er);
if (es->es_el)
ea_set_remove_stuffed(ip, es->es_el);
inode_set_ctime_current(&ip->i_inode);
__mark_inode_dirty(&ip->i_inode, I_DIRTY_DATASYNC);
gfs2_trans_end(GFS2_SB(&ip->i_inode));
return error;
}
static int ea_set_simple_alloc(struct gfs2_inode *ip,
struct gfs2_ea_request *er, void *private)
{
struct ea_set *es = private;
struct gfs2_ea_header *ea = es->es_ea;
int error;
gfs2_trans_add_meta(ip->i_gl, es->es_bh);
if (es->ea_split)
ea = ea_split_ea(ea);
error = ea_write(ip, ea, er);
if (error)
return error;
if (es->es_el)
ea_set_remove_stuffed(ip, es->es_el);
return 0;
}
static int ea_set_simple(struct gfs2_inode *ip, struct buffer_head *bh,
struct gfs2_ea_header *ea, struct gfs2_ea_header *prev,
void *private)
{
struct ea_set *es = private;
unsigned int size;
int stuffed;
int error;
stuffed = ea_calc_size(GFS2_SB(&ip->i_inode), es->es_er->er_name_len,
es->es_er->er_data_len, &size);
if (ea->ea_type == GFS2_EATYPE_UNUSED) {
if (GFS2_EA_REC_LEN(ea) < size)
return 0;
if (!GFS2_EA_IS_STUFFED(ea)) {
error = ea_remove_unstuffed(ip, bh, ea, prev, 1);
if (error)
return error;
}
es->ea_split = 0;
} else if (GFS2_EA_REC_LEN(ea) - GFS2_EA_SIZE(ea) >= size)
es->ea_split = 1;
else
return 0;
if (stuffed) {
error = ea_set_simple_noalloc(ip, bh, ea, es);
if (error)
return error;
} else {
unsigned int blks;
es->es_bh = bh;
es->es_ea = ea;
blks = 2 + DIV_ROUND_UP(es->es_er->er_data_len,
GFS2_SB(&ip->i_inode)->sd_jbsize);
error = ea_alloc_skeleton(ip, es->es_er, blks,
ea_set_simple_alloc, es);
if (error)
return error;
}
return 1;
}
static int ea_set_block(struct gfs2_inode *ip, struct gfs2_ea_request *er,
void *private)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *indbh, *newbh;
__be64 *eablk;
int error;
int mh_size = sizeof(struct gfs2_meta_header);
if (ip->i_diskflags & GFS2_DIF_EA_INDIRECT) {
__be64 *end;
error = gfs2_meta_read(ip->i_gl, ip->i_eattr, DIO_WAIT, 0,
&indbh);
if (error)
return error;
if (gfs2_metatype_check(sdp, indbh, GFS2_METATYPE_IN)) {
error = -EIO;
goto out;
}
eablk = (__be64 *)(indbh->b_data + mh_size);
end = eablk + sdp->sd_inptrs;
for (; eablk < end; eablk++)
if (!*eablk)
break;
if (eablk == end) {
error = -ENOSPC;
goto out;
}
gfs2_trans_add_meta(ip->i_gl, indbh);
} else {
u64 blk;
unsigned int n = 1;
error = gfs2_alloc_blocks(ip, &blk, &n, 0, NULL);
if (error)
return error;
gfs2_trans_remove_revoke(sdp, blk, 1);
indbh = gfs2_meta_new(ip->i_gl, blk);
gfs2_trans_add_meta(ip->i_gl, indbh);
gfs2_metatype_set(indbh, GFS2_METATYPE_IN, GFS2_FORMAT_IN);
gfs2_buffer_clear_tail(indbh, mh_size);
eablk = (__be64 *)(indbh->b_data + mh_size);
*eablk = cpu_to_be64(ip->i_eattr);
ip->i_eattr = blk;
ip->i_diskflags |= GFS2_DIF_EA_INDIRECT;
gfs2_add_inode_blocks(&ip->i_inode, 1);
eablk++;
}
error = ea_alloc_blk(ip, &newbh);
if (error)
goto out;
*eablk = cpu_to_be64((u64)newbh->b_blocknr);
error = ea_write(ip, GFS2_EA_BH2FIRST(newbh), er);
brelse(newbh);
if (error)
goto out;
if (private)
ea_set_remove_stuffed(ip, private);
out:
brelse(indbh);
return error;
}
static int ea_set_i(struct gfs2_inode *ip, int type, const char *name,
const void *value, size_t size, struct gfs2_ea_location *el)
{
struct gfs2_ea_request er;
struct ea_set es;
unsigned int blks = 2;
int error;
er.er_type = type;
er.er_name = name;
er.er_data = (void *)value;
er.er_name_len = strlen(name);
er.er_data_len = size;
memset(&es, 0, sizeof(struct ea_set));
es.es_er = &er;
es.es_el = el;
error = ea_foreach(ip, ea_set_simple, &es);
if (error > 0)
return 0;
if (error)
return error;
if (!(ip->i_diskflags & GFS2_DIF_EA_INDIRECT))
blks++;
if (GFS2_EAREQ_SIZE_STUFFED(&er) > GFS2_SB(&ip->i_inode)->sd_jbsize)
blks += DIV_ROUND_UP(er.er_data_len, GFS2_SB(&ip->i_inode)->sd_jbsize);
return ea_alloc_skeleton(ip, &er, blks, ea_set_block, el);
}
static int ea_set_remove_unstuffed(struct gfs2_inode *ip,
struct gfs2_ea_location *el)
{
if (el->el_prev && GFS2_EA2NEXT(el->el_prev) != el->el_ea) {
el->el_prev = GFS2_EA2NEXT(el->el_prev);
gfs2_assert_withdraw(GFS2_SB(&ip->i_inode),
GFS2_EA2NEXT(el->el_prev) == el->el_ea);
}
return ea_remove_unstuffed(ip, el->el_bh, el->el_ea, el->el_prev, 0);
}
static int ea_remove_stuffed(struct gfs2_inode *ip, struct gfs2_ea_location *el)
{
struct gfs2_ea_header *ea = el->el_ea;
struct gfs2_ea_header *prev = el->el_prev;
int error;
error = gfs2_trans_begin(GFS2_SB(&ip->i_inode), RES_DINODE + RES_EATTR, 0);
if (error)
return error;
gfs2_trans_add_meta(ip->i_gl, el->el_bh);
if (prev) {
u32 len;
len = GFS2_EA_REC_LEN(prev) + GFS2_EA_REC_LEN(ea);
prev->ea_rec_len = cpu_to_be32(len);
if (GFS2_EA_IS_LAST(ea))
prev->ea_flags |= GFS2_EAFLAG_LAST;
} else {
ea->ea_type = GFS2_EATYPE_UNUSED;
}
inode_set_ctime_current(&ip->i_inode);
__mark_inode_dirty(&ip->i_inode, I_DIRTY_DATASYNC);
gfs2_trans_end(GFS2_SB(&ip->i_inode));
return error;
}
/**
* gfs2_xattr_remove - Remove a GFS2 extended attribute
* @ip: The inode
* @type: The type of the extended attribute
* @name: The name of the extended attribute
*
* This is not called directly by the VFS since we use the (common)
* scheme of making a "set with NULL data" mean a remove request. Note
* that this is different from a set with zero length data.
*
* Returns: 0, or errno on failure
*/
static int gfs2_xattr_remove(struct gfs2_inode *ip, int type, const char *name)
{
struct gfs2_ea_location el;
int error;
if (!ip->i_eattr)
return -ENODATA;
error = gfs2_ea_find(ip, type, name, &el);
if (error)
return error;
if (!el.el_ea)
return -ENODATA;
if (GFS2_EA_IS_STUFFED(el.el_ea))
error = ea_remove_stuffed(ip, &el);
else
error = ea_remove_unstuffed(ip, el.el_bh, el.el_ea, el.el_prev, 0);
brelse(el.el_bh);
return error;
}
/**
* __gfs2_xattr_set - Set (or remove) a GFS2 extended attribute
* @inode: The inode
* @name: The name of the extended attribute
* @value: The value of the extended attribute (NULL for remove)
* @size: The size of the @value argument
* @flags: Create or Replace
* @type: The type of the extended attribute
*
* See gfs2_xattr_remove() for details of the removal of xattrs.
*
* Returns: 0 or errno on failure
*/
int __gfs2_xattr_set(struct inode *inode, const char *name,
const void *value, size_t size, int flags, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_ea_location el;
unsigned int namel = strlen(name);
int error;
if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
return -EPERM;
if (namel > GFS2_EA_MAX_NAME_LEN)
return -ERANGE;
if (value == NULL) {
error = gfs2_xattr_remove(ip, type, name);
if (error == -ENODATA && !(flags & XATTR_REPLACE))
error = 0;
return error;
}
if (ea_check_size(sdp, namel, size))
return -ERANGE;
if (!ip->i_eattr) {
if (flags & XATTR_REPLACE)
return -ENODATA;
return ea_init(ip, type, name, value, size);
}
error = gfs2_ea_find(ip, type, name, &el);
if (error)
return error;
if (el.el_ea) {
if (ip->i_diskflags & GFS2_DIF_APPENDONLY) {
brelse(el.el_bh);
return -EPERM;
}
error = -EEXIST;
if (!(flags & XATTR_CREATE)) {
int unstuffed = !GFS2_EA_IS_STUFFED(el.el_ea);
error = ea_set_i(ip, type, name, value, size, &el);
if (!error && unstuffed)
ea_set_remove_unstuffed(ip, &el);
}
brelse(el.el_bh);
return error;
}
error = -ENODATA;
if (!(flags & XATTR_REPLACE))
error = ea_set_i(ip, type, name, value, size, NULL);
return error;
}
static int gfs2_xattr_set(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 gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int ret;
ret = gfs2_qa_get(ip);
if (ret)
return ret;
/* May be called from gfs_setattr with the glock locked. */
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (ret)
goto out;
} else {
if (WARN_ON_ONCE(ip->i_gl->gl_state != LM_ST_EXCLUSIVE)) {
ret = -EIO;
goto out;
}
gfs2_holder_mark_uninitialized(&gh);
}
ret = __gfs2_xattr_set(inode, name, value, size, flags, handler->flags);
if (gfs2_holder_initialized(&gh))
gfs2_glock_dq_uninit(&gh);
out:
gfs2_qa_put(ip);
return ret;
}
static int ea_dealloc_indirect(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrp_list rlist;
struct gfs2_rgrpd *rgd;
struct buffer_head *indbh, *dibh;
__be64 *eablk, *end;
unsigned int rg_blocks = 0;
u64 bstart = 0;
unsigned int blen = 0;
unsigned int blks = 0;
unsigned int x;
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
memset(&rlist, 0, sizeof(struct gfs2_rgrp_list));
error = gfs2_meta_read(ip->i_gl, ip->i_eattr, DIO_WAIT, 0, &indbh);
if (error)
return error;
if (gfs2_metatype_check(sdp, indbh, GFS2_METATYPE_IN)) {
error = -EIO;
goto out;
}
eablk = (__be64 *)(indbh->b_data + sizeof(struct gfs2_meta_header));
end = eablk + sdp->sd_inptrs;
for (; eablk < end; eablk++) {
u64 bn;
if (!*eablk)
break;
bn = be64_to_cpu(*eablk);
if (bstart + blen == bn)
blen++;
else {
if (bstart)
gfs2_rlist_add(ip, &rlist, bstart);
bstart = bn;
blen = 1;
}
blks++;
}
if (bstart)
gfs2_rlist_add(ip, &rlist, bstart);
else
goto out;
gfs2_rlist_alloc(&rlist, LM_ST_EXCLUSIVE, LM_FLAG_NODE_SCOPE);
for (x = 0; x < rlist.rl_rgrps; x++) {
rgd = gfs2_glock2rgrp(rlist.rl_ghs[x].gh_gl);
rg_blocks += rgd->rd_length;
}
error = gfs2_glock_nq_m(rlist.rl_rgrps, rlist.rl_ghs);
if (error)
goto out_rlist_free;
error = gfs2_trans_begin(sdp, rg_blocks + RES_DINODE + RES_INDIRECT +
RES_STATFS + RES_QUOTA, blks);
if (error)
goto out_gunlock;
gfs2_trans_add_meta(ip->i_gl, indbh);
eablk = (__be64 *)(indbh->b_data + sizeof(struct gfs2_meta_header));
bstart = 0;
rgd = NULL;
blen = 0;
for (; eablk < end; eablk++) {
u64 bn;
if (!*eablk)
break;
bn = be64_to_cpu(*eablk);
if (bstart + blen == bn)
blen++;
else {
if (bstart)
gfs2_free_meta(ip, rgd, bstart, blen);
bstart = bn;
rgd = gfs2_blk2rgrpd(sdp, bstart, true);
blen = 1;
}
*eablk = 0;
gfs2_add_inode_blocks(&ip->i_inode, -1);
}
if (bstart)
gfs2_free_meta(ip, rgd, bstart, blen);
ip->i_diskflags &= ~GFS2_DIF_EA_INDIRECT;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (!error) {
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
}
gfs2_trans_end(sdp);
out_gunlock:
gfs2_glock_dq_m(rlist.rl_rgrps, rlist.rl_ghs);
out_rlist_free:
gfs2_rlist_free(&rlist);
out:
brelse(indbh);
return error;
}
static int ea_dealloc_block(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *rgd;
struct buffer_head *dibh;
struct gfs2_holder gh;
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
rgd = gfs2_blk2rgrpd(sdp, ip->i_eattr, 1);
if (!rgd) {
gfs2_consist_inode(ip);
return -EIO;
}
error = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, &gh);
if (error)
return error;
error = gfs2_trans_begin(sdp, RES_RG_BIT + RES_DINODE + RES_STATFS +
RES_QUOTA, 1);
if (error)
goto out_gunlock;
gfs2_free_meta(ip, rgd, ip->i_eattr, 1);
ip->i_eattr = 0;
gfs2_add_inode_blocks(&ip->i_inode, -1);
if (likely(!test_bit(GIF_ALLOC_FAILED, &ip->i_flags))) {
error = gfs2_meta_inode_buffer(ip, &dibh);
if (!error) {
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
}
}
gfs2_trans_end(sdp);
out_gunlock:
gfs2_glock_dq_uninit(&gh);
return error;
}
/**
* gfs2_ea_dealloc - deallocate the extended attribute fork
* @ip: the inode
*
* Returns: errno
*/
int gfs2_ea_dealloc(struct gfs2_inode *ip)
{
int error;
error = gfs2_rindex_update(GFS2_SB(&ip->i_inode));
if (error)
return error;
error = gfs2_quota_hold(ip, NO_UID_QUOTA_CHANGE, NO_GID_QUOTA_CHANGE);
if (error)
return error;
if (likely(!test_bit(GIF_ALLOC_FAILED, &ip->i_flags))) {
error = ea_foreach(ip, ea_dealloc_unstuffed, NULL);
if (error)
goto out_quota;
if (ip->i_diskflags & GFS2_DIF_EA_INDIRECT) {
error = ea_dealloc_indirect(ip);
if (error)
goto out_quota;
}
}
error = ea_dealloc_block(ip);
out_quota:
gfs2_quota_unhold(ip);
return error;
}
static const struct xattr_handler gfs2_xattr_user_handler = {
.prefix = XATTR_USER_PREFIX,
.flags = GFS2_EATYPE_USR,
.get = gfs2_xattr_get,
.set = gfs2_xattr_set,
};
static const struct xattr_handler gfs2_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.flags = GFS2_EATYPE_SECURITY,
.get = gfs2_xattr_get,
.set = gfs2_xattr_set,
};
static bool
gfs2_xattr_trusted_list(struct dentry *dentry)
{
return capable(CAP_SYS_ADMIN);
}
static const struct xattr_handler gfs2_xattr_trusted_handler = {
.prefix = XATTR_TRUSTED_PREFIX,
.flags = GFS2_EATYPE_TRUSTED,
.list = gfs2_xattr_trusted_list,
.get = gfs2_xattr_get,
.set = gfs2_xattr_set,
};
const struct xattr_handler *gfs2_xattr_handlers_max[] = {
/* GFS2_FS_FORMAT_MAX */
&gfs2_xattr_trusted_handler,
/* GFS2_FS_FORMAT_MIN */
&gfs2_xattr_user_handler,
&gfs2_xattr_security_handler,
NULL,
};
const struct xattr_handler **gfs2_xattr_handlers_min = gfs2_xattr_handlers_max + 1;
| linux-master | fs/gfs2/xattr.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/cred.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/uaccess.h>
#include <linux/gfs2_ondisk.h>
#include <linux/blkdev.h>
#include "gfs2.h"
#include "incore.h"
#include "sys.h"
#include "super.h"
#include "glock.h"
#include "quota.h"
#include "util.h"
#include "glops.h"
#include "recovery.h"
struct gfs2_attr {
struct attribute attr;
ssize_t (*show)(struct gfs2_sbd *, char *);
ssize_t (*store)(struct gfs2_sbd *, const char *, size_t);
};
static ssize_t gfs2_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
struct gfs2_attr *a = container_of(attr, struct gfs2_attr, attr);
return a->show ? a->show(sdp, buf) : 0;
}
static ssize_t gfs2_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t len)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
struct gfs2_attr *a = container_of(attr, struct gfs2_attr, attr);
return a->store ? a->store(sdp, buf, len) : len;
}
static const struct sysfs_ops gfs2_attr_ops = {
.show = gfs2_attr_show,
.store = gfs2_attr_store,
};
static struct kset *gfs2_kset;
static ssize_t id_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u:%u\n",
MAJOR(sdp->sd_vfs->s_dev), MINOR(sdp->sd_vfs->s_dev));
}
static ssize_t status_show(struct gfs2_sbd *sdp, char *buf)
{
unsigned long f = sdp->sd_flags;
ssize_t s;
s = snprintf(buf, PAGE_SIZE,
"Journal Checked: %d\n"
"Journal Live: %d\n"
"Journal ID: %d\n"
"Spectator: %d\n"
"Withdrawn: %d\n"
"No barriers: %d\n"
"No recovery: %d\n"
"Demote: %d\n"
"No Journal ID: %d\n"
"Mounted RO: %d\n"
"RO Recovery: %d\n"
"Skip DLM Unlock: %d\n"
"Force AIL Flush: %d\n"
"FS Freeze Initiator: %d\n"
"FS Frozen: %d\n"
"Withdrawing: %d\n"
"Withdraw In Prog: %d\n"
"Remote Withdraw: %d\n"
"Withdraw Recovery: %d\n"
"Deactivating: %d\n"
"sd_log_error: %d\n"
"sd_log_flush_lock: %d\n"
"sd_log_num_revoke: %u\n"
"sd_log_in_flight: %d\n"
"sd_log_blks_needed: %d\n"
"sd_log_blks_free: %d\n"
"sd_log_flush_head: %d\n"
"sd_log_flush_tail: %d\n"
"sd_log_blks_reserved: %d\n"
"sd_log_revokes_available: %d\n"
"sd_log_pinned: %d\n"
"sd_log_thresh1: %d\n"
"sd_log_thresh2: %d\n",
test_bit(SDF_JOURNAL_CHECKED, &f),
test_bit(SDF_JOURNAL_LIVE, &f),
(sdp->sd_jdesc ? sdp->sd_jdesc->jd_jid : 0),
(sdp->sd_args.ar_spectator ? 1 : 0),
test_bit(SDF_WITHDRAWN, &f),
test_bit(SDF_NOBARRIERS, &f),
test_bit(SDF_NORECOVERY, &f),
test_bit(SDF_DEMOTE, &f),
test_bit(SDF_NOJOURNALID, &f),
(sb_rdonly(sdp->sd_vfs) ? 1 : 0),
test_bit(SDF_RORECOVERY, &f),
test_bit(SDF_SKIP_DLM_UNLOCK, &f),
test_bit(SDF_FORCE_AIL_FLUSH, &f),
test_bit(SDF_FREEZE_INITIATOR, &f),
test_bit(SDF_FROZEN, &f),
test_bit(SDF_WITHDRAWING, &f),
test_bit(SDF_WITHDRAW_IN_PROG, &f),
test_bit(SDF_REMOTE_WITHDRAW, &f),
test_bit(SDF_WITHDRAW_RECOVERY, &f),
test_bit(SDF_KILL, &f),
sdp->sd_log_error,
rwsem_is_locked(&sdp->sd_log_flush_lock),
sdp->sd_log_num_revoke,
atomic_read(&sdp->sd_log_in_flight),
atomic_read(&sdp->sd_log_blks_needed),
atomic_read(&sdp->sd_log_blks_free),
sdp->sd_log_flush_head,
sdp->sd_log_flush_tail,
sdp->sd_log_blks_reserved,
atomic_read(&sdp->sd_log_revokes_available),
atomic_read(&sdp->sd_log_pinned),
atomic_read(&sdp->sd_log_thresh1),
atomic_read(&sdp->sd_log_thresh2));
return s;
}
static ssize_t fsname_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", sdp->sd_fsname);
}
static ssize_t uuid_show(struct gfs2_sbd *sdp, char *buf)
{
struct super_block *s = sdp->sd_vfs;
buf[0] = '\0';
if (uuid_is_null(&s->s_uuid))
return 0;
return snprintf(buf, PAGE_SIZE, "%pUB\n", &s->s_uuid);
}
static ssize_t freeze_show(struct gfs2_sbd *sdp, char *buf)
{
struct super_block *sb = sdp->sd_vfs;
int frozen = (sb->s_writers.frozen == SB_UNFROZEN) ? 0 : 1;
return snprintf(buf, PAGE_SIZE, "%d\n", frozen);
}
static ssize_t freeze_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
int error, n;
error = kstrtoint(buf, 0, &n);
if (error)
return error;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
switch (n) {
case 0:
error = thaw_super(sdp->sd_vfs, FREEZE_HOLDER_USERSPACE);
break;
case 1:
error = freeze_super(sdp->sd_vfs, FREEZE_HOLDER_USERSPACE);
break;
default:
return -EINVAL;
}
if (error) {
fs_warn(sdp, "freeze %d error %d\n", n, error);
return error;
}
return len;
}
static ssize_t withdraw_show(struct gfs2_sbd *sdp, char *buf)
{
unsigned int b = gfs2_withdrawn(sdp);
return snprintf(buf, PAGE_SIZE, "%u\n", b);
}
static ssize_t withdraw_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
int error, val;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtoint(buf, 0, &val);
if (error)
return error;
if (val != 1)
return -EINVAL;
gfs2_lm(sdp, "withdrawing from cluster at user's request\n");
gfs2_withdraw(sdp);
return len;
}
static ssize_t statfs_sync_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
int error, val;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtoint(buf, 0, &val);
if (error)
return error;
if (val != 1)
return -EINVAL;
gfs2_statfs_sync(sdp->sd_vfs, 0);
return len;
}
static ssize_t quota_sync_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
int error, val;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtoint(buf, 0, &val);
if (error)
return error;
if (val != 1)
return -EINVAL;
gfs2_quota_sync(sdp->sd_vfs, 0);
return len;
}
static ssize_t quota_refresh_user_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
struct kqid qid;
int error;
u32 id;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtou32(buf, 0, &id);
if (error)
return error;
qid = make_kqid(current_user_ns(), USRQUOTA, id);
if (!qid_valid(qid))
return -EINVAL;
error = gfs2_quota_refresh(sdp, qid);
return error ? error : len;
}
static ssize_t quota_refresh_group_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
struct kqid qid;
int error;
u32 id;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtou32(buf, 0, &id);
if (error)
return error;
qid = make_kqid(current_user_ns(), GRPQUOTA, id);
if (!qid_valid(qid))
return -EINVAL;
error = gfs2_quota_refresh(sdp, qid);
return error ? error : len;
}
static ssize_t demote_rq_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
struct gfs2_glock *gl;
const struct gfs2_glock_operations *glops;
unsigned int glmode;
unsigned int gltype;
unsigned long long glnum;
char mode[16];
int rv;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
rv = sscanf(buf, "%u:%llu %15s", &gltype, &glnum,
mode);
if (rv != 3)
return -EINVAL;
if (strcmp(mode, "EX") == 0)
glmode = LM_ST_UNLOCKED;
else if ((strcmp(mode, "CW") == 0) || (strcmp(mode, "DF") == 0))
glmode = LM_ST_DEFERRED;
else if ((strcmp(mode, "PR") == 0) || (strcmp(mode, "SH") == 0))
glmode = LM_ST_SHARED;
else
return -EINVAL;
if (gltype > LM_TYPE_JOURNAL)
return -EINVAL;
if (gltype == LM_TYPE_NONDISK && glnum == GFS2_FREEZE_LOCK)
glops = &gfs2_freeze_glops;
else
glops = gfs2_glops_list[gltype];
if (glops == NULL)
return -EINVAL;
if (!test_and_set_bit(SDF_DEMOTE, &sdp->sd_flags))
fs_info(sdp, "demote interface used\n");
rv = gfs2_glock_get(sdp, glnum, glops, 0, &gl);
if (rv)
return rv;
gfs2_glock_cb(gl, glmode);
gfs2_glock_put(gl);
return len;
}
#define GFS2_ATTR(name, mode, show, store) \
static struct gfs2_attr gfs2_attr_##name = __ATTR(name, mode, show, store)
GFS2_ATTR(id, 0444, id_show, NULL);
GFS2_ATTR(fsname, 0444, fsname_show, NULL);
GFS2_ATTR(uuid, 0444, uuid_show, NULL);
GFS2_ATTR(freeze, 0644, freeze_show, freeze_store);
GFS2_ATTR(withdraw, 0644, withdraw_show, withdraw_store);
GFS2_ATTR(statfs_sync, 0200, NULL, statfs_sync_store);
GFS2_ATTR(quota_sync, 0200, NULL, quota_sync_store);
GFS2_ATTR(quota_refresh_user, 0200, NULL, quota_refresh_user_store);
GFS2_ATTR(quota_refresh_group, 0200, NULL, quota_refresh_group_store);
GFS2_ATTR(demote_rq, 0200, NULL, demote_rq_store);
GFS2_ATTR(status, 0400, status_show, NULL);
static struct attribute *gfs2_attrs[] = {
&gfs2_attr_id.attr,
&gfs2_attr_fsname.attr,
&gfs2_attr_uuid.attr,
&gfs2_attr_freeze.attr,
&gfs2_attr_withdraw.attr,
&gfs2_attr_statfs_sync.attr,
&gfs2_attr_quota_sync.attr,
&gfs2_attr_quota_refresh_user.attr,
&gfs2_attr_quota_refresh_group.attr,
&gfs2_attr_demote_rq.attr,
&gfs2_attr_status.attr,
NULL,
};
ATTRIBUTE_GROUPS(gfs2);
static void gfs2_sbd_release(struct kobject *kobj)
{
struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
complete(&sdp->sd_kobj_unregister);
}
static struct kobj_type gfs2_ktype = {
.release = gfs2_sbd_release,
.default_groups = gfs2_groups,
.sysfs_ops = &gfs2_attr_ops,
};
/*
* lock_module. Originally from lock_dlm
*/
static ssize_t proto_name_show(struct gfs2_sbd *sdp, char *buf)
{
const struct lm_lockops *ops = sdp->sd_lockstruct.ls_ops;
return sprintf(buf, "%s\n", ops->lm_proto_name);
}
static ssize_t block_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
ssize_t ret;
int val = 0;
if (test_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags))
val = 1;
ret = sprintf(buf, "%d\n", val);
return ret;
}
static ssize_t block_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int ret, val;
ret = kstrtoint(buf, 0, &val);
if (ret)
return ret;
if (val == 1)
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
else if (val == 0) {
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
smp_mb__after_atomic();
gfs2_glock_thaw(sdp);
} else {
return -EINVAL;
}
return len;
}
static ssize_t wdack_show(struct gfs2_sbd *sdp, char *buf)
{
int val = completion_done(&sdp->sd_wdack) ? 1 : 0;
return sprintf(buf, "%d\n", val);
}
static ssize_t wdack_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
int ret, val;
ret = kstrtoint(buf, 0, &val);
if (ret)
return ret;
if ((val == 1) &&
!strcmp(sdp->sd_lockstruct.ls_ops->lm_proto_name, "lock_dlm"))
complete(&sdp->sd_wdack);
else
return -EINVAL;
return len;
}
static ssize_t lkfirst_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_first);
}
static ssize_t lkfirst_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
unsigned first;
int rv;
rv = sscanf(buf, "%u", &first);
if (rv != 1 || first > 1)
return -EINVAL;
rv = wait_for_completion_killable(&sdp->sd_locking_init);
if (rv)
return rv;
spin_lock(&sdp->sd_jindex_spin);
rv = -EBUSY;
if (test_bit(SDF_NOJOURNALID, &sdp->sd_flags) == 0)
goto out;
rv = -EINVAL;
if (sdp->sd_args.ar_spectator)
goto out;
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
goto out;
sdp->sd_lockstruct.ls_first = first;
rv = 0;
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv ? rv : len;
}
static ssize_t first_done_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", !!test_bit(DFL_FIRST_MOUNT_DONE, &ls->ls_recover_flags));
}
int gfs2_recover_set(struct gfs2_sbd *sdp, unsigned jid)
{
struct gfs2_jdesc *jd;
int rv;
/* Wait for our primary journal to be initialized */
wait_for_completion(&sdp->sd_journal_ready);
spin_lock(&sdp->sd_jindex_spin);
rv = -EBUSY;
/**
* If we're a spectator, we use journal0, but it's not really ours.
* So we need to wait for its recovery too. If we skip it we'd never
* queue work to the recovery workqueue, and so its completion would
* never clear the DFL_BLOCK_LOCKS flag, so all our locks would
* permanently stop working.
*/
if (!sdp->sd_jdesc)
goto out;
if (sdp->sd_jdesc->jd_jid == jid && !sdp->sd_args.ar_spectator)
goto out;
rv = -ENOENT;
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
if (jd->jd_jid != jid && !sdp->sd_args.ar_spectator)
continue;
rv = gfs2_recover_journal(jd, false);
break;
}
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv;
}
static ssize_t recover_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
unsigned jid;
int rv;
rv = sscanf(buf, "%u", &jid);
if (rv != 1)
return -EINVAL;
if (test_bit(SDF_NORECOVERY, &sdp->sd_flags)) {
rv = -ESHUTDOWN;
goto out;
}
rv = gfs2_recover_set(sdp, jid);
out:
return rv ? rv : len;
}
static ssize_t recover_done_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_recover_jid_done);
}
static ssize_t recover_status_show(struct gfs2_sbd *sdp, char *buf)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sprintf(buf, "%d\n", ls->ls_recover_jid_status);
}
static ssize_t jid_show(struct gfs2_sbd *sdp, char *buf)
{
return sprintf(buf, "%d\n", sdp->sd_lockstruct.ls_jid);
}
static ssize_t jid_store(struct gfs2_sbd *sdp, const char *buf, size_t len)
{
int jid;
int rv;
rv = sscanf(buf, "%d", &jid);
if (rv != 1)
return -EINVAL;
rv = wait_for_completion_killable(&sdp->sd_locking_init);
if (rv)
return rv;
spin_lock(&sdp->sd_jindex_spin);
rv = -EINVAL;
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
goto out;
rv = -EBUSY;
if (test_bit(SDF_NOJOURNALID, &sdp->sd_flags) == 0)
goto out;
rv = 0;
if (sdp->sd_args.ar_spectator && jid > 0)
rv = jid = -EINVAL;
sdp->sd_lockstruct.ls_jid = jid;
clear_bit(SDF_NOJOURNALID, &sdp->sd_flags);
smp_mb__after_atomic();
wake_up_bit(&sdp->sd_flags, SDF_NOJOURNALID);
out:
spin_unlock(&sdp->sd_jindex_spin);
return rv ? rv : len;
}
#define GDLM_ATTR(_name,_mode,_show,_store) \
static struct gfs2_attr gdlm_attr_##_name = __ATTR(_name,_mode,_show,_store)
GDLM_ATTR(proto_name, 0444, proto_name_show, NULL);
GDLM_ATTR(block, 0644, block_show, block_store);
GDLM_ATTR(withdraw, 0644, wdack_show, wdack_store);
GDLM_ATTR(jid, 0644, jid_show, jid_store);
GDLM_ATTR(first, 0644, lkfirst_show, lkfirst_store);
GDLM_ATTR(first_done, 0444, first_done_show, NULL);
GDLM_ATTR(recover, 0600, NULL, recover_store);
GDLM_ATTR(recover_done, 0444, recover_done_show, NULL);
GDLM_ATTR(recover_status, 0444, recover_status_show, NULL);
static struct attribute *lock_module_attrs[] = {
&gdlm_attr_proto_name.attr,
&gdlm_attr_block.attr,
&gdlm_attr_withdraw.attr,
&gdlm_attr_jid.attr,
&gdlm_attr_first.attr,
&gdlm_attr_first_done.attr,
&gdlm_attr_recover.attr,
&gdlm_attr_recover_done.attr,
&gdlm_attr_recover_status.attr,
NULL,
};
/*
* get and set struct gfs2_tune fields
*/
static ssize_t quota_scale_show(struct gfs2_sbd *sdp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u %u\n",
sdp->sd_tune.gt_quota_scale_num,
sdp->sd_tune.gt_quota_scale_den);
}
static ssize_t quota_scale_store(struct gfs2_sbd *sdp, const char *buf,
size_t len)
{
struct gfs2_tune *gt = &sdp->sd_tune;
unsigned int x, y;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (sscanf(buf, "%u %u", &x, &y) != 2 || !y)
return -EINVAL;
spin_lock(>->gt_spin);
gt->gt_quota_scale_num = x;
gt->gt_quota_scale_den = y;
spin_unlock(>->gt_spin);
return len;
}
static ssize_t tune_set(struct gfs2_sbd *sdp, unsigned int *field,
int check_zero, const char *buf, size_t len)
{
struct gfs2_tune *gt = &sdp->sd_tune;
unsigned int x;
int error;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
error = kstrtouint(buf, 0, &x);
if (error)
return error;
if (check_zero && !x)
return -EINVAL;
spin_lock(>->gt_spin);
*field = x;
spin_unlock(>->gt_spin);
return len;
}
#define TUNE_ATTR_3(name, show, store) \
static struct gfs2_attr tune_attr_##name = __ATTR(name, 0644, show, store)
#define TUNE_ATTR_2(name, store) \
static ssize_t name##_show(struct gfs2_sbd *sdp, char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%u\n", sdp->sd_tune.gt_##name); \
} \
TUNE_ATTR_3(name, name##_show, store)
#define TUNE_ATTR(name, check_zero) \
static ssize_t name##_store(struct gfs2_sbd *sdp, const char *buf, size_t len)\
{ \
return tune_set(sdp, &sdp->sd_tune.gt_##name, check_zero, buf, len); \
} \
TUNE_ATTR_2(name, name##_store)
TUNE_ATTR(quota_warn_period, 0);
TUNE_ATTR(quota_quantum, 0);
TUNE_ATTR(max_readahead, 0);
TUNE_ATTR(complain_secs, 0);
TUNE_ATTR(statfs_slow, 0);
TUNE_ATTR(new_files_jdata, 0);
TUNE_ATTR(statfs_quantum, 1);
TUNE_ATTR_3(quota_scale, quota_scale_show, quota_scale_store);
static struct attribute *tune_attrs[] = {
&tune_attr_quota_warn_period.attr,
&tune_attr_quota_quantum.attr,
&tune_attr_max_readahead.attr,
&tune_attr_complain_secs.attr,
&tune_attr_statfs_slow.attr,
&tune_attr_statfs_quantum.attr,
&tune_attr_quota_scale.attr,
&tune_attr_new_files_jdata.attr,
NULL,
};
static const struct attribute_group tune_group = {
.name = "tune",
.attrs = tune_attrs,
};
static const struct attribute_group lock_module_group = {
.name = "lock_module",
.attrs = lock_module_attrs,
};
int gfs2_sys_fs_add(struct gfs2_sbd *sdp)
{
struct super_block *sb = sdp->sd_vfs;
int error;
char ro[20];
char spectator[20];
char *envp[] = { ro, spectator, NULL };
sprintf(ro, "RDONLY=%d", sb_rdonly(sb));
sprintf(spectator, "SPECTATOR=%d", sdp->sd_args.ar_spectator ? 1 : 0);
init_completion(&sdp->sd_kobj_unregister);
sdp->sd_kobj.kset = gfs2_kset;
error = kobject_init_and_add(&sdp->sd_kobj, &gfs2_ktype, NULL,
"%s", sdp->sd_table_name);
if (error)
goto fail_reg;
error = sysfs_create_group(&sdp->sd_kobj, &tune_group);
if (error)
goto fail_reg;
error = sysfs_create_group(&sdp->sd_kobj, &lock_module_group);
if (error)
goto fail_tune;
error = sysfs_create_link(&sdp->sd_kobj,
&disk_to_dev(sb->s_bdev->bd_disk)->kobj,
"device");
if (error)
goto fail_lock_module;
kobject_uevent_env(&sdp->sd_kobj, KOBJ_ADD, envp);
return 0;
fail_lock_module:
sysfs_remove_group(&sdp->sd_kobj, &lock_module_group);
fail_tune:
sysfs_remove_group(&sdp->sd_kobj, &tune_group);
fail_reg:
fs_err(sdp, "error %d adding sysfs files\n", error);
kobject_put(&sdp->sd_kobj);
wait_for_completion(&sdp->sd_kobj_unregister);
sb->s_fs_info = NULL;
return error;
}
void gfs2_sys_fs_del(struct gfs2_sbd *sdp)
{
sysfs_remove_link(&sdp->sd_kobj, "device");
sysfs_remove_group(&sdp->sd_kobj, &tune_group);
sysfs_remove_group(&sdp->sd_kobj, &lock_module_group);
kobject_put(&sdp->sd_kobj);
wait_for_completion(&sdp->sd_kobj_unregister);
}
static int gfs2_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
{
const struct gfs2_sbd *sdp = container_of(kobj, struct gfs2_sbd, sd_kobj);
const struct super_block *s = sdp->sd_vfs;
add_uevent_var(env, "LOCKTABLE=%s", sdp->sd_table_name);
add_uevent_var(env, "LOCKPROTO=%s", sdp->sd_proto_name);
if (!test_bit(SDF_NOJOURNALID, &sdp->sd_flags))
add_uevent_var(env, "JOURNALID=%d", sdp->sd_lockstruct.ls_jid);
if (!uuid_is_null(&s->s_uuid))
add_uevent_var(env, "UUID=%pUB", &s->s_uuid);
return 0;
}
static const struct kset_uevent_ops gfs2_uevent_ops = {
.uevent = gfs2_uevent,
};
int gfs2_sys_init(void)
{
gfs2_kset = kset_create_and_add("gfs2", &gfs2_uevent_ops, fs_kobj);
if (!gfs2_kset)
return -ENOMEM;
return 0;
}
void gfs2_sys_uninit(void)
{
kset_unregister(gfs2_kset);
}
| linux-master | fs/gfs2/sys.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/kthread.h>
#include <linux/crc32.h>
#include <linux/gfs2_ondisk.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include "gfs2.h"
#include "incore.h"
#include "glock.h"
#include "glops.h"
#include "log.h"
#include "lops.h"
#include "recovery.h"
#include "rgrp.h"
#include "super.h"
#include "util.h"
struct kmem_cache *gfs2_glock_cachep __read_mostly;
struct kmem_cache *gfs2_glock_aspace_cachep __read_mostly;
struct kmem_cache *gfs2_inode_cachep __read_mostly;
struct kmem_cache *gfs2_bufdata_cachep __read_mostly;
struct kmem_cache *gfs2_rgrpd_cachep __read_mostly;
struct kmem_cache *gfs2_quotad_cachep __read_mostly;
struct kmem_cache *gfs2_qadata_cachep __read_mostly;
struct kmem_cache *gfs2_trans_cachep __read_mostly;
mempool_t *gfs2_page_pool __read_mostly;
void gfs2_assert_i(struct gfs2_sbd *sdp)
{
fs_emerg(sdp, "fatal assertion failed\n");
}
/**
* check_journal_clean - Make sure a journal is clean for a spectator mount
* @sdp: The GFS2 superblock
* @jd: The journal descriptor
* @verbose: Show more prints in the log
*
* Returns: 0 if the journal is clean or locked, else an error
*/
int check_journal_clean(struct gfs2_sbd *sdp, struct gfs2_jdesc *jd,
bool verbose)
{
int error;
struct gfs2_holder j_gh;
struct gfs2_log_header_host head;
struct gfs2_inode *ip;
ip = GFS2_I(jd->jd_inode);
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_NOEXP |
GL_EXACT | GL_NOCACHE, &j_gh);
if (error) {
if (verbose)
fs_err(sdp, "Error %d locking journal for spectator "
"mount.\n", error);
return -EPERM;
}
error = gfs2_jdesc_check(jd);
if (error) {
if (verbose)
fs_err(sdp, "Error checking journal for spectator "
"mount.\n");
goto out_unlock;
}
error = gfs2_find_jhead(jd, &head, false);
if (error) {
if (verbose)
fs_err(sdp, "Error parsing journal for spectator "
"mount.\n");
goto out_unlock;
}
if (!(head.lh_flags & GFS2_LOG_HEAD_UNMOUNT)) {
error = -EPERM;
if (verbose)
fs_err(sdp, "jid=%u: Journal is dirty, so the first "
"mounter must not be a spectator.\n",
jd->jd_jid);
}
out_unlock:
gfs2_glock_dq_uninit(&j_gh);
return error;
}
/**
* gfs2_freeze_lock_shared - hold the freeze glock
* @sdp: the superblock
*/
int gfs2_freeze_lock_shared(struct gfs2_sbd *sdp)
{
int error;
error = gfs2_glock_nq_init(sdp->sd_freeze_gl, LM_ST_SHARED,
LM_FLAG_NOEXP | GL_EXACT,
&sdp->sd_freeze_gh);
if (error)
fs_err(sdp, "can't lock the freeze glock: %d\n", error);
return error;
}
void gfs2_freeze_unlock(struct gfs2_holder *freeze_gh)
{
if (gfs2_holder_initialized(freeze_gh))
gfs2_glock_dq_uninit(freeze_gh);
}
static void signal_our_withdraw(struct gfs2_sbd *sdp)
{
struct gfs2_glock *live_gl = sdp->sd_live_gh.gh_gl;
struct inode *inode;
struct gfs2_inode *ip;
struct gfs2_glock *i_gl;
u64 no_formal_ino;
int ret = 0;
int tries;
if (test_bit(SDF_NORECOVERY, &sdp->sd_flags) || !sdp->sd_jdesc)
return;
gfs2_ail_drain(sdp); /* frees all transactions */
inode = sdp->sd_jdesc->jd_inode;
ip = GFS2_I(inode);
i_gl = ip->i_gl;
no_formal_ino = ip->i_no_formal_ino;
/* Prevent any glock dq until withdraw recovery is complete */
set_bit(SDF_WITHDRAW_RECOVERY, &sdp->sd_flags);
/*
* Don't tell dlm we're bailing until we have no more buffers in the
* wind. If journal had an IO error, the log code should just purge
* the outstanding buffers rather than submitting new IO. Making the
* file system read-only will flush the journal, etc.
*
* During a normal unmount, gfs2_make_fs_ro calls gfs2_log_shutdown
* which clears SDF_JOURNAL_LIVE. In a withdraw, we must not write
* any UNMOUNT log header, so we can't call gfs2_log_shutdown, and
* therefore we need to clear SDF_JOURNAL_LIVE manually.
*/
clear_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags);
if (!sb_rdonly(sdp->sd_vfs)) {
bool locked = mutex_trylock(&sdp->sd_freeze_mutex);
wake_up(&sdp->sd_logd_waitq);
wake_up(&sdp->sd_quota_wait);
wait_event_timeout(sdp->sd_log_waitq,
gfs2_log_is_empty(sdp),
HZ * 5);
sdp->sd_vfs->s_flags |= SB_RDONLY;
if (locked)
mutex_unlock(&sdp->sd_freeze_mutex);
/*
* Dequeue any pending non-system glock holders that can no
* longer be granted because the file system is withdrawn.
*/
gfs2_gl_dq_holders(sdp);
}
if (sdp->sd_lockstruct.ls_ops->lm_lock == NULL) { /* lock_nolock */
if (!ret)
ret = -EIO;
clear_bit(SDF_WITHDRAW_RECOVERY, &sdp->sd_flags);
goto skip_recovery;
}
/*
* Drop the glock for our journal so another node can recover it.
*/
if (gfs2_holder_initialized(&sdp->sd_journal_gh)) {
gfs2_glock_dq_wait(&sdp->sd_journal_gh);
gfs2_holder_uninit(&sdp->sd_journal_gh);
}
sdp->sd_jinode_gh.gh_flags |= GL_NOCACHE;
gfs2_glock_dq(&sdp->sd_jinode_gh);
gfs2_thaw_freeze_initiator(sdp->sd_vfs);
wait_on_bit(&i_gl->gl_flags, GLF_DEMOTE, TASK_UNINTERRUPTIBLE);
/*
* holder_uninit to force glock_put, to force dlm to let go
*/
gfs2_holder_uninit(&sdp->sd_jinode_gh);
/*
* Note: We need to be careful here:
* Our iput of jd_inode will evict it. The evict will dequeue its
* glock, but the glock dq will wait for the withdraw unless we have
* exception code in glock_dq.
*/
iput(inode);
sdp->sd_jdesc->jd_inode = NULL;
/*
* Wait until the journal inode's glock is freed. This allows try locks
* on other nodes to be successful, otherwise we remain the owner of
* the glock as far as dlm is concerned.
*/
if (i_gl->gl_ops->go_free) {
set_bit(GLF_FREEING, &i_gl->gl_flags);
wait_on_bit(&i_gl->gl_flags, GLF_FREEING, TASK_UNINTERRUPTIBLE);
}
/*
* Dequeue the "live" glock, but keep a reference so it's never freed.
*/
gfs2_glock_hold(live_gl);
gfs2_glock_dq_wait(&sdp->sd_live_gh);
/*
* We enqueue the "live" glock in EX so that all other nodes
* get a demote request and act on it. We don't really want the
* lock in EX, so we send a "try" lock with 1CB to produce a callback.
*/
fs_warn(sdp, "Requesting recovery of jid %d.\n",
sdp->sd_lockstruct.ls_jid);
gfs2_holder_reinit(LM_ST_EXCLUSIVE,
LM_FLAG_TRY_1CB | LM_FLAG_NOEXP | GL_NOPID,
&sdp->sd_live_gh);
msleep(GL_GLOCK_MAX_HOLD);
/*
* This will likely fail in a cluster, but succeed standalone:
*/
ret = gfs2_glock_nq(&sdp->sd_live_gh);
/*
* If we actually got the "live" lock in EX mode, there are no other
* nodes available to replay our journal. So we try to replay it
* ourselves. We hold the "live" glock to prevent other mounters
* during recovery, then just dequeue it and reacquire it in our
* normal SH mode. Just in case the problem that caused us to
* withdraw prevents us from recovering our journal (e.g. io errors
* and such) we still check if the journal is clean before proceeding
* but we may wait forever until another mounter does the recovery.
*/
if (ret == 0) {
fs_warn(sdp, "No other mounters found. Trying to recover our "
"own journal jid %d.\n", sdp->sd_lockstruct.ls_jid);
if (gfs2_recover_journal(sdp->sd_jdesc, 1))
fs_warn(sdp, "Unable to recover our journal jid %d.\n",
sdp->sd_lockstruct.ls_jid);
gfs2_glock_dq_wait(&sdp->sd_live_gh);
gfs2_holder_reinit(LM_ST_SHARED,
LM_FLAG_NOEXP | GL_EXACT | GL_NOPID,
&sdp->sd_live_gh);
gfs2_glock_nq(&sdp->sd_live_gh);
}
gfs2_glock_queue_put(live_gl); /* drop extra reference we acquired */
clear_bit(SDF_WITHDRAW_RECOVERY, &sdp->sd_flags);
/*
* At this point our journal is evicted, so we need to get a new inode
* for it. Once done, we need to call gfs2_find_jhead which
* calls gfs2_map_journal_extents to map it for us again.
*
* Note that we don't really want it to look up a FREE block. The
* GFS2_BLKST_FREE simply overrides a block check in gfs2_inode_lookup
* which would otherwise fail because it requires grabbing an rgrp
* glock, which would fail with -EIO because we're withdrawing.
*/
inode = gfs2_inode_lookup(sdp->sd_vfs, DT_UNKNOWN,
sdp->sd_jdesc->jd_no_addr, no_formal_ino,
GFS2_BLKST_FREE);
if (IS_ERR(inode)) {
fs_warn(sdp, "Reprocessing of jid %d failed with %ld.\n",
sdp->sd_lockstruct.ls_jid, PTR_ERR(inode));
goto skip_recovery;
}
sdp->sd_jdesc->jd_inode = inode;
d_mark_dontcache(inode);
/*
* Now wait until recovery is complete.
*/
for (tries = 0; tries < 10; tries++) {
ret = check_journal_clean(sdp, sdp->sd_jdesc, false);
if (!ret)
break;
msleep(HZ);
fs_warn(sdp, "Waiting for journal recovery jid %d.\n",
sdp->sd_lockstruct.ls_jid);
}
skip_recovery:
if (!ret)
fs_warn(sdp, "Journal recovery complete for jid %d.\n",
sdp->sd_lockstruct.ls_jid);
else
fs_warn(sdp, "Journal recovery skipped for jid %d until next "
"mount.\n", sdp->sd_lockstruct.ls_jid);
fs_warn(sdp, "Glock dequeues delayed: %lu\n", sdp->sd_glock_dqs_held);
sdp->sd_glock_dqs_held = 0;
wake_up_bit(&sdp->sd_flags, SDF_WITHDRAW_RECOVERY);
}
void gfs2_lm(struct gfs2_sbd *sdp, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (sdp->sd_args.ar_errors == GFS2_ERRORS_WITHDRAW &&
test_bit(SDF_WITHDRAWN, &sdp->sd_flags))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
fs_err(sdp, "%pV", &vaf);
va_end(args);
}
int gfs2_withdraw(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
const struct lm_lockops *lm = ls->ls_ops;
if (sdp->sd_args.ar_errors == GFS2_ERRORS_WITHDRAW) {
unsigned long old = READ_ONCE(sdp->sd_flags), new;
do {
if (old & BIT(SDF_WITHDRAWN)) {
wait_on_bit(&sdp->sd_flags,
SDF_WITHDRAW_IN_PROG,
TASK_UNINTERRUPTIBLE);
return -1;
}
new = old | BIT(SDF_WITHDRAWN) | BIT(SDF_WITHDRAW_IN_PROG);
} while (unlikely(!try_cmpxchg(&sdp->sd_flags, &old, new)));
fs_err(sdp, "about to withdraw this file system\n");
BUG_ON(sdp->sd_args.ar_debug);
signal_our_withdraw(sdp);
kobject_uevent(&sdp->sd_kobj, KOBJ_OFFLINE);
if (!strcmp(sdp->sd_lockstruct.ls_ops->lm_proto_name, "lock_dlm"))
wait_for_completion(&sdp->sd_wdack);
if (lm->lm_unmount) {
fs_err(sdp, "telling LM to unmount\n");
lm->lm_unmount(sdp);
}
set_bit(SDF_SKIP_DLM_UNLOCK, &sdp->sd_flags);
fs_err(sdp, "File system withdrawn\n");
dump_stack();
clear_bit(SDF_WITHDRAW_IN_PROG, &sdp->sd_flags);
smp_mb__after_atomic();
wake_up_bit(&sdp->sd_flags, SDF_WITHDRAW_IN_PROG);
}
if (sdp->sd_args.ar_errors == GFS2_ERRORS_PANIC)
panic("GFS2: fsid=%s: panic requested\n", sdp->sd_fsname);
return -1;
}
/*
* gfs2_assert_withdraw_i - Cause the machine to withdraw if @assertion is false
*/
void gfs2_assert_withdraw_i(struct gfs2_sbd *sdp, char *assertion,
const char *function, char *file, unsigned int line,
bool delayed)
{
if (gfs2_withdrawn(sdp))
return;
fs_err(sdp,
"fatal: assertion \"%s\" failed\n"
" function = %s, file = %s, line = %u\n",
assertion, function, file, line);
/*
* If errors=panic was specified on mount, it won't help to delay the
* withdraw.
*/
if (sdp->sd_args.ar_errors == GFS2_ERRORS_PANIC)
delayed = false;
if (delayed)
gfs2_withdraw_delayed(sdp);
else
gfs2_withdraw(sdp);
dump_stack();
}
/*
* gfs2_assert_warn_i - Print a message to the console if @assertion is false
*/
void gfs2_assert_warn_i(struct gfs2_sbd *sdp, char *assertion,
const char *function, char *file, unsigned int line)
{
if (time_before(jiffies,
sdp->sd_last_warning +
gfs2_tune_get(sdp, gt_complain_secs) * HZ))
return;
if (sdp->sd_args.ar_errors == GFS2_ERRORS_WITHDRAW)
fs_warn(sdp, "warning: assertion \"%s\" failed at function = %s, file = %s, line = %u\n",
assertion, function, file, line);
if (sdp->sd_args.ar_debug)
BUG();
else
dump_stack();
if (sdp->sd_args.ar_errors == GFS2_ERRORS_PANIC)
panic("GFS2: fsid=%s: warning: assertion \"%s\" failed\n"
"GFS2: fsid=%s: function = %s, file = %s, line = %u\n",
sdp->sd_fsname, assertion,
sdp->sd_fsname, function, file, line);
sdp->sd_last_warning = jiffies;
}
/*
* gfs2_consist_i - Flag a filesystem consistency error and withdraw
*/
void gfs2_consist_i(struct gfs2_sbd *sdp, const char *function,
char *file, unsigned int line)
{
gfs2_lm(sdp,
"fatal: filesystem consistency error - function = %s, file = %s, line = %u\n",
function, file, line);
gfs2_withdraw(sdp);
}
/*
* gfs2_consist_inode_i - Flag an inode consistency error and withdraw
*/
void gfs2_consist_inode_i(struct gfs2_inode *ip,
const char *function, char *file, unsigned int line)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
gfs2_lm(sdp,
"fatal: filesystem consistency error\n"
" inode = %llu %llu\n"
" function = %s, file = %s, line = %u\n",
(unsigned long long)ip->i_no_formal_ino,
(unsigned long long)ip->i_no_addr,
function, file, line);
gfs2_dump_glock(NULL, ip->i_gl, 1);
gfs2_withdraw(sdp);
}
/*
* gfs2_consist_rgrpd_i - Flag a RG consistency error and withdraw
*/
void gfs2_consist_rgrpd_i(struct gfs2_rgrpd *rgd,
const char *function, char *file, unsigned int line)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
char fs_id_buf[sizeof(sdp->sd_fsname) + 7];
sprintf(fs_id_buf, "fsid=%s: ", sdp->sd_fsname);
gfs2_rgrp_dump(NULL, rgd, fs_id_buf);
gfs2_lm(sdp,
"fatal: filesystem consistency error\n"
" RG = %llu\n"
" function = %s, file = %s, line = %u\n",
(unsigned long long)rgd->rd_addr,
function, file, line);
gfs2_dump_glock(NULL, rgd->rd_gl, 1);
gfs2_withdraw(sdp);
}
/*
* gfs2_meta_check_ii - Flag a magic number consistency error and withdraw
* Returns: -1 if this call withdrew the machine,
* -2 if it was already withdrawn
*/
int gfs2_meta_check_ii(struct gfs2_sbd *sdp, struct buffer_head *bh,
const char *type, const char *function, char *file,
unsigned int line)
{
int me;
gfs2_lm(sdp,
"fatal: invalid metadata block\n"
" bh = %llu (%s)\n"
" function = %s, file = %s, line = %u\n",
(unsigned long long)bh->b_blocknr, type,
function, file, line);
me = gfs2_withdraw(sdp);
return (me) ? -1 : -2;
}
/*
* gfs2_metatype_check_ii - Flag a metadata type consistency error and withdraw
* Returns: -1 if this call withdrew the machine,
* -2 if it was already withdrawn
*/
int gfs2_metatype_check_ii(struct gfs2_sbd *sdp, struct buffer_head *bh,
u16 type, u16 t, const char *function,
char *file, unsigned int line)
{
int me;
gfs2_lm(sdp,
"fatal: invalid metadata block\n"
" bh = %llu (type: exp=%u, found=%u)\n"
" function = %s, file = %s, line = %u\n",
(unsigned long long)bh->b_blocknr, type, t,
function, file, line);
me = gfs2_withdraw(sdp);
return (me) ? -1 : -2;
}
/*
* gfs2_io_error_i - Flag an I/O error and withdraw
* Returns: -1 if this call withdrew the machine,
* 0 if it was already withdrawn
*/
int gfs2_io_error_i(struct gfs2_sbd *sdp, const char *function, char *file,
unsigned int line)
{
gfs2_lm(sdp,
"fatal: I/O error\n"
" function = %s, file = %s, line = %u\n",
function, file, line);
return gfs2_withdraw(sdp);
}
/*
* gfs2_io_error_bh_i - Flag a buffer I/O error
* @withdraw: withdraw the filesystem
*/
void gfs2_io_error_bh_i(struct gfs2_sbd *sdp, struct buffer_head *bh,
const char *function, char *file, unsigned int line,
bool withdraw)
{
if (gfs2_withdrawn(sdp))
return;
fs_err(sdp, "fatal: I/O error\n"
" block = %llu\n"
" function = %s, file = %s, line = %u\n",
(unsigned long long)bh->b_blocknr, function, file, line);
if (withdraw)
gfs2_withdraw(sdp);
}
| linux-master | fs/gfs2/util.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright 2004-2011 Red Hat, Inc.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/fs.h>
#include <linux/dlm.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/gfs2_ondisk.h>
#include <linux/sched/signal.h>
#include "incore.h"
#include "glock.h"
#include "glops.h"
#include "recovery.h"
#include "util.h"
#include "sys.h"
#include "trace_gfs2.h"
/**
* gfs2_update_stats - Update time based stats
* @s: The stats to update (local or global)
* @index: The index inside @s
* @sample: New data to include
*/
static inline void gfs2_update_stats(struct gfs2_lkstats *s, unsigned index,
s64 sample)
{
/*
* @delta is the difference between the current rtt sample and the
* running average srtt. We add 1/8 of that to the srtt in order to
* update the current srtt estimate. The variance estimate is a bit
* more complicated. We subtract the current variance estimate from
* the abs value of the @delta and add 1/4 of that to the running
* total. That's equivalent to 3/4 of the current variance
* estimate plus 1/4 of the abs of @delta.
*
* Note that the index points at the array entry containing the
* smoothed mean value, and the variance is always in the following
* entry
*
* Reference: TCP/IP Illustrated, vol 2, p. 831,832
* All times are in units of integer nanoseconds. Unlike the TCP/IP
* case, they are not scaled fixed point.
*/
s64 delta = sample - s->stats[index];
s->stats[index] += (delta >> 3);
index++;
s->stats[index] += (s64)(abs(delta) - s->stats[index]) >> 2;
}
/**
* gfs2_update_reply_times - Update locking statistics
* @gl: The glock to update
*
* This assumes that gl->gl_dstamp has been set earlier.
*
* The rtt (lock round trip time) is an estimate of the time
* taken to perform a dlm lock request. We update it on each
* reply from the dlm.
*
* The blocking flag is set on the glock for all dlm requests
* which may potentially block due to lock requests from other nodes.
* DLM requests where the current lock state is exclusive, the
* requested state is null (or unlocked) or where the TRY or
* TRY_1CB flags are set are classified as non-blocking. All
* other DLM requests are counted as (potentially) blocking.
*/
static inline void gfs2_update_reply_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
unsigned index = test_bit(GLF_BLOCKING, &gl->gl_flags) ?
GFS2_LKS_SRTTB : GFS2_LKS_SRTT;
s64 rtt;
preempt_disable();
rtt = ktime_to_ns(ktime_sub(ktime_get_real(), gl->gl_dstamp));
lks = this_cpu_ptr(gl->gl_name.ln_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, index, rtt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], index, rtt); /* Global */
preempt_enable();
trace_gfs2_glock_lock_time(gl, rtt);
}
/**
* gfs2_update_request_times - Update locking statistics
* @gl: The glock to update
*
* The irt (lock inter-request times) measures the average time
* between requests to the dlm. It is updated immediately before
* each dlm call.
*/
static inline void gfs2_update_request_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
ktime_t dstamp;
s64 irt;
preempt_disable();
dstamp = gl->gl_dstamp;
gl->gl_dstamp = ktime_get_real();
irt = ktime_to_ns(ktime_sub(gl->gl_dstamp, dstamp));
lks = this_cpu_ptr(gl->gl_name.ln_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, GFS2_LKS_SIRT, irt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], GFS2_LKS_SIRT, irt); /* Global */
preempt_enable();
}
static void gdlm_ast(void *arg)
{
struct gfs2_glock *gl = arg;
unsigned ret = gl->gl_state;
gfs2_update_reply_times(gl);
BUG_ON(gl->gl_lksb.sb_flags & DLM_SBF_DEMOTED);
if ((gl->gl_lksb.sb_flags & DLM_SBF_VALNOTVALID) && gl->gl_lksb.sb_lvbptr)
memset(gl->gl_lksb.sb_lvbptr, 0, GDLM_LVB_SIZE);
switch (gl->gl_lksb.sb_status) {
case -DLM_EUNLOCK: /* Unlocked, so glock can be freed */
if (gl->gl_ops->go_free)
gl->gl_ops->go_free(gl);
gfs2_glock_free(gl);
return;
case -DLM_ECANCEL: /* Cancel while getting lock */
ret |= LM_OUT_CANCELED;
goto out;
case -EAGAIN: /* Try lock fails */
case -EDEADLK: /* Deadlock detected */
goto out;
case -ETIMEDOUT: /* Canceled due to timeout */
ret |= LM_OUT_ERROR;
goto out;
case 0: /* Success */
break;
default: /* Something unexpected */
BUG();
}
ret = gl->gl_req;
if (gl->gl_lksb.sb_flags & DLM_SBF_ALTMODE) {
if (gl->gl_req == LM_ST_SHARED)
ret = LM_ST_DEFERRED;
else if (gl->gl_req == LM_ST_DEFERRED)
ret = LM_ST_SHARED;
else
BUG();
}
set_bit(GLF_INITIAL, &gl->gl_flags);
gfs2_glock_complete(gl, ret);
return;
out:
if (!test_bit(GLF_INITIAL, &gl->gl_flags))
gl->gl_lksb.sb_lkid = 0;
gfs2_glock_complete(gl, ret);
}
static void gdlm_bast(void *arg, int mode)
{
struct gfs2_glock *gl = arg;
switch (mode) {
case DLM_LOCK_EX:
gfs2_glock_cb(gl, LM_ST_UNLOCKED);
break;
case DLM_LOCK_CW:
gfs2_glock_cb(gl, LM_ST_DEFERRED);
break;
case DLM_LOCK_PR:
gfs2_glock_cb(gl, LM_ST_SHARED);
break;
default:
fs_err(gl->gl_name.ln_sbd, "unknown bast mode %d\n", mode);
BUG();
}
}
/* convert gfs lock-state to dlm lock-mode */
static int make_mode(struct gfs2_sbd *sdp, const unsigned int lmstate)
{
switch (lmstate) {
case LM_ST_UNLOCKED:
return DLM_LOCK_NL;
case LM_ST_EXCLUSIVE:
return DLM_LOCK_EX;
case LM_ST_DEFERRED:
return DLM_LOCK_CW;
case LM_ST_SHARED:
return DLM_LOCK_PR;
}
fs_err(sdp, "unknown LM state %d\n", lmstate);
BUG();
return -1;
}
static u32 make_flags(struct gfs2_glock *gl, const unsigned int gfs_flags,
const int req)
{
u32 lkf = 0;
if (gl->gl_lksb.sb_lvbptr)
lkf |= DLM_LKF_VALBLK;
if (gfs_flags & LM_FLAG_TRY)
lkf |= DLM_LKF_NOQUEUE;
if (gfs_flags & LM_FLAG_TRY_1CB) {
lkf |= DLM_LKF_NOQUEUE;
lkf |= DLM_LKF_NOQUEUEBAST;
}
if (gfs_flags & LM_FLAG_ANY) {
if (req == DLM_LOCK_PR)
lkf |= DLM_LKF_ALTCW;
else if (req == DLM_LOCK_CW)
lkf |= DLM_LKF_ALTPR;
else
BUG();
}
if (gl->gl_lksb.sb_lkid != 0) {
lkf |= DLM_LKF_CONVERT;
if (test_bit(GLF_BLOCKING, &gl->gl_flags))
lkf |= DLM_LKF_QUECVT;
}
return lkf;
}
static void gfs2_reverse_hex(char *c, u64 value)
{
*c = '0';
while (value) {
*c-- = hex_asc[value & 0x0f];
value >>= 4;
}
}
static int gdlm_lock(struct gfs2_glock *gl, unsigned int req_state,
unsigned int flags)
{
struct lm_lockstruct *ls = &gl->gl_name.ln_sbd->sd_lockstruct;
int req;
u32 lkf;
char strname[GDLM_STRNAME_BYTES] = "";
int error;
req = make_mode(gl->gl_name.ln_sbd, req_state);
lkf = make_flags(gl, flags, req);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
if (gl->gl_lksb.sb_lkid) {
gfs2_update_request_times(gl);
} else {
memset(strname, ' ', GDLM_STRNAME_BYTES - 1);
strname[GDLM_STRNAME_BYTES - 1] = '\0';
gfs2_reverse_hex(strname + 7, gl->gl_name.ln_type);
gfs2_reverse_hex(strname + 23, gl->gl_name.ln_number);
gl->gl_dstamp = ktime_get_real();
}
/*
* Submit the actual lock request.
*/
again:
error = dlm_lock(ls->ls_dlm, req, &gl->gl_lksb, lkf, strname,
GDLM_STRNAME_BYTES - 1, 0, gdlm_ast, gl, gdlm_bast);
if (error == -EBUSY) {
msleep(20);
goto again;
}
return error;
}
static void gdlm_put_lock(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (gl->gl_lksb.sb_lkid == 0)
goto out_free;
clear_bit(GLF_BLOCKING, &gl->gl_flags);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_update_request_times(gl);
/* don't want to call dlm if we've unmounted the lock protocol */
if (test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
goto out_free;
/* don't want to skip dlm_unlock writing the lvb when lock has one */
if (test_bit(SDF_SKIP_DLM_UNLOCK, &sdp->sd_flags) &&
!gl->gl_lksb.sb_lvbptr)
goto out_free;
again:
error = dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_VALBLK,
NULL, gl);
if (error == -EBUSY) {
msleep(20);
goto again;
}
if (error) {
fs_err(sdp, "gdlm_unlock %x,%llx err=%d\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number, error);
}
return;
out_free:
gfs2_glock_free(gl);
}
static void gdlm_cancel(struct gfs2_glock *gl)
{
struct lm_lockstruct *ls = &gl->gl_name.ln_sbd->sd_lockstruct;
dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_CANCEL, NULL, gl);
}
/*
* dlm/gfs2 recovery coordination using dlm_recover callbacks
*
* 0. gfs2 checks for another cluster node withdraw, needing journal replay
* 1. dlm_controld sees lockspace members change
* 2. dlm_controld blocks dlm-kernel locking activity
* 3. dlm_controld within dlm-kernel notifies gfs2 (recover_prep)
* 4. dlm_controld starts and finishes its own user level recovery
* 5. dlm_controld starts dlm-kernel dlm_recoverd to do kernel recovery
* 6. dlm_recoverd notifies gfs2 of failed nodes (recover_slot)
* 7. dlm_recoverd does its own lock recovery
* 8. dlm_recoverd unblocks dlm-kernel locking activity
* 9. dlm_recoverd notifies gfs2 when done (recover_done with new generation)
* 10. gfs2_control updates control_lock lvb with new generation and jid bits
* 11. gfs2_control enqueues journals for gfs2_recover to recover (maybe none)
* 12. gfs2_recover dequeues and recovers journals of failed nodes
* 13. gfs2_recover provides recovery results to gfs2_control (recovery_result)
* 14. gfs2_control updates control_lock lvb jid bits for recovered journals
* 15. gfs2_control unblocks normal locking when all journals are recovered
*
* - failures during recovery
*
* recover_prep() may set BLOCK_LOCKS (step 3) again before gfs2_control
* clears BLOCK_LOCKS (step 15), e.g. another node fails while still
* recovering for a prior failure. gfs2_control needs a way to detect
* this so it can leave BLOCK_LOCKS set in step 15. This is managed using
* the recover_block and recover_start values.
*
* recover_done() provides a new lockspace generation number each time it
* is called (step 9). This generation number is saved as recover_start.
* When recover_prep() is called, it sets BLOCK_LOCKS and sets
* recover_block = recover_start. So, while recover_block is equal to
* recover_start, BLOCK_LOCKS should remain set. (recover_spin must
* be held around the BLOCK_LOCKS/recover_block/recover_start logic.)
*
* - more specific gfs2 steps in sequence above
*
* 3. recover_prep sets BLOCK_LOCKS and sets recover_block = recover_start
* 6. recover_slot records any failed jids (maybe none)
* 9. recover_done sets recover_start = new generation number
* 10. gfs2_control sets control_lock lvb = new gen + bits for failed jids
* 12. gfs2_recover does journal recoveries for failed jids identified above
* 14. gfs2_control clears control_lock lvb bits for recovered jids
* 15. gfs2_control checks if recover_block == recover_start (step 3 occured
* again) then do nothing, otherwise if recover_start > recover_block
* then clear BLOCK_LOCKS.
*
* - parallel recovery steps across all nodes
*
* All nodes attempt to update the control_lock lvb with the new generation
* number and jid bits, but only the first to get the control_lock EX will
* do so; others will see that it's already done (lvb already contains new
* generation number.)
*
* . All nodes get the same recover_prep/recover_slot/recover_done callbacks
* . All nodes attempt to set control_lock lvb gen + bits for the new gen
* . One node gets control_lock first and writes the lvb, others see it's done
* . All nodes attempt to recover jids for which they see control_lock bits set
* . One node succeeds for a jid, and that one clears the jid bit in the lvb
* . All nodes will eventually see all lvb bits clear and unblock locks
*
* - is there a problem with clearing an lvb bit that should be set
* and missing a journal recovery?
*
* 1. jid fails
* 2. lvb bit set for step 1
* 3. jid recovered for step 1
* 4. jid taken again (new mount)
* 5. jid fails (for step 4)
* 6. lvb bit set for step 5 (will already be set)
* 7. lvb bit cleared for step 3
*
* This is not a problem because the failure in step 5 does not
* require recovery, because the mount in step 4 could not have
* progressed far enough to unblock locks and access the fs. The
* control_mount() function waits for all recoveries to be complete
* for the latest lockspace generation before ever unblocking locks
* and returning. The mount in step 4 waits until the recovery in
* step 1 is done.
*
* - special case of first mounter: first node to mount the fs
*
* The first node to mount a gfs2 fs needs to check all the journals
* and recover any that need recovery before other nodes are allowed
* to mount the fs. (Others may begin mounting, but they must wait
* for the first mounter to be done before taking locks on the fs
* or accessing the fs.) This has two parts:
*
* 1. The mounted_lock tells a node it's the first to mount the fs.
* Each node holds the mounted_lock in PR while it's mounted.
* Each node tries to acquire the mounted_lock in EX when it mounts.
* If a node is granted the mounted_lock EX it means there are no
* other mounted nodes (no PR locks exist), and it is the first mounter.
* The mounted_lock is demoted to PR when first recovery is done, so
* others will fail to get an EX lock, but will get a PR lock.
*
* 2. The control_lock blocks others in control_mount() while the first
* mounter is doing first mount recovery of all journals.
* A mounting node needs to acquire control_lock in EX mode before
* it can proceed. The first mounter holds control_lock in EX while doing
* the first mount recovery, blocking mounts from other nodes, then demotes
* control_lock to NL when it's done (others_may_mount/first_done),
* allowing other nodes to continue mounting.
*
* first mounter:
* control_lock EX/NOQUEUE success
* mounted_lock EX/NOQUEUE success (no other PR, so no other mounters)
* set first=1
* do first mounter recovery
* mounted_lock EX->PR
* control_lock EX->NL, write lvb generation
*
* other mounter:
* control_lock EX/NOQUEUE success (if fail -EAGAIN, retry)
* mounted_lock EX/NOQUEUE fail -EAGAIN (expected due to other mounters PR)
* mounted_lock PR/NOQUEUE success
* read lvb generation
* control_lock EX->NL
* set first=0
*
* - mount during recovery
*
* If a node mounts while others are doing recovery (not first mounter),
* the mounting node will get its initial recover_done() callback without
* having seen any previous failures/callbacks.
*
* It must wait for all recoveries preceding its mount to be finished
* before it unblocks locks. It does this by repeating the "other mounter"
* steps above until the lvb generation number is >= its mount generation
* number (from initial recover_done) and all lvb bits are clear.
*
* - control_lock lvb format
*
* 4 bytes generation number: the latest dlm lockspace generation number
* from recover_done callback. Indicates the jid bitmap has been updated
* to reflect all slot failures through that generation.
* 4 bytes unused.
* GDLM_LVB_SIZE-8 bytes of jid bit map. If bit N is set, it indicates
* that jid N needs recovery.
*/
#define JID_BITMAP_OFFSET 8 /* 4 byte generation number + 4 byte unused */
static void control_lvb_read(struct lm_lockstruct *ls, uint32_t *lvb_gen,
char *lvb_bits)
{
__le32 gen;
memcpy(lvb_bits, ls->ls_control_lvb, GDLM_LVB_SIZE);
memcpy(&gen, lvb_bits, sizeof(__le32));
*lvb_gen = le32_to_cpu(gen);
}
static void control_lvb_write(struct lm_lockstruct *ls, uint32_t lvb_gen,
char *lvb_bits)
{
__le32 gen;
memcpy(ls->ls_control_lvb, lvb_bits, GDLM_LVB_SIZE);
gen = cpu_to_le32(lvb_gen);
memcpy(ls->ls_control_lvb, &gen, sizeof(__le32));
}
static int all_jid_bits_clear(char *lvb)
{
return !memchr_inv(lvb + JID_BITMAP_OFFSET, 0,
GDLM_LVB_SIZE - JID_BITMAP_OFFSET);
}
static void sync_wait_cb(void *arg)
{
struct lm_lockstruct *ls = arg;
complete(&ls->ls_sync_wait);
}
static int sync_unlock(struct gfs2_sbd *sdp, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
error = dlm_unlock(ls->ls_dlm, lksb->sb_lkid, 0, lksb, ls);
if (error) {
fs_err(sdp, "%s lkid %x error %d\n",
name, lksb->sb_lkid, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
if (lksb->sb_status != -DLM_EUNLOCK) {
fs_err(sdp, "%s lkid %x status %d\n",
name, lksb->sb_lkid, lksb->sb_status);
return -1;
}
return 0;
}
static int sync_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags,
unsigned int num, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char strname[GDLM_STRNAME_BYTES];
int error, status;
memset(strname, 0, GDLM_STRNAME_BYTES);
snprintf(strname, GDLM_STRNAME_BYTES, "%8x%16x", LM_TYPE_NONDISK, num);
error = dlm_lock(ls->ls_dlm, mode, lksb, flags,
strname, GDLM_STRNAME_BYTES - 1,
0, sync_wait_cb, ls, NULL);
if (error) {
fs_err(sdp, "%s lkid %x flags %x mode %d error %d\n",
name, lksb->sb_lkid, flags, mode, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
status = lksb->sb_status;
if (status && status != -EAGAIN) {
fs_err(sdp, "%s lkid %x flags %x mode %d status %d\n",
name, lksb->sb_lkid, flags, mode, status);
}
return status;
}
static int mounted_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_mounted_lksb, "mounted_lock");
}
static int mounted_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_MOUNTED_LOCK,
&ls->ls_mounted_lksb, "mounted_lock");
}
static int control_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_control_lksb, "control_lock");
}
static int control_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_CONTROL_LOCK,
&ls->ls_control_lksb, "control_lock");
}
/**
* remote_withdraw - react to a node withdrawing from the file system
* @sdp: The superblock
*/
static void remote_withdraw(struct gfs2_sbd *sdp)
{
struct gfs2_jdesc *jd;
int ret = 0, count = 0;
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
if (jd->jd_jid == sdp->sd_lockstruct.ls_jid)
continue;
ret = gfs2_recover_journal(jd, true);
if (ret)
break;
count++;
}
/* Now drop the additional reference we acquired */
fs_err(sdp, "Journals checked: %d, ret = %d.\n", count, ret);
}
static void gfs2_control_func(struct work_struct *work)
{
struct gfs2_sbd *sdp = container_of(work, struct gfs2_sbd, sd_control_work.work);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t block_gen, start_gen, lvb_gen, flags;
int recover_set = 0;
int write_lvb = 0;
int recover_size;
int i, error;
/* First check for other nodes that may have done a withdraw. */
if (test_bit(SDF_REMOTE_WITHDRAW, &sdp->sd_flags)) {
remote_withdraw(sdp);
clear_bit(SDF_REMOTE_WITHDRAW, &sdp->sd_flags);
return;
}
spin_lock(&ls->ls_recover_spin);
/*
* No MOUNT_DONE means we're still mounting; control_mount()
* will set this flag, after which this thread will take over
* all further clearing of BLOCK_LOCKS.
*
* FIRST_MOUNT means this node is doing first mounter recovery,
* for which recovery control is handled by
* control_mount()/control_first_done(), not this thread.
*/
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
spin_unlock(&ls->ls_recover_spin);
/*
* Equal block_gen and start_gen implies we are between
* recover_prep and recover_done callbacks, which means
* dlm recovery is in progress and dlm locking is blocked.
* There's no point trying to do any work until recover_done.
*/
if (block_gen == start_gen)
return;
/*
* Propagate recover_submit[] and recover_result[] to lvb:
* dlm_recoverd adds to recover_submit[] jids needing recovery
* gfs2_recover adds to recover_result[] journal recovery results
*
* set lvb bit for jids in recover_submit[] if the lvb has not
* yet been updated for the generation of the failure
*
* clear lvb bit for jids in recover_result[] if the result of
* the journal recovery is SUCCESS
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control lock EX error %d\n", error);
return;
}
control_lvb_read(ls, &lvb_gen, ls->ls_lvb_bits);
spin_lock(&ls->ls_recover_spin);
if (block_gen != ls->ls_recover_block ||
start_gen != ls->ls_recover_start) {
fs_info(sdp, "recover generation %u block1 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
return;
}
recover_size = ls->ls_recover_size;
if (lvb_gen <= start_gen) {
/*
* Clear lvb bits for jids we've successfully recovered.
* Because all nodes attempt to recover failed journals,
* a journal can be recovered multiple times successfully
* in succession. Only the first will really do recovery,
* the others find it clean, but still report a successful
* recovery. So, another node may have already recovered
* the jid and cleared the lvb bit for it.
*/
for (i = 0; i < recover_size; i++) {
if (ls->ls_recover_result[i] != LM_RD_SUCCESS)
continue;
ls->ls_recover_result[i] = 0;
if (!test_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET))
continue;
__clear_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET);
write_lvb = 1;
}
}
if (lvb_gen == start_gen) {
/*
* Failed slots before start_gen are already set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < lvb_gen)
ls->ls_recover_submit[i] = 0;
}
} else if (lvb_gen < start_gen) {
/*
* Failed slots before start_gen are not yet set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < start_gen) {
ls->ls_recover_submit[i] = 0;
__set_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET);
}
}
/* even if there are no bits to set, we need to write the
latest generation to the lvb */
write_lvb = 1;
} else {
/*
* we should be getting a recover_done() for lvb_gen soon
*/
}
spin_unlock(&ls->ls_recover_spin);
if (write_lvb) {
control_lvb_write(ls, start_gen, ls->ls_lvb_bits);
flags = DLM_LKF_CONVERT | DLM_LKF_VALBLK;
} else {
flags = DLM_LKF_CONVERT;
}
error = control_lock(sdp, DLM_LOCK_NL, flags);
if (error) {
fs_err(sdp, "control lock NL error %d\n", error);
return;
}
/*
* Everyone will see jid bits set in the lvb, run gfs2_recover_set(),
* and clear a jid bit in the lvb if the recovery is a success.
* Eventually all journals will be recovered, all jid bits will
* be cleared in the lvb, and everyone will clear BLOCK_LOCKS.
*/
for (i = 0; i < recover_size; i++) {
if (test_bit_le(i, ls->ls_lvb_bits + JID_BITMAP_OFFSET)) {
fs_info(sdp, "recover generation %u jid %d\n",
start_gen, i);
gfs2_recover_set(sdp, i);
recover_set++;
}
}
if (recover_set)
return;
/*
* No more jid bits set in lvb, all recovery is done, unblock locks
* (unless a new recover_prep callback has occured blocking locks
* again while working above)
*/
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_block == block_gen &&
ls->ls_recover_start == start_gen) {
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "recover generation %u done\n", start_gen);
gfs2_glock_thaw(sdp);
} else {
fs_info(sdp, "recover generation %u block2 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
}
}
static int control_mount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t start_gen, block_gen, mount_gen, lvb_gen;
int mounted_mode;
int retries = 0;
int error;
memset(&ls->ls_mounted_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lvb, 0, GDLM_LVB_SIZE);
ls->ls_control_lksb.sb_lvbptr = ls->ls_control_lvb;
init_completion(&ls->ls_sync_wait);
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control_mount control_lock NL error %d\n", error);
return error;
}
error = mounted_lock(sdp, DLM_LOCK_NL, 0);
if (error) {
fs_err(sdp, "control_mount mounted_lock NL error %d\n", error);
control_unlock(sdp);
return error;
}
mounted_mode = DLM_LOCK_NL;
restart:
if (retries++ && signal_pending(current)) {
error = -EINTR;
goto fail;
}
/*
* We always start with both locks in NL. control_lock is
* demoted to NL below so we don't need to do it here.
*/
if (mounted_mode != DLM_LOCK_NL) {
error = mounted_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
mounted_mode = DLM_LOCK_NL;
}
/*
* Other nodes need to do some work in dlm recovery and gfs2_control
* before the recover_done and control_lock will be ready for us below.
* A delay here is not required but often avoids having to retry.
*/
msleep_interruptible(500);
/*
* Acquire control_lock in EX and mounted_lock in either EX or PR.
* control_lock lvb keeps track of any pending journal recoveries.
* mounted_lock indicates if any other nodes have the fs mounted.
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE|DLM_LKF_VALBLK);
if (error == -EAGAIN) {
goto restart;
} else if (error) {
fs_err(sdp, "control_mount control_lock EX error %d\n", error);
goto fail;
}
/**
* If we're a spectator, we don't want to take the lock in EX because
* we cannot do the first-mount responsibility it implies: recovery.
*/
if (sdp->sd_args.ar_spectator)
goto locks_done;
error = mounted_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_EX;
goto locks_done;
} else if (error != -EAGAIN) {
fs_err(sdp, "control_mount mounted_lock EX error %d\n", error);
goto fail;
}
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_PR;
goto locks_done;
} else {
/* not even -EAGAIN should happen here */
fs_err(sdp, "control_mount mounted_lock PR error %d\n", error);
goto fail;
}
locks_done:
/*
* If we got both locks above in EX, then we're the first mounter.
* If not, then we need to wait for the control_lock lvb to be
* updated by other mounted nodes to reflect our mount generation.
*
* In simple first mounter cases, first mounter will see zero lvb_gen,
* but in cases where all existing nodes leave/fail before mounting
* nodes finish control_mount, then all nodes will be mounting and
* lvb_gen will be non-zero.
*/
control_lvb_read(ls, &lvb_gen, ls->ls_lvb_bits);
if (lvb_gen == 0xFFFFFFFF) {
/* special value to force mount attempts to fail */
fs_err(sdp, "control_mount control_lock disabled\n");
error = -EINVAL;
goto fail;
}
if (mounted_mode == DLM_LOCK_EX) {
/* first mounter, keep both EX while doing first recovery */
spin_lock(&ls->ls_recover_spin);
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "first mounter control generation %u\n", lvb_gen);
return 0;
}
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
/*
* We are not first mounter, now we need to wait for the control_lock
* lvb generation to be >= the generation from our first recover_done
* and all lvb bits to be clear (no pending journal recoveries.)
*/
if (!all_jid_bits_clear(ls->ls_lvb_bits)) {
/* journals need recovery, wait until all are clear */
fs_info(sdp, "control_mount wait for journal recovery\n");
goto restart;
}
spin_lock(&ls->ls_recover_spin);
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
mount_gen = ls->ls_recover_mount;
if (lvb_gen < mount_gen) {
/* wait for mounted nodes to update control_lock lvb to our
generation, which might include new recovery bits set */
if (sdp->sd_args.ar_spectator) {
fs_info(sdp, "Recovery is required. Waiting for a "
"non-spectator to mount.\n");
msleep_interruptible(1000);
} else {
fs_info(sdp, "control_mount wait1 block %u start %u "
"mount %u lvb %u flags %lx\n", block_gen,
start_gen, mount_gen, lvb_gen,
ls->ls_recover_flags);
}
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (lvb_gen != start_gen) {
/* wait for mounted nodes to update control_lock lvb to the
latest recovery generation */
fs_info(sdp, "control_mount wait2 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (block_gen == start_gen) {
/* dlm recovery in progress, wait for it to finish */
fs_info(sdp, "control_mount wait3 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
return 0;
fail:
mounted_unlock(sdp);
control_unlock(sdp);
return error;
}
static int control_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t start_gen, block_gen;
int error;
restart:
spin_lock(&ls->ls_recover_spin);
start_gen = ls->ls_recover_start;
block_gen = ls->ls_recover_block;
if (test_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags) ||
!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
/* sanity check, should not happen */
fs_err(sdp, "control_first_done start %u block %u flags %lx\n",
start_gen, block_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
control_unlock(sdp);
return -1;
}
if (start_gen == block_gen) {
/*
* Wait for the end of a dlm recovery cycle to switch from
* first mounter recovery. We can ignore any recover_slot
* callbacks between the recover_prep and next recover_done
* because we are still the first mounter and any failed nodes
* have not fully mounted, so they don't need recovery.
*/
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "control_first_done wait gen %u\n", start_gen);
wait_on_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY,
TASK_UNINTERRUPTIBLE);
goto restart;
}
clear_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
memset(ls->ls_lvb_bits, 0, GDLM_LVB_SIZE);
control_lvb_write(ls, start_gen, ls->ls_lvb_bits);
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT);
if (error)
fs_err(sdp, "control_first_done mounted PR error %d\n", error);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error)
fs_err(sdp, "control_first_done control NL error %d\n", error);
return error;
}
/*
* Expand static jid arrays if necessary (by increments of RECOVER_SIZE_INC)
* to accommodate the largest slot number. (NB dlm slot numbers start at 1,
* gfs2 jids start at 0, so jid = slot - 1)
*/
#define RECOVER_SIZE_INC 16
static int set_recover_size(struct gfs2_sbd *sdp, struct dlm_slot *slots,
int num_slots)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t *submit = NULL;
uint32_t *result = NULL;
uint32_t old_size, new_size;
int i, max_jid;
if (!ls->ls_lvb_bits) {
ls->ls_lvb_bits = kzalloc(GDLM_LVB_SIZE, GFP_NOFS);
if (!ls->ls_lvb_bits)
return -ENOMEM;
}
max_jid = 0;
for (i = 0; i < num_slots; i++) {
if (max_jid < slots[i].slot - 1)
max_jid = slots[i].slot - 1;
}
old_size = ls->ls_recover_size;
new_size = old_size;
while (new_size < max_jid + 1)
new_size += RECOVER_SIZE_INC;
if (new_size == old_size)
return 0;
submit = kcalloc(new_size, sizeof(uint32_t), GFP_NOFS);
result = kcalloc(new_size, sizeof(uint32_t), GFP_NOFS);
if (!submit || !result) {
kfree(submit);
kfree(result);
return -ENOMEM;
}
spin_lock(&ls->ls_recover_spin);
memcpy(submit, ls->ls_recover_submit, old_size * sizeof(uint32_t));
memcpy(result, ls->ls_recover_result, old_size * sizeof(uint32_t));
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = submit;
ls->ls_recover_result = result;
ls->ls_recover_size = new_size;
spin_unlock(&ls->ls_recover_spin);
return 0;
}
static void free_recover_size(struct lm_lockstruct *ls)
{
kfree(ls->ls_lvb_bits);
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
ls->ls_recover_size = 0;
ls->ls_lvb_bits = NULL;
}
/* dlm calls before it does lock recovery */
static void gdlm_recover_prep(void *arg)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (gfs2_withdrawn(sdp)) {
fs_err(sdp, "recover_prep ignored due to withdraw.\n");
return;
}
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_block = ls->ls_recover_start;
set_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_prep has been completed on all lockspace members;
identifies slot/jid of failed member */
static void gdlm_recover_slot(void *arg, struct dlm_slot *slot)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int jid = slot->slot - 1;
if (gfs2_withdrawn(sdp)) {
fs_err(sdp, "recover_slot jid %d ignored due to withdraw.\n",
jid);
return;
}
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recover_slot jid %d gen %u short size %d\n",
jid, ls->ls_recover_block, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_submit[jid]) {
fs_info(sdp, "recover_slot jid %d gen %u prev %u\n",
jid, ls->ls_recover_block, ls->ls_recover_submit[jid]);
}
ls->ls_recover_submit[jid] = ls->ls_recover_block;
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_slot and after it completes lock recovery */
static void gdlm_recover_done(void *arg, struct dlm_slot *slots, int num_slots,
int our_slot, uint32_t generation)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (gfs2_withdrawn(sdp)) {
fs_err(sdp, "recover_done ignored due to withdraw.\n");
return;
}
/* ensure the ls jid arrays are large enough */
set_recover_size(sdp, slots, num_slots);
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_start = generation;
if (!ls->ls_recover_mount) {
ls->ls_recover_mount = generation;
ls->ls_jid = our_slot - 1;
}
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work, 0);
clear_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
smp_mb__after_atomic();
wake_up_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY);
spin_unlock(&ls->ls_recover_spin);
}
/* gfs2_recover thread has a journal recovery result */
static void gdlm_recovery_result(struct gfs2_sbd *sdp, unsigned int jid,
unsigned int result)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (gfs2_withdrawn(sdp)) {
fs_err(sdp, "recovery_result jid %d ignored due to withdraw.\n",
jid);
return;
}
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
/* don't care about the recovery of own journal during mount */
if (jid == ls->ls_jid)
return;
spin_lock(&ls->ls_recover_spin);
if (test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recovery_result jid %d short size %d\n",
jid, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
fs_info(sdp, "recover jid %d result %s\n", jid,
result == LM_RD_GAVEUP ? "busy" : "success");
ls->ls_recover_result[jid] = result;
/* GAVEUP means another node is recovering the journal; delay our
next attempt to recover it, to give the other node a chance to
finish before trying again */
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work,
result == LM_RD_GAVEUP ? HZ : 0);
spin_unlock(&ls->ls_recover_spin);
}
static const struct dlm_lockspace_ops gdlm_lockspace_ops = {
.recover_prep = gdlm_recover_prep,
.recover_slot = gdlm_recover_slot,
.recover_done = gdlm_recover_done,
};
static int gdlm_mount(struct gfs2_sbd *sdp, const char *table)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char cluster[GFS2_LOCKNAME_LEN];
const char *fsname;
uint32_t flags;
int error, ops_result;
/*
* initialize everything
*/
INIT_DELAYED_WORK(&sdp->sd_control_work, gfs2_control_func);
spin_lock_init(&ls->ls_recover_spin);
ls->ls_recover_flags = 0;
ls->ls_recover_mount = 0;
ls->ls_recover_start = 0;
ls->ls_recover_block = 0;
ls->ls_recover_size = 0;
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
ls->ls_lvb_bits = NULL;
error = set_recover_size(sdp, NULL, 0);
if (error)
goto fail;
/*
* prepare dlm_new_lockspace args
*/
fsname = strchr(table, ':');
if (!fsname) {
fs_info(sdp, "no fsname found\n");
error = -EINVAL;
goto fail_free;
}
memset(cluster, 0, sizeof(cluster));
memcpy(cluster, table, strlen(table) - strlen(fsname));
fsname++;
flags = DLM_LSFL_NEWEXCL;
/*
* create/join lockspace
*/
error = dlm_new_lockspace(fsname, cluster, flags, GDLM_LVB_SIZE,
&gdlm_lockspace_ops, sdp, &ops_result,
&ls->ls_dlm);
if (error) {
fs_err(sdp, "dlm_new_lockspace error %d\n", error);
goto fail_free;
}
if (ops_result < 0) {
/*
* dlm does not support ops callbacks,
* old dlm_controld/gfs_controld are used, try without ops.
*/
fs_info(sdp, "dlm lockspace ops not used\n");
free_recover_size(ls);
set_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags);
return 0;
}
if (!test_bit(SDF_NOJOURNALID, &sdp->sd_flags)) {
fs_err(sdp, "dlm lockspace ops disallow jid preset\n");
error = -EINVAL;
goto fail_release;
}
/*
* control_mount() uses control_lock to determine first mounter,
* and for later mounts, waits for any recoveries to be cleared.
*/
error = control_mount(sdp);
if (error) {
fs_err(sdp, "mount control error %d\n", error);
goto fail_release;
}
ls->ls_first = !!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
clear_bit(SDF_NOJOURNALID, &sdp->sd_flags);
smp_mb__after_atomic();
wake_up_bit(&sdp->sd_flags, SDF_NOJOURNALID);
return 0;
fail_release:
dlm_release_lockspace(ls->ls_dlm, 2);
fail_free:
free_recover_size(ls);
fail:
return error;
}
static void gdlm_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
error = control_first_done(sdp);
if (error)
fs_err(sdp, "mount first_done error %d\n", error);
}
static void gdlm_unmount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
goto release;
/* wait for gfs2_control_wq to be done with this mount */
spin_lock(&ls->ls_recover_spin);
set_bit(DFL_UNMOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
flush_delayed_work(&sdp->sd_control_work);
/* mounted_lock and control_lock will be purged in dlm recovery */
release:
if (ls->ls_dlm) {
dlm_release_lockspace(ls->ls_dlm, 2);
ls->ls_dlm = NULL;
}
free_recover_size(ls);
}
static const match_table_t dlm_tokens = {
{ Opt_jid, "jid=%d"},
{ Opt_id, "id=%d"},
{ Opt_first, "first=%d"},
{ Opt_nodir, "nodir=%d"},
{ Opt_err, NULL },
};
const struct lm_lockops gfs2_dlm_ops = {
.lm_proto_name = "lock_dlm",
.lm_mount = gdlm_mount,
.lm_first_done = gdlm_first_done,
.lm_recovery_result = gdlm_recovery_result,
.lm_unmount = gdlm_unmount,
.lm_put_lock = gdlm_put_lock,
.lm_lock = gdlm_lock,
.lm_cancel = gdlm_cancel,
.lm_tokens = &dlm_tokens,
};
| linux-master | fs/gfs2/lock_dlm.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/buffer_head.h>
#include <linux/delay.h>
#include <linux/sort.h>
#include <linux/hash.h>
#include <linux/jhash.h>
#include <linux/kallsyms.h>
#include <linux/gfs2_ondisk.h>
#include <linux/list.h>
#include <linux/wait.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/workqueue.h>
#include <linux/jiffies.h>
#include <linux/rcupdate.h>
#include <linux/rculist_bl.h>
#include <linux/bit_spinlock.h>
#include <linux/percpu.h>
#include <linux/list_sort.h>
#include <linux/lockref.h>
#include <linux/rhashtable.h>
#include <linux/pid_namespace.h>
#include <linux/fdtable.h>
#include <linux/file.h>
#include "gfs2.h"
#include "incore.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "lops.h"
#include "meta_io.h"
#include "quota.h"
#include "super.h"
#include "util.h"
#include "bmap.h"
#define CREATE_TRACE_POINTS
#include "trace_gfs2.h"
struct gfs2_glock_iter {
struct gfs2_sbd *sdp; /* incore superblock */
struct rhashtable_iter hti; /* rhashtable iterator */
struct gfs2_glock *gl; /* current glock struct */
loff_t last_pos; /* last position */
};
typedef void (*glock_examiner) (struct gfs2_glock * gl);
static void do_xmote(struct gfs2_glock *gl, struct gfs2_holder *gh, unsigned int target);
static void __gfs2_glock_dq(struct gfs2_holder *gh);
static void handle_callback(struct gfs2_glock *gl, unsigned int state,
unsigned long delay, bool remote);
static struct dentry *gfs2_root;
static struct workqueue_struct *glock_workqueue;
static LIST_HEAD(lru_list);
static atomic_t lru_count = ATOMIC_INIT(0);
static DEFINE_SPINLOCK(lru_lock);
#define GFS2_GL_HASH_SHIFT 15
#define GFS2_GL_HASH_SIZE BIT(GFS2_GL_HASH_SHIFT)
static const struct rhashtable_params ht_parms = {
.nelem_hint = GFS2_GL_HASH_SIZE * 3 / 4,
.key_len = offsetofend(struct lm_lockname, ln_type),
.key_offset = offsetof(struct gfs2_glock, gl_name),
.head_offset = offsetof(struct gfs2_glock, gl_node),
};
static struct rhashtable gl_hash_table;
#define GLOCK_WAIT_TABLE_BITS 12
#define GLOCK_WAIT_TABLE_SIZE (1 << GLOCK_WAIT_TABLE_BITS)
static wait_queue_head_t glock_wait_table[GLOCK_WAIT_TABLE_SIZE] __cacheline_aligned;
struct wait_glock_queue {
struct lm_lockname *name;
wait_queue_entry_t wait;
};
static int glock_wake_function(wait_queue_entry_t *wait, unsigned int mode,
int sync, void *key)
{
struct wait_glock_queue *wait_glock =
container_of(wait, struct wait_glock_queue, wait);
struct lm_lockname *wait_name = wait_glock->name;
struct lm_lockname *wake_name = key;
if (wake_name->ln_sbd != wait_name->ln_sbd ||
wake_name->ln_number != wait_name->ln_number ||
wake_name->ln_type != wait_name->ln_type)
return 0;
return autoremove_wake_function(wait, mode, sync, key);
}
static wait_queue_head_t *glock_waitqueue(struct lm_lockname *name)
{
u32 hash = jhash2((u32 *)name, ht_parms.key_len / 4, 0);
return glock_wait_table + hash_32(hash, GLOCK_WAIT_TABLE_BITS);
}
/**
* wake_up_glock - Wake up waiters on a glock
* @gl: the glock
*/
static void wake_up_glock(struct gfs2_glock *gl)
{
wait_queue_head_t *wq = glock_waitqueue(&gl->gl_name);
if (waitqueue_active(wq))
__wake_up(wq, TASK_NORMAL, 1, &gl->gl_name);
}
static void gfs2_glock_dealloc(struct rcu_head *rcu)
{
struct gfs2_glock *gl = container_of(rcu, struct gfs2_glock, gl_rcu);
kfree(gl->gl_lksb.sb_lvbptr);
if (gl->gl_ops->go_flags & GLOF_ASPACE) {
struct gfs2_glock_aspace *gla =
container_of(gl, struct gfs2_glock_aspace, glock);
kmem_cache_free(gfs2_glock_aspace_cachep, gla);
} else
kmem_cache_free(gfs2_glock_cachep, gl);
}
/**
* glock_blocked_by_withdraw - determine if we can still use a glock
* @gl: the glock
*
* We need to allow some glocks to be enqueued, dequeued, promoted, and demoted
* when we're withdrawn. For example, to maintain metadata integrity, we should
* disallow the use of inode and rgrp glocks when withdrawn. Other glocks like
* the iopen or freeze glock may be safely used because none of their
* metadata goes through the journal. So in general, we should disallow all
* glocks that are journaled, and allow all the others. One exception is:
* we need to allow our active journal to be promoted and demoted so others
* may recover it and we can reacquire it when they're done.
*/
static bool glock_blocked_by_withdraw(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (likely(!gfs2_withdrawn(sdp)))
return false;
if (gl->gl_ops->go_flags & GLOF_NONDISK)
return false;
if (!sdp->sd_jdesc ||
gl->gl_name.ln_number == sdp->sd_jdesc->jd_no_addr)
return false;
return true;
}
void gfs2_glock_free(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
gfs2_glock_assert_withdraw(gl, atomic_read(&gl->gl_revokes) == 0);
rhashtable_remove_fast(&gl_hash_table, &gl->gl_node, ht_parms);
smp_mb();
wake_up_glock(gl);
call_rcu(&gl->gl_rcu, gfs2_glock_dealloc);
if (atomic_dec_and_test(&sdp->sd_glock_disposal))
wake_up(&sdp->sd_kill_wait);
}
/**
* gfs2_glock_hold() - increment reference count on glock
* @gl: The glock to hold
*
*/
struct gfs2_glock *gfs2_glock_hold(struct gfs2_glock *gl)
{
GLOCK_BUG_ON(gl, __lockref_is_dead(&gl->gl_lockref));
lockref_get(&gl->gl_lockref);
return gl;
}
/**
* demote_ok - Check to see if it's ok to unlock a glock
* @gl: the glock
*
* Returns: 1 if it's ok
*/
static int demote_ok(const struct gfs2_glock *gl)
{
const struct gfs2_glock_operations *glops = gl->gl_ops;
if (gl->gl_state == LM_ST_UNLOCKED)
return 0;
if (!list_empty(&gl->gl_holders))
return 0;
if (glops->go_demote_ok)
return glops->go_demote_ok(gl);
return 1;
}
void gfs2_glock_add_to_lru(struct gfs2_glock *gl)
{
if (!(gl->gl_ops->go_flags & GLOF_LRU))
return;
spin_lock(&lru_lock);
list_move_tail(&gl->gl_lru, &lru_list);
if (!test_bit(GLF_LRU, &gl->gl_flags)) {
set_bit(GLF_LRU, &gl->gl_flags);
atomic_inc(&lru_count);
}
spin_unlock(&lru_lock);
}
static void gfs2_glock_remove_from_lru(struct gfs2_glock *gl)
{
if (!(gl->gl_ops->go_flags & GLOF_LRU))
return;
spin_lock(&lru_lock);
if (test_bit(GLF_LRU, &gl->gl_flags)) {
list_del_init(&gl->gl_lru);
atomic_dec(&lru_count);
clear_bit(GLF_LRU, &gl->gl_flags);
}
spin_unlock(&lru_lock);
}
/*
* Enqueue the glock on the work queue. Passes one glock reference on to the
* work queue.
*/
static void __gfs2_glock_queue_work(struct gfs2_glock *gl, unsigned long delay) {
if (!queue_delayed_work(glock_workqueue, &gl->gl_work, delay)) {
/*
* We are holding the lockref spinlock, and the work was still
* queued above. The queued work (glock_work_func) takes that
* spinlock before dropping its glock reference(s), so it
* cannot have dropped them in the meantime.
*/
GLOCK_BUG_ON(gl, gl->gl_lockref.count < 2);
gl->gl_lockref.count--;
}
}
static void gfs2_glock_queue_work(struct gfs2_glock *gl, unsigned long delay) {
spin_lock(&gl->gl_lockref.lock);
__gfs2_glock_queue_work(gl, delay);
spin_unlock(&gl->gl_lockref.lock);
}
static void __gfs2_glock_put(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct address_space *mapping = gfs2_glock2aspace(gl);
lockref_mark_dead(&gl->gl_lockref);
spin_unlock(&gl->gl_lockref.lock);
gfs2_glock_remove_from_lru(gl);
GLOCK_BUG_ON(gl, !list_empty(&gl->gl_holders));
if (mapping) {
truncate_inode_pages_final(mapping);
if (!gfs2_withdrawn(sdp))
GLOCK_BUG_ON(gl, !mapping_empty(mapping));
}
trace_gfs2_glock_put(gl);
sdp->sd_lockstruct.ls_ops->lm_put_lock(gl);
}
/*
* Cause the glock to be put in work queue context.
*/
void gfs2_glock_queue_put(struct gfs2_glock *gl)
{
gfs2_glock_queue_work(gl, 0);
}
/**
* gfs2_glock_put() - Decrement reference count on glock
* @gl: The glock to put
*
*/
void gfs2_glock_put(struct gfs2_glock *gl)
{
if (lockref_put_or_lock(&gl->gl_lockref))
return;
__gfs2_glock_put(gl);
}
/**
* may_grant - check if it's ok to grant a new lock
* @gl: The glock
* @current_gh: One of the current holders of @gl
* @gh: The lock request which we wish to grant
*
* With our current compatibility rules, if a glock has one or more active
* holders (HIF_HOLDER flag set), any of those holders can be passed in as
* @current_gh; they are all the same as far as compatibility with the new @gh
* goes.
*
* Returns true if it's ok to grant the lock.
*/
static inline bool may_grant(struct gfs2_glock *gl,
struct gfs2_holder *current_gh,
struct gfs2_holder *gh)
{
if (current_gh) {
GLOCK_BUG_ON(gl, !test_bit(HIF_HOLDER, ¤t_gh->gh_iflags));
switch(current_gh->gh_state) {
case LM_ST_EXCLUSIVE:
/*
* Here we make a special exception to grant holders
* who agree to share the EX lock with other holders
* who also have the bit set. If the original holder
* has the LM_FLAG_NODE_SCOPE bit set, we grant more
* holders with the bit set.
*/
return gh->gh_state == LM_ST_EXCLUSIVE &&
(current_gh->gh_flags & LM_FLAG_NODE_SCOPE) &&
(gh->gh_flags & LM_FLAG_NODE_SCOPE);
case LM_ST_SHARED:
case LM_ST_DEFERRED:
return gh->gh_state == current_gh->gh_state;
default:
return false;
}
}
if (gl->gl_state == gh->gh_state)
return true;
if (gh->gh_flags & GL_EXACT)
return false;
if (gl->gl_state == LM_ST_EXCLUSIVE) {
return gh->gh_state == LM_ST_SHARED ||
gh->gh_state == LM_ST_DEFERRED;
}
if (gh->gh_flags & LM_FLAG_ANY)
return gl->gl_state != LM_ST_UNLOCKED;
return false;
}
static void gfs2_holder_wake(struct gfs2_holder *gh)
{
clear_bit(HIF_WAIT, &gh->gh_iflags);
smp_mb__after_atomic();
wake_up_bit(&gh->gh_iflags, HIF_WAIT);
if (gh->gh_flags & GL_ASYNC) {
struct gfs2_sbd *sdp = gh->gh_gl->gl_name.ln_sbd;
wake_up(&sdp->sd_async_glock_wait);
}
}
/**
* do_error - Something unexpected has happened during a lock request
* @gl: The glock
* @ret: The status from the DLM
*/
static void do_error(struct gfs2_glock *gl, const int ret)
{
struct gfs2_holder *gh, *tmp;
list_for_each_entry_safe(gh, tmp, &gl->gl_holders, gh_list) {
if (test_bit(HIF_HOLDER, &gh->gh_iflags))
continue;
if (ret & LM_OUT_ERROR)
gh->gh_error = -EIO;
else if (gh->gh_flags & (LM_FLAG_TRY | LM_FLAG_TRY_1CB))
gh->gh_error = GLR_TRYFAILED;
else
continue;
list_del_init(&gh->gh_list);
trace_gfs2_glock_queue(gh, 0);
gfs2_holder_wake(gh);
}
}
/**
* find_first_holder - find the first "holder" gh
* @gl: the glock
*/
static inline struct gfs2_holder *find_first_holder(const struct gfs2_glock *gl)
{
struct gfs2_holder *gh;
if (!list_empty(&gl->gl_holders)) {
gh = list_first_entry(&gl->gl_holders, struct gfs2_holder,
gh_list);
if (test_bit(HIF_HOLDER, &gh->gh_iflags))
return gh;
}
return NULL;
}
/*
* gfs2_instantiate - Call the glops instantiate function
* @gh: The glock holder
*
* Returns: 0 if instantiate was successful, or error.
*/
int gfs2_instantiate(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
const struct gfs2_glock_operations *glops = gl->gl_ops;
int ret;
again:
if (!test_bit(GLF_INSTANTIATE_NEEDED, &gl->gl_flags))
goto done;
/*
* Since we unlock the lockref lock, we set a flag to indicate
* instantiate is in progress.
*/
if (test_and_set_bit(GLF_INSTANTIATE_IN_PROG, &gl->gl_flags)) {
wait_on_bit(&gl->gl_flags, GLF_INSTANTIATE_IN_PROG,
TASK_UNINTERRUPTIBLE);
/*
* Here we just waited for a different instantiate to finish.
* But that may not have been successful, as when a process
* locks an inode glock _before_ it has an actual inode to
* instantiate into. So we check again. This process might
* have an inode to instantiate, so might be successful.
*/
goto again;
}
ret = glops->go_instantiate(gl);
if (!ret)
clear_bit(GLF_INSTANTIATE_NEEDED, &gl->gl_flags);
clear_and_wake_up_bit(GLF_INSTANTIATE_IN_PROG, &gl->gl_flags);
if (ret)
return ret;
done:
if (glops->go_held)
return glops->go_held(gh);
return 0;
}
/**
* do_promote - promote as many requests as possible on the current queue
* @gl: The glock
*
* Returns true on success (i.e., progress was made or there are no waiters).
*/
static bool do_promote(struct gfs2_glock *gl)
{
struct gfs2_holder *gh, *current_gh;
current_gh = find_first_holder(gl);
list_for_each_entry(gh, &gl->gl_holders, gh_list) {
if (test_bit(HIF_HOLDER, &gh->gh_iflags))
continue;
if (!may_grant(gl, current_gh, gh)) {
/*
* If we get here, it means we may not grant this
* holder for some reason. If this holder is at the
* head of the list, it means we have a blocked holder
* at the head, so return false.
*/
if (list_is_first(&gh->gh_list, &gl->gl_holders))
return false;
do_error(gl, 0);
break;
}
set_bit(HIF_HOLDER, &gh->gh_iflags);
trace_gfs2_promote(gh);
gfs2_holder_wake(gh);
if (!current_gh)
current_gh = gh;
}
return true;
}
/**
* find_first_waiter - find the first gh that's waiting for the glock
* @gl: the glock
*/
static inline struct gfs2_holder *find_first_waiter(const struct gfs2_glock *gl)
{
struct gfs2_holder *gh;
list_for_each_entry(gh, &gl->gl_holders, gh_list) {
if (!test_bit(HIF_HOLDER, &gh->gh_iflags))
return gh;
}
return NULL;
}
/**
* state_change - record that the glock is now in a different state
* @gl: the glock
* @new_state: the new state
*/
static void state_change(struct gfs2_glock *gl, unsigned int new_state)
{
int held1, held2;
held1 = (gl->gl_state != LM_ST_UNLOCKED);
held2 = (new_state != LM_ST_UNLOCKED);
if (held1 != held2) {
GLOCK_BUG_ON(gl, __lockref_is_dead(&gl->gl_lockref));
if (held2)
gl->gl_lockref.count++;
else
gl->gl_lockref.count--;
}
if (new_state != gl->gl_target)
/* shorten our minimum hold time */
gl->gl_hold_time = max(gl->gl_hold_time - GL_GLOCK_HOLD_DECR,
GL_GLOCK_MIN_HOLD);
gl->gl_state = new_state;
gl->gl_tchange = jiffies;
}
static void gfs2_set_demote(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
set_bit(GLF_DEMOTE, &gl->gl_flags);
smp_mb();
wake_up(&sdp->sd_async_glock_wait);
}
static void gfs2_demote_wake(struct gfs2_glock *gl)
{
gl->gl_demote_state = LM_ST_EXCLUSIVE;
clear_bit(GLF_DEMOTE, &gl->gl_flags);
smp_mb__after_atomic();
wake_up_bit(&gl->gl_flags, GLF_DEMOTE);
}
/**
* finish_xmote - The DLM has replied to one of our lock requests
* @gl: The glock
* @ret: The status from the DLM
*
*/
static void finish_xmote(struct gfs2_glock *gl, unsigned int ret)
{
const struct gfs2_glock_operations *glops = gl->gl_ops;
struct gfs2_holder *gh;
unsigned state = ret & LM_OUT_ST_MASK;
spin_lock(&gl->gl_lockref.lock);
trace_gfs2_glock_state_change(gl, state);
state_change(gl, state);
gh = find_first_waiter(gl);
/* Demote to UN request arrived during demote to SH or DF */
if (test_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags) &&
state != LM_ST_UNLOCKED && gl->gl_demote_state == LM_ST_UNLOCKED)
gl->gl_target = LM_ST_UNLOCKED;
/* Check for state != intended state */
if (unlikely(state != gl->gl_target)) {
if (gh && (ret & LM_OUT_CANCELED))
gfs2_holder_wake(gh);
if (gh && !test_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags)) {
/* move to back of queue and try next entry */
if (ret & LM_OUT_CANCELED) {
list_move_tail(&gh->gh_list, &gl->gl_holders);
gh = find_first_waiter(gl);
gl->gl_target = gh->gh_state;
if (do_promote(gl))
goto out;
goto retry;
}
/* Some error or failed "try lock" - report it */
if ((ret & LM_OUT_ERROR) ||
(gh->gh_flags & (LM_FLAG_TRY | LM_FLAG_TRY_1CB))) {
gl->gl_target = gl->gl_state;
do_error(gl, ret);
goto out;
}
}
switch(state) {
/* Unlocked due to conversion deadlock, try again */
case LM_ST_UNLOCKED:
retry:
do_xmote(gl, gh, gl->gl_target);
break;
/* Conversion fails, unlock and try again */
case LM_ST_SHARED:
case LM_ST_DEFERRED:
do_xmote(gl, gh, LM_ST_UNLOCKED);
break;
default: /* Everything else */
fs_err(gl->gl_name.ln_sbd, "wanted %u got %u\n",
gl->gl_target, state);
GLOCK_BUG_ON(gl, 1);
}
spin_unlock(&gl->gl_lockref.lock);
return;
}
/* Fast path - we got what we asked for */
if (test_and_clear_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags))
gfs2_demote_wake(gl);
if (state != LM_ST_UNLOCKED) {
if (glops->go_xmote_bh) {
int rv;
spin_unlock(&gl->gl_lockref.lock);
rv = glops->go_xmote_bh(gl);
spin_lock(&gl->gl_lockref.lock);
if (rv) {
do_error(gl, rv);
goto out;
}
}
do_promote(gl);
}
out:
clear_bit(GLF_LOCK, &gl->gl_flags);
spin_unlock(&gl->gl_lockref.lock);
}
static bool is_system_glock(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
if (gl == m_ip->i_gl)
return true;
return false;
}
/**
* do_xmote - Calls the DLM to change the state of a lock
* @gl: The lock state
* @gh: The holder (only for promotes)
* @target: The target lock state
*
*/
static void do_xmote(struct gfs2_glock *gl, struct gfs2_holder *gh,
unsigned int target)
__releases(&gl->gl_lockref.lock)
__acquires(&gl->gl_lockref.lock)
{
const struct gfs2_glock_operations *glops = gl->gl_ops;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
unsigned int lck_flags = (unsigned int)(gh ? gh->gh_flags : 0);
int ret;
if (target != LM_ST_UNLOCKED && glock_blocked_by_withdraw(gl) &&
gh && !(gh->gh_flags & LM_FLAG_NOEXP))
goto skip_inval;
lck_flags &= (LM_FLAG_TRY | LM_FLAG_TRY_1CB | LM_FLAG_NOEXP);
GLOCK_BUG_ON(gl, gl->gl_state == target);
GLOCK_BUG_ON(gl, gl->gl_state == gl->gl_target);
if ((target == LM_ST_UNLOCKED || target == LM_ST_DEFERRED) &&
glops->go_inval) {
/*
* If another process is already doing the invalidate, let that
* finish first. The glock state machine will get back to this
* holder again later.
*/
if (test_and_set_bit(GLF_INVALIDATE_IN_PROGRESS,
&gl->gl_flags))
return;
do_error(gl, 0); /* Fail queued try locks */
}
gl->gl_req = target;
set_bit(GLF_BLOCKING, &gl->gl_flags);
if ((gl->gl_req == LM_ST_UNLOCKED) ||
(gl->gl_state == LM_ST_EXCLUSIVE) ||
(lck_flags & (LM_FLAG_TRY|LM_FLAG_TRY_1CB)))
clear_bit(GLF_BLOCKING, &gl->gl_flags);
spin_unlock(&gl->gl_lockref.lock);
if (glops->go_sync) {
ret = glops->go_sync(gl);
/* If we had a problem syncing (due to io errors or whatever,
* we should not invalidate the metadata or tell dlm to
* release the glock to other nodes.
*/
if (ret) {
if (cmpxchg(&sdp->sd_log_error, 0, ret)) {
fs_err(sdp, "Error %d syncing glock \n", ret);
gfs2_dump_glock(NULL, gl, true);
}
goto skip_inval;
}
}
if (test_bit(GLF_INVALIDATE_IN_PROGRESS, &gl->gl_flags)) {
/*
* The call to go_sync should have cleared out the ail list.
* If there are still items, we have a problem. We ought to
* withdraw, but we can't because the withdraw code also uses
* glocks. Warn about the error, dump the glock, then fall
* through and wait for logd to do the withdraw for us.
*/
if ((atomic_read(&gl->gl_ail_count) != 0) &&
(!cmpxchg(&sdp->sd_log_error, 0, -EIO))) {
gfs2_glock_assert_warn(gl,
!atomic_read(&gl->gl_ail_count));
gfs2_dump_glock(NULL, gl, true);
}
glops->go_inval(gl, target == LM_ST_DEFERRED ? 0 : DIO_METADATA);
clear_bit(GLF_INVALIDATE_IN_PROGRESS, &gl->gl_flags);
}
skip_inval:
gfs2_glock_hold(gl);
/*
* Check for an error encountered since we called go_sync and go_inval.
* If so, we can't withdraw from the glock code because the withdraw
* code itself uses glocks (see function signal_our_withdraw) to
* change the mount to read-only. Most importantly, we must not call
* dlm to unlock the glock until the journal is in a known good state
* (after journal replay) otherwise other nodes may use the object
* (rgrp or dinode) and then later, journal replay will corrupt the
* file system. The best we can do here is wait for the logd daemon
* to see sd_log_error and withdraw, and in the meantime, requeue the
* work for later.
*
* We make a special exception for some system glocks, such as the
* system statfs inode glock, which needs to be granted before the
* gfs2_quotad daemon can exit, and that exit needs to finish before
* we can unmount the withdrawn file system.
*
* However, if we're just unlocking the lock (say, for unmount, when
* gfs2_gl_hash_clear calls clear_glock) and recovery is complete
* then it's okay to tell dlm to unlock it.
*/
if (unlikely(sdp->sd_log_error && !gfs2_withdrawn(sdp)))
gfs2_withdraw_delayed(sdp);
if (glock_blocked_by_withdraw(gl) &&
(target != LM_ST_UNLOCKED ||
test_bit(SDF_WITHDRAW_RECOVERY, &sdp->sd_flags))) {
if (!is_system_glock(gl)) {
handle_callback(gl, LM_ST_UNLOCKED, 0, false); /* sets demote */
/*
* Ordinarily, we would call dlm and its callback would call
* finish_xmote, which would call state_change() to the new state.
* Since we withdrew, we won't call dlm, so call state_change
* manually, but to the UNLOCKED state we desire.
*/
state_change(gl, LM_ST_UNLOCKED);
/*
* We skip telling dlm to do the locking, so we won't get a
* reply that would otherwise clear GLF_LOCK. So we clear it here.
*/
clear_bit(GLF_LOCK, &gl->gl_flags);
clear_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags);
gfs2_glock_queue_work(gl, GL_GLOCK_DFT_HOLD);
goto out;
} else {
clear_bit(GLF_INVALIDATE_IN_PROGRESS, &gl->gl_flags);
}
}
if (sdp->sd_lockstruct.ls_ops->lm_lock) {
/* lock_dlm */
ret = sdp->sd_lockstruct.ls_ops->lm_lock(gl, target, lck_flags);
if (ret == -EINVAL && gl->gl_target == LM_ST_UNLOCKED &&
target == LM_ST_UNLOCKED &&
test_bit(SDF_SKIP_DLM_UNLOCK, &sdp->sd_flags)) {
finish_xmote(gl, target);
gfs2_glock_queue_work(gl, 0);
} else if (ret) {
fs_err(sdp, "lm_lock ret %d\n", ret);
GLOCK_BUG_ON(gl, !gfs2_withdrawn(sdp));
}
} else { /* lock_nolock */
finish_xmote(gl, target);
gfs2_glock_queue_work(gl, 0);
}
out:
spin_lock(&gl->gl_lockref.lock);
}
/**
* run_queue - do all outstanding tasks related to a glock
* @gl: The glock in question
* @nonblock: True if we must not block in run_queue
*
*/
static void run_queue(struct gfs2_glock *gl, const int nonblock)
__releases(&gl->gl_lockref.lock)
__acquires(&gl->gl_lockref.lock)
{
struct gfs2_holder *gh = NULL;
if (test_and_set_bit(GLF_LOCK, &gl->gl_flags))
return;
GLOCK_BUG_ON(gl, test_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags));
if (test_bit(GLF_DEMOTE, &gl->gl_flags) &&
gl->gl_demote_state != gl->gl_state) {
if (find_first_holder(gl))
goto out_unlock;
if (nonblock)
goto out_sched;
set_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags);
GLOCK_BUG_ON(gl, gl->gl_demote_state == LM_ST_EXCLUSIVE);
gl->gl_target = gl->gl_demote_state;
} else {
if (test_bit(GLF_DEMOTE, &gl->gl_flags))
gfs2_demote_wake(gl);
if (do_promote(gl))
goto out_unlock;
gh = find_first_waiter(gl);
gl->gl_target = gh->gh_state;
if (!(gh->gh_flags & (LM_FLAG_TRY | LM_FLAG_TRY_1CB)))
do_error(gl, 0); /* Fail queued try locks */
}
do_xmote(gl, gh, gl->gl_target);
return;
out_sched:
clear_bit(GLF_LOCK, &gl->gl_flags);
smp_mb__after_atomic();
gl->gl_lockref.count++;
__gfs2_glock_queue_work(gl, 0);
return;
out_unlock:
clear_bit(GLF_LOCK, &gl->gl_flags);
smp_mb__after_atomic();
return;
}
/**
* glock_set_object - set the gl_object field of a glock
* @gl: the glock
* @object: the object
*/
void glock_set_object(struct gfs2_glock *gl, void *object)
{
void *prev_object;
spin_lock(&gl->gl_lockref.lock);
prev_object = gl->gl_object;
gl->gl_object = object;
spin_unlock(&gl->gl_lockref.lock);
if (gfs2_assert_warn(gl->gl_name.ln_sbd, prev_object == NULL)) {
pr_warn("glock=%u/%llx\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number);
gfs2_dump_glock(NULL, gl, true);
}
}
/**
* glock_clear_object - clear the gl_object field of a glock
* @gl: the glock
* @object: object the glock currently points at
*/
void glock_clear_object(struct gfs2_glock *gl, void *object)
{
void *prev_object;
spin_lock(&gl->gl_lockref.lock);
prev_object = gl->gl_object;
gl->gl_object = NULL;
spin_unlock(&gl->gl_lockref.lock);
if (gfs2_assert_warn(gl->gl_name.ln_sbd, prev_object == object)) {
pr_warn("glock=%u/%llx\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number);
gfs2_dump_glock(NULL, gl, true);
}
}
void gfs2_inode_remember_delete(struct gfs2_glock *gl, u64 generation)
{
struct gfs2_inode_lvb *ri = (void *)gl->gl_lksb.sb_lvbptr;
if (ri->ri_magic == 0)
ri->ri_magic = cpu_to_be32(GFS2_MAGIC);
if (ri->ri_magic == cpu_to_be32(GFS2_MAGIC))
ri->ri_generation_deleted = cpu_to_be64(generation);
}
bool gfs2_inode_already_deleted(struct gfs2_glock *gl, u64 generation)
{
struct gfs2_inode_lvb *ri = (void *)gl->gl_lksb.sb_lvbptr;
if (ri->ri_magic != cpu_to_be32(GFS2_MAGIC))
return false;
return generation <= be64_to_cpu(ri->ri_generation_deleted);
}
static void gfs2_glock_poke(struct gfs2_glock *gl)
{
int flags = LM_FLAG_TRY_1CB | LM_FLAG_ANY | GL_SKIP;
struct gfs2_holder gh;
int error;
__gfs2_holder_init(gl, LM_ST_SHARED, flags, &gh, _RET_IP_);
error = gfs2_glock_nq(&gh);
if (!error)
gfs2_glock_dq(&gh);
gfs2_holder_uninit(&gh);
}
static bool gfs2_try_evict(struct gfs2_glock *gl)
{
struct gfs2_inode *ip;
bool evicted = false;
/*
* If there is contention on the iopen glock and we have an inode, try
* to grab and release the inode so that it can be evicted. This will
* allow the remote node to go ahead and delete the inode without us
* having to do it, which will avoid rgrp glock thrashing.
*
* The remote node is likely still holding the corresponding inode
* glock, so it will run before we get to verify that the delete has
* happened below.
*/
spin_lock(&gl->gl_lockref.lock);
ip = gl->gl_object;
if (ip && !igrab(&ip->i_inode))
ip = NULL;
spin_unlock(&gl->gl_lockref.lock);
if (ip) {
gl->gl_no_formal_ino = ip->i_no_formal_ino;
set_bit(GIF_DEFERRED_DELETE, &ip->i_flags);
d_prune_aliases(&ip->i_inode);
iput(&ip->i_inode);
/* If the inode was evicted, gl->gl_object will now be NULL. */
spin_lock(&gl->gl_lockref.lock);
ip = gl->gl_object;
if (ip) {
clear_bit(GIF_DEFERRED_DELETE, &ip->i_flags);
if (!igrab(&ip->i_inode))
ip = NULL;
}
spin_unlock(&gl->gl_lockref.lock);
if (ip) {
gfs2_glock_poke(ip->i_gl);
iput(&ip->i_inode);
}
evicted = !ip;
}
return evicted;
}
bool gfs2_queue_try_to_evict(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (test_and_set_bit(GLF_TRY_TO_EVICT, &gl->gl_flags))
return false;
return queue_delayed_work(sdp->sd_delete_wq,
&gl->gl_delete, 0);
}
static bool gfs2_queue_verify_evict(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (test_and_set_bit(GLF_VERIFY_EVICT, &gl->gl_flags))
return false;
return queue_delayed_work(sdp->sd_delete_wq,
&gl->gl_delete, 5 * HZ);
}
static void delete_work_func(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct gfs2_glock *gl = container_of(dwork, struct gfs2_glock, gl_delete);
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct inode *inode;
u64 no_addr = gl->gl_name.ln_number;
if (test_and_clear_bit(GLF_TRY_TO_EVICT, &gl->gl_flags)) {
/*
* If we can evict the inode, give the remote node trying to
* delete the inode some time before verifying that the delete
* has happened. Otherwise, if we cause contention on the inode glock
* immediately, the remote node will think that we still have
* the inode in use, and so it will give up waiting.
*
* If we can't evict the inode, signal to the remote node that
* the inode is still in use. We'll later try to delete the
* inode locally in gfs2_evict_inode.
*
* FIXME: We only need to verify that the remote node has
* deleted the inode because nodes before this remote delete
* rework won't cooperate. At a later time, when we no longer
* care about compatibility with such nodes, we can skip this
* step entirely.
*/
if (gfs2_try_evict(gl)) {
if (test_bit(SDF_KILL, &sdp->sd_flags))
goto out;
if (gfs2_queue_verify_evict(gl))
return;
}
goto out;
}
if (test_and_clear_bit(GLF_VERIFY_EVICT, &gl->gl_flags)) {
inode = gfs2_lookup_by_inum(sdp, no_addr, gl->gl_no_formal_ino,
GFS2_BLKST_UNLINKED);
if (IS_ERR(inode)) {
if (PTR_ERR(inode) == -EAGAIN &&
!test_bit(SDF_KILL, &sdp->sd_flags) &&
gfs2_queue_verify_evict(gl))
return;
} else {
d_prune_aliases(inode);
iput(inode);
}
}
out:
gfs2_glock_put(gl);
}
static void glock_work_func(struct work_struct *work)
{
unsigned long delay = 0;
struct gfs2_glock *gl = container_of(work, struct gfs2_glock, gl_work.work);
unsigned int drop_refs = 1;
if (test_and_clear_bit(GLF_REPLY_PENDING, &gl->gl_flags)) {
finish_xmote(gl, gl->gl_reply);
drop_refs++;
}
spin_lock(&gl->gl_lockref.lock);
if (test_bit(GLF_PENDING_DEMOTE, &gl->gl_flags) &&
gl->gl_state != LM_ST_UNLOCKED &&
gl->gl_demote_state != LM_ST_EXCLUSIVE) {
unsigned long holdtime, now = jiffies;
holdtime = gl->gl_tchange + gl->gl_hold_time;
if (time_before(now, holdtime))
delay = holdtime - now;
if (!delay) {
clear_bit(GLF_PENDING_DEMOTE, &gl->gl_flags);
gfs2_set_demote(gl);
}
}
run_queue(gl, 0);
if (delay) {
/* Keep one glock reference for the work we requeue. */
drop_refs--;
if (gl->gl_name.ln_type != LM_TYPE_INODE)
delay = 0;
__gfs2_glock_queue_work(gl, delay);
}
/*
* Drop the remaining glock references manually here. (Mind that
* __gfs2_glock_queue_work depends on the lockref spinlock begin held
* here as well.)
*/
gl->gl_lockref.count -= drop_refs;
if (!gl->gl_lockref.count) {
__gfs2_glock_put(gl);
return;
}
spin_unlock(&gl->gl_lockref.lock);
}
static struct gfs2_glock *find_insert_glock(struct lm_lockname *name,
struct gfs2_glock *new)
{
struct wait_glock_queue wait;
wait_queue_head_t *wq = glock_waitqueue(name);
struct gfs2_glock *gl;
wait.name = name;
init_wait(&wait.wait);
wait.wait.func = glock_wake_function;
again:
prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
rcu_read_lock();
if (new) {
gl = rhashtable_lookup_get_insert_fast(&gl_hash_table,
&new->gl_node, ht_parms);
if (IS_ERR(gl))
goto out;
} else {
gl = rhashtable_lookup_fast(&gl_hash_table,
name, ht_parms);
}
if (gl && !lockref_get_not_dead(&gl->gl_lockref)) {
rcu_read_unlock();
schedule();
goto again;
}
out:
rcu_read_unlock();
finish_wait(wq, &wait.wait);
return gl;
}
/**
* gfs2_glock_get() - Get a glock, or create one if one doesn't exist
* @sdp: The GFS2 superblock
* @number: the lock number
* @glops: The glock_operations to use
* @create: If 0, don't create the glock if it doesn't exist
* @glp: the glock is returned here
*
* This does not lock a glock, just finds/creates structures for one.
*
* Returns: errno
*/
int gfs2_glock_get(struct gfs2_sbd *sdp, u64 number,
const struct gfs2_glock_operations *glops, int create,
struct gfs2_glock **glp)
{
struct super_block *s = sdp->sd_vfs;
struct lm_lockname name = { .ln_number = number,
.ln_type = glops->go_type,
.ln_sbd = sdp };
struct gfs2_glock *gl, *tmp;
struct address_space *mapping;
int ret = 0;
gl = find_insert_glock(&name, NULL);
if (gl) {
*glp = gl;
return 0;
}
if (!create)
return -ENOENT;
if (glops->go_flags & GLOF_ASPACE) {
struct gfs2_glock_aspace *gla =
kmem_cache_alloc(gfs2_glock_aspace_cachep, GFP_NOFS);
if (!gla)
return -ENOMEM;
gl = &gla->glock;
} else {
gl = kmem_cache_alloc(gfs2_glock_cachep, GFP_NOFS);
if (!gl)
return -ENOMEM;
}
memset(&gl->gl_lksb, 0, sizeof(struct dlm_lksb));
gl->gl_ops = glops;
if (glops->go_flags & GLOF_LVB) {
gl->gl_lksb.sb_lvbptr = kzalloc(GDLM_LVB_SIZE, GFP_NOFS);
if (!gl->gl_lksb.sb_lvbptr) {
gfs2_glock_dealloc(&gl->gl_rcu);
return -ENOMEM;
}
}
atomic_inc(&sdp->sd_glock_disposal);
gl->gl_node.next = NULL;
gl->gl_flags = glops->go_instantiate ? BIT(GLF_INSTANTIATE_NEEDED) : 0;
gl->gl_name = name;
lockdep_set_subclass(&gl->gl_lockref.lock, glops->go_subclass);
gl->gl_lockref.count = 1;
gl->gl_state = LM_ST_UNLOCKED;
gl->gl_target = LM_ST_UNLOCKED;
gl->gl_demote_state = LM_ST_EXCLUSIVE;
gl->gl_dstamp = 0;
preempt_disable();
/* We use the global stats to estimate the initial per-glock stats */
gl->gl_stats = this_cpu_ptr(sdp->sd_lkstats)->lkstats[glops->go_type];
preempt_enable();
gl->gl_stats.stats[GFS2_LKS_DCOUNT] = 0;
gl->gl_stats.stats[GFS2_LKS_QCOUNT] = 0;
gl->gl_tchange = jiffies;
gl->gl_object = NULL;
gl->gl_hold_time = GL_GLOCK_DFT_HOLD;
INIT_DELAYED_WORK(&gl->gl_work, glock_work_func);
if (gl->gl_name.ln_type == LM_TYPE_IOPEN)
INIT_DELAYED_WORK(&gl->gl_delete, delete_work_func);
mapping = gfs2_glock2aspace(gl);
if (mapping) {
mapping->a_ops = &gfs2_meta_aops;
mapping->host = s->s_bdev->bd_inode;
mapping->flags = 0;
mapping_set_gfp_mask(mapping, GFP_NOFS);
mapping->private_data = NULL;
mapping->writeback_index = 0;
}
tmp = find_insert_glock(&name, gl);
if (!tmp) {
*glp = gl;
goto out;
}
if (IS_ERR(tmp)) {
ret = PTR_ERR(tmp);
goto out_free;
}
*glp = tmp;
out_free:
gfs2_glock_dealloc(&gl->gl_rcu);
if (atomic_dec_and_test(&sdp->sd_glock_disposal))
wake_up(&sdp->sd_kill_wait);
out:
return ret;
}
/**
* __gfs2_holder_init - initialize a struct gfs2_holder in the default way
* @gl: the glock
* @state: the state we're requesting
* @flags: the modifier flags
* @gh: the holder structure
*
*/
void __gfs2_holder_init(struct gfs2_glock *gl, unsigned int state, u16 flags,
struct gfs2_holder *gh, unsigned long ip)
{
INIT_LIST_HEAD(&gh->gh_list);
gh->gh_gl = gfs2_glock_hold(gl);
gh->gh_ip = ip;
gh->gh_owner_pid = get_pid(task_pid(current));
gh->gh_state = state;
gh->gh_flags = flags;
gh->gh_iflags = 0;
}
/**
* gfs2_holder_reinit - reinitialize a struct gfs2_holder so we can requeue it
* @state: the state we're requesting
* @flags: the modifier flags
* @gh: the holder structure
*
* Don't mess with the glock.
*
*/
void gfs2_holder_reinit(unsigned int state, u16 flags, struct gfs2_holder *gh)
{
gh->gh_state = state;
gh->gh_flags = flags;
gh->gh_iflags = 0;
gh->gh_ip = _RET_IP_;
put_pid(gh->gh_owner_pid);
gh->gh_owner_pid = get_pid(task_pid(current));
}
/**
* gfs2_holder_uninit - uninitialize a holder structure (drop glock reference)
* @gh: the holder structure
*
*/
void gfs2_holder_uninit(struct gfs2_holder *gh)
{
put_pid(gh->gh_owner_pid);
gfs2_glock_put(gh->gh_gl);
gfs2_holder_mark_uninitialized(gh);
gh->gh_ip = 0;
}
static void gfs2_glock_update_hold_time(struct gfs2_glock *gl,
unsigned long start_time)
{
/* Have we waited longer that a second? */
if (time_after(jiffies, start_time + HZ)) {
/* Lengthen the minimum hold time. */
gl->gl_hold_time = min(gl->gl_hold_time + GL_GLOCK_HOLD_INCR,
GL_GLOCK_MAX_HOLD);
}
}
/**
* gfs2_glock_holder_ready - holder is ready and its error code can be collected
* @gh: the glock holder
*
* Called when a glock holder no longer needs to be waited for because it is
* now either held (HIF_HOLDER set; gh_error == 0), or acquiring the lock has
* failed (gh_error != 0).
*/
int gfs2_glock_holder_ready(struct gfs2_holder *gh)
{
if (gh->gh_error || (gh->gh_flags & GL_SKIP))
return gh->gh_error;
gh->gh_error = gfs2_instantiate(gh);
if (gh->gh_error)
gfs2_glock_dq(gh);
return gh->gh_error;
}
/**
* gfs2_glock_wait - wait on a glock acquisition
* @gh: the glock holder
*
* Returns: 0 on success
*/
int gfs2_glock_wait(struct gfs2_holder *gh)
{
unsigned long start_time = jiffies;
might_sleep();
wait_on_bit(&gh->gh_iflags, HIF_WAIT, TASK_UNINTERRUPTIBLE);
gfs2_glock_update_hold_time(gh->gh_gl, start_time);
return gfs2_glock_holder_ready(gh);
}
static int glocks_pending(unsigned int num_gh, struct gfs2_holder *ghs)
{
int i;
for (i = 0; i < num_gh; i++)
if (test_bit(HIF_WAIT, &ghs[i].gh_iflags))
return 1;
return 0;
}
/**
* gfs2_glock_async_wait - wait on multiple asynchronous glock acquisitions
* @num_gh: the number of holders in the array
* @ghs: the glock holder array
*
* Returns: 0 on success, meaning all glocks have been granted and are held.
* -ESTALE if the request timed out, meaning all glocks were released,
* and the caller should retry the operation.
*/
int gfs2_glock_async_wait(unsigned int num_gh, struct gfs2_holder *ghs)
{
struct gfs2_sbd *sdp = ghs[0].gh_gl->gl_name.ln_sbd;
int i, ret = 0, timeout = 0;
unsigned long start_time = jiffies;
might_sleep();
/*
* Total up the (minimum hold time * 2) of all glocks and use that to
* determine the max amount of time we should wait.
*/
for (i = 0; i < num_gh; i++)
timeout += ghs[i].gh_gl->gl_hold_time << 1;
if (!wait_event_timeout(sdp->sd_async_glock_wait,
!glocks_pending(num_gh, ghs), timeout)) {
ret = -ESTALE; /* request timed out. */
goto out;
}
for (i = 0; i < num_gh; i++) {
struct gfs2_holder *gh = &ghs[i];
int ret2;
if (test_bit(HIF_HOLDER, &gh->gh_iflags)) {
gfs2_glock_update_hold_time(gh->gh_gl,
start_time);
}
ret2 = gfs2_glock_holder_ready(gh);
if (!ret)
ret = ret2;
}
out:
if (ret) {
for (i = 0; i < num_gh; i++) {
struct gfs2_holder *gh = &ghs[i];
gfs2_glock_dq(gh);
}
}
return ret;
}
/**
* handle_callback - process a demote request
* @gl: the glock
* @state: the state the caller wants us to change to
* @delay: zero to demote immediately; otherwise pending demote
* @remote: true if this came from a different cluster node
*
* There are only two requests that we are going to see in actual
* practise: LM_ST_SHARED and LM_ST_UNLOCKED
*/
static void handle_callback(struct gfs2_glock *gl, unsigned int state,
unsigned long delay, bool remote)
{
if (delay)
set_bit(GLF_PENDING_DEMOTE, &gl->gl_flags);
else
gfs2_set_demote(gl);
if (gl->gl_demote_state == LM_ST_EXCLUSIVE) {
gl->gl_demote_state = state;
gl->gl_demote_time = jiffies;
} else if (gl->gl_demote_state != LM_ST_UNLOCKED &&
gl->gl_demote_state != state) {
gl->gl_demote_state = LM_ST_UNLOCKED;
}
if (gl->gl_ops->go_callback)
gl->gl_ops->go_callback(gl, remote);
trace_gfs2_demote_rq(gl, remote);
}
void gfs2_print_dbg(struct seq_file *seq, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
if (seq) {
seq_vprintf(seq, fmt, args);
} else {
vaf.fmt = fmt;
vaf.va = &args;
pr_err("%pV", &vaf);
}
va_end(args);
}
static inline bool pid_is_meaningful(const struct gfs2_holder *gh)
{
if (!(gh->gh_flags & GL_NOPID))
return true;
if (gh->gh_state == LM_ST_UNLOCKED)
return true;
return false;
}
/**
* add_to_queue - Add a holder to the wait queue (but look for recursion)
* @gh: the holder structure to add
*
* Eventually we should move the recursive locking trap to a
* debugging option or something like that. This is the fast
* path and needs to have the minimum number of distractions.
*
*/
static inline void add_to_queue(struct gfs2_holder *gh)
__releases(&gl->gl_lockref.lock)
__acquires(&gl->gl_lockref.lock)
{
struct gfs2_glock *gl = gh->gh_gl;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct list_head *insert_pt = NULL;
struct gfs2_holder *gh2;
int try_futile = 0;
GLOCK_BUG_ON(gl, gh->gh_owner_pid == NULL);
if (test_and_set_bit(HIF_WAIT, &gh->gh_iflags))
GLOCK_BUG_ON(gl, true);
if (gh->gh_flags & (LM_FLAG_TRY | LM_FLAG_TRY_1CB)) {
if (test_bit(GLF_LOCK, &gl->gl_flags)) {
struct gfs2_holder *current_gh;
current_gh = find_first_holder(gl);
try_futile = !may_grant(gl, current_gh, gh);
}
if (test_bit(GLF_INVALIDATE_IN_PROGRESS, &gl->gl_flags))
goto fail;
}
list_for_each_entry(gh2, &gl->gl_holders, gh_list) {
if (likely(gh2->gh_owner_pid != gh->gh_owner_pid))
continue;
if (gh->gh_gl->gl_ops->go_type == LM_TYPE_FLOCK)
continue;
if (!pid_is_meaningful(gh2))
continue;
goto trap_recursive;
}
list_for_each_entry(gh2, &gl->gl_holders, gh_list) {
if (try_futile &&
!(gh2->gh_flags & (LM_FLAG_TRY | LM_FLAG_TRY_1CB))) {
fail:
gh->gh_error = GLR_TRYFAILED;
gfs2_holder_wake(gh);
return;
}
if (test_bit(HIF_HOLDER, &gh2->gh_iflags))
continue;
}
trace_gfs2_glock_queue(gh, 1);
gfs2_glstats_inc(gl, GFS2_LKS_QCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_QCOUNT);
if (likely(insert_pt == NULL)) {
list_add_tail(&gh->gh_list, &gl->gl_holders);
return;
}
list_add_tail(&gh->gh_list, insert_pt);
gh = list_first_entry(&gl->gl_holders, struct gfs2_holder, gh_list);
spin_unlock(&gl->gl_lockref.lock);
if (sdp->sd_lockstruct.ls_ops->lm_cancel)
sdp->sd_lockstruct.ls_ops->lm_cancel(gl);
spin_lock(&gl->gl_lockref.lock);
return;
trap_recursive:
fs_err(sdp, "original: %pSR\n", (void *)gh2->gh_ip);
fs_err(sdp, "pid: %d\n", pid_nr(gh2->gh_owner_pid));
fs_err(sdp, "lock type: %d req lock state : %d\n",
gh2->gh_gl->gl_name.ln_type, gh2->gh_state);
fs_err(sdp, "new: %pSR\n", (void *)gh->gh_ip);
fs_err(sdp, "pid: %d\n", pid_nr(gh->gh_owner_pid));
fs_err(sdp, "lock type: %d req lock state : %d\n",
gh->gh_gl->gl_name.ln_type, gh->gh_state);
gfs2_dump_glock(NULL, gl, true);
BUG();
}
/**
* gfs2_glock_nq - enqueue a struct gfs2_holder onto a glock (acquire a glock)
* @gh: the holder structure
*
* if (gh->gh_flags & GL_ASYNC), this never returns an error
*
* Returns: 0, GLR_TRYFAILED, or errno on failure
*/
int gfs2_glock_nq(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
int error = 0;
if (glock_blocked_by_withdraw(gl) && !(gh->gh_flags & LM_FLAG_NOEXP))
return -EIO;
if (test_bit(GLF_LRU, &gl->gl_flags))
gfs2_glock_remove_from_lru(gl);
gh->gh_error = 0;
spin_lock(&gl->gl_lockref.lock);
add_to_queue(gh);
if (unlikely((LM_FLAG_NOEXP & gh->gh_flags) &&
test_and_clear_bit(GLF_FROZEN, &gl->gl_flags))) {
set_bit(GLF_REPLY_PENDING, &gl->gl_flags);
gl->gl_lockref.count++;
__gfs2_glock_queue_work(gl, 0);
}
run_queue(gl, 1);
spin_unlock(&gl->gl_lockref.lock);
if (!(gh->gh_flags & GL_ASYNC))
error = gfs2_glock_wait(gh);
return error;
}
/**
* gfs2_glock_poll - poll to see if an async request has been completed
* @gh: the holder
*
* Returns: 1 if the request is ready to be gfs2_glock_wait()ed on
*/
int gfs2_glock_poll(struct gfs2_holder *gh)
{
return test_bit(HIF_WAIT, &gh->gh_iflags) ? 0 : 1;
}
static inline bool needs_demote(struct gfs2_glock *gl)
{
return (test_bit(GLF_DEMOTE, &gl->gl_flags) ||
test_bit(GLF_PENDING_DEMOTE, &gl->gl_flags));
}
static void __gfs2_glock_dq(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
unsigned delay = 0;
int fast_path = 0;
/*
* This holder should not be cached, so mark it for demote.
* Note: this should be done before the check for needs_demote
* below.
*/
if (gh->gh_flags & GL_NOCACHE)
handle_callback(gl, LM_ST_UNLOCKED, 0, false);
list_del_init(&gh->gh_list);
clear_bit(HIF_HOLDER, &gh->gh_iflags);
trace_gfs2_glock_queue(gh, 0);
/*
* If there hasn't been a demote request we are done.
* (Let the remaining holders, if any, keep holding it.)
*/
if (!needs_demote(gl)) {
if (list_empty(&gl->gl_holders))
fast_path = 1;
}
if (!test_bit(GLF_LFLUSH, &gl->gl_flags) && demote_ok(gl))
gfs2_glock_add_to_lru(gl);
if (unlikely(!fast_path)) {
gl->gl_lockref.count++;
if (test_bit(GLF_PENDING_DEMOTE, &gl->gl_flags) &&
!test_bit(GLF_DEMOTE, &gl->gl_flags) &&
gl->gl_name.ln_type == LM_TYPE_INODE)
delay = gl->gl_hold_time;
__gfs2_glock_queue_work(gl, delay);
}
}
/**
* gfs2_glock_dq - dequeue a struct gfs2_holder from a glock (release a glock)
* @gh: the glock holder
*
*/
void gfs2_glock_dq(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
spin_lock(&gl->gl_lockref.lock);
if (!gfs2_holder_queued(gh)) {
/*
* May have already been dequeued because the locking request
* was GL_ASYNC and it has failed in the meantime.
*/
goto out;
}
if (list_is_first(&gh->gh_list, &gl->gl_holders) &&
!test_bit(HIF_HOLDER, &gh->gh_iflags)) {
spin_unlock(&gl->gl_lockref.lock);
gl->gl_name.ln_sbd->sd_lockstruct.ls_ops->lm_cancel(gl);
wait_on_bit(&gh->gh_iflags, HIF_WAIT, TASK_UNINTERRUPTIBLE);
spin_lock(&gl->gl_lockref.lock);
}
/*
* If we're in the process of file system withdraw, we cannot just
* dequeue any glocks until our journal is recovered, lest we introduce
* file system corruption. We need two exceptions to this rule: We need
* to allow unlocking of nondisk glocks and the glock for our own
* journal that needs recovery.
*/
if (test_bit(SDF_WITHDRAW_RECOVERY, &sdp->sd_flags) &&
glock_blocked_by_withdraw(gl) &&
gh->gh_gl != sdp->sd_jinode_gl) {
sdp->sd_glock_dqs_held++;
spin_unlock(&gl->gl_lockref.lock);
might_sleep();
wait_on_bit(&sdp->sd_flags, SDF_WITHDRAW_RECOVERY,
TASK_UNINTERRUPTIBLE);
spin_lock(&gl->gl_lockref.lock);
}
__gfs2_glock_dq(gh);
out:
spin_unlock(&gl->gl_lockref.lock);
}
void gfs2_glock_dq_wait(struct gfs2_holder *gh)
{
struct gfs2_glock *gl = gh->gh_gl;
gfs2_glock_dq(gh);
might_sleep();
wait_on_bit(&gl->gl_flags, GLF_DEMOTE, TASK_UNINTERRUPTIBLE);
}
/**
* gfs2_glock_dq_uninit - dequeue a holder from a glock and initialize it
* @gh: the holder structure
*
*/
void gfs2_glock_dq_uninit(struct gfs2_holder *gh)
{
gfs2_glock_dq(gh);
gfs2_holder_uninit(gh);
}
/**
* gfs2_glock_nq_num - acquire a glock based on lock number
* @sdp: the filesystem
* @number: the lock number
* @glops: the glock operations for the type of glock
* @state: the state to acquire the glock in
* @flags: modifier flags for the acquisition
* @gh: the struct gfs2_holder
*
* Returns: errno
*/
int gfs2_glock_nq_num(struct gfs2_sbd *sdp, u64 number,
const struct gfs2_glock_operations *glops,
unsigned int state, u16 flags, struct gfs2_holder *gh)
{
struct gfs2_glock *gl;
int error;
error = gfs2_glock_get(sdp, number, glops, CREATE, &gl);
if (!error) {
error = gfs2_glock_nq_init(gl, state, flags, gh);
gfs2_glock_put(gl);
}
return error;
}
/**
* glock_compare - Compare two struct gfs2_glock structures for sorting
* @arg_a: the first structure
* @arg_b: the second structure
*
*/
static int glock_compare(const void *arg_a, const void *arg_b)
{
const struct gfs2_holder *gh_a = *(const struct gfs2_holder **)arg_a;
const struct gfs2_holder *gh_b = *(const struct gfs2_holder **)arg_b;
const struct lm_lockname *a = &gh_a->gh_gl->gl_name;
const struct lm_lockname *b = &gh_b->gh_gl->gl_name;
if (a->ln_number > b->ln_number)
return 1;
if (a->ln_number < b->ln_number)
return -1;
BUG_ON(gh_a->gh_gl->gl_ops->go_type == gh_b->gh_gl->gl_ops->go_type);
return 0;
}
/**
* nq_m_sync - synchronously acquire more than one glock in deadlock free order
* @num_gh: the number of structures
* @ghs: an array of struct gfs2_holder structures
* @p: placeholder for the holder structure to pass back
*
* Returns: 0 on success (all glocks acquired),
* errno on failure (no glocks acquired)
*/
static int nq_m_sync(unsigned int num_gh, struct gfs2_holder *ghs,
struct gfs2_holder **p)
{
unsigned int x;
int error = 0;
for (x = 0; x < num_gh; x++)
p[x] = &ghs[x];
sort(p, num_gh, sizeof(struct gfs2_holder *), glock_compare, NULL);
for (x = 0; x < num_gh; x++) {
error = gfs2_glock_nq(p[x]);
if (error) {
while (x--)
gfs2_glock_dq(p[x]);
break;
}
}
return error;
}
/**
* gfs2_glock_nq_m - acquire multiple glocks
* @num_gh: the number of structures
* @ghs: an array of struct gfs2_holder structures
*
* Returns: 0 on success (all glocks acquired),
* errno on failure (no glocks acquired)
*/
int gfs2_glock_nq_m(unsigned int num_gh, struct gfs2_holder *ghs)
{
struct gfs2_holder *tmp[4];
struct gfs2_holder **pph = tmp;
int error = 0;
switch(num_gh) {
case 0:
return 0;
case 1:
return gfs2_glock_nq(ghs);
default:
if (num_gh <= 4)
break;
pph = kmalloc_array(num_gh, sizeof(struct gfs2_holder *),
GFP_NOFS);
if (!pph)
return -ENOMEM;
}
error = nq_m_sync(num_gh, ghs, pph);
if (pph != tmp)
kfree(pph);
return error;
}
/**
* gfs2_glock_dq_m - release multiple glocks
* @num_gh: the number of structures
* @ghs: an array of struct gfs2_holder structures
*
*/
void gfs2_glock_dq_m(unsigned int num_gh, struct gfs2_holder *ghs)
{
while (num_gh--)
gfs2_glock_dq(&ghs[num_gh]);
}
void gfs2_glock_cb(struct gfs2_glock *gl, unsigned int state)
{
unsigned long delay = 0;
unsigned long holdtime;
unsigned long now = jiffies;
gfs2_glock_hold(gl);
spin_lock(&gl->gl_lockref.lock);
holdtime = gl->gl_tchange + gl->gl_hold_time;
if (!list_empty(&gl->gl_holders) &&
gl->gl_name.ln_type == LM_TYPE_INODE) {
if (time_before(now, holdtime))
delay = holdtime - now;
if (test_bit(GLF_REPLY_PENDING, &gl->gl_flags))
delay = gl->gl_hold_time;
}
handle_callback(gl, state, delay, true);
__gfs2_glock_queue_work(gl, delay);
spin_unlock(&gl->gl_lockref.lock);
}
/**
* gfs2_should_freeze - Figure out if glock should be frozen
* @gl: The glock in question
*
* Glocks are not frozen if (a) the result of the dlm operation is
* an error, (b) the locking operation was an unlock operation or
* (c) if there is a "noexp" flagged request anywhere in the queue
*
* Returns: 1 if freezing should occur, 0 otherwise
*/
static int gfs2_should_freeze(const struct gfs2_glock *gl)
{
const struct gfs2_holder *gh;
if (gl->gl_reply & ~LM_OUT_ST_MASK)
return 0;
if (gl->gl_target == LM_ST_UNLOCKED)
return 0;
list_for_each_entry(gh, &gl->gl_holders, gh_list) {
if (test_bit(HIF_HOLDER, &gh->gh_iflags))
continue;
if (LM_FLAG_NOEXP & gh->gh_flags)
return 0;
}
return 1;
}
/**
* gfs2_glock_complete - Callback used by locking
* @gl: Pointer to the glock
* @ret: The return value from the dlm
*
* The gl_reply field is under the gl_lockref.lock lock so that it is ok
* to use a bitfield shared with other glock state fields.
*/
void gfs2_glock_complete(struct gfs2_glock *gl, int ret)
{
struct lm_lockstruct *ls = &gl->gl_name.ln_sbd->sd_lockstruct;
spin_lock(&gl->gl_lockref.lock);
gl->gl_reply = ret;
if (unlikely(test_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags))) {
if (gfs2_should_freeze(gl)) {
set_bit(GLF_FROZEN, &gl->gl_flags);
spin_unlock(&gl->gl_lockref.lock);
return;
}
}
gl->gl_lockref.count++;
set_bit(GLF_REPLY_PENDING, &gl->gl_flags);
__gfs2_glock_queue_work(gl, 0);
spin_unlock(&gl->gl_lockref.lock);
}
static int glock_cmp(void *priv, const struct list_head *a,
const struct list_head *b)
{
struct gfs2_glock *gla, *glb;
gla = list_entry(a, struct gfs2_glock, gl_lru);
glb = list_entry(b, struct gfs2_glock, gl_lru);
if (gla->gl_name.ln_number > glb->gl_name.ln_number)
return 1;
if (gla->gl_name.ln_number < glb->gl_name.ln_number)
return -1;
return 0;
}
/**
* gfs2_dispose_glock_lru - Demote a list of glocks
* @list: The list to dispose of
*
* Disposing of glocks may involve disk accesses, so that here we sort
* the glocks by number (i.e. disk location of the inodes) so that if
* there are any such accesses, they'll be sent in order (mostly).
*
* Must be called under the lru_lock, but may drop and retake this
* lock. While the lru_lock is dropped, entries may vanish from the
* list, but no new entries will appear on the list (since it is
* private)
*/
static void gfs2_dispose_glock_lru(struct list_head *list)
__releases(&lru_lock)
__acquires(&lru_lock)
{
struct gfs2_glock *gl;
list_sort(NULL, list, glock_cmp);
while(!list_empty(list)) {
gl = list_first_entry(list, struct gfs2_glock, gl_lru);
list_del_init(&gl->gl_lru);
clear_bit(GLF_LRU, &gl->gl_flags);
if (!spin_trylock(&gl->gl_lockref.lock)) {
add_back_to_lru:
list_add(&gl->gl_lru, &lru_list);
set_bit(GLF_LRU, &gl->gl_flags);
atomic_inc(&lru_count);
continue;
}
if (test_and_set_bit(GLF_LOCK, &gl->gl_flags)) {
spin_unlock(&gl->gl_lockref.lock);
goto add_back_to_lru;
}
gl->gl_lockref.count++;
if (demote_ok(gl))
handle_callback(gl, LM_ST_UNLOCKED, 0, false);
WARN_ON(!test_and_clear_bit(GLF_LOCK, &gl->gl_flags));
__gfs2_glock_queue_work(gl, 0);
spin_unlock(&gl->gl_lockref.lock);
cond_resched_lock(&lru_lock);
}
}
/**
* gfs2_scan_glock_lru - Scan the LRU looking for locks to demote
* @nr: The number of entries to scan
*
* This function selects the entries on the LRU which are able to
* be demoted, and then kicks off the process by calling
* gfs2_dispose_glock_lru() above.
*/
static long gfs2_scan_glock_lru(int nr)
{
struct gfs2_glock *gl, *next;
LIST_HEAD(dispose);
long freed = 0;
spin_lock(&lru_lock);
list_for_each_entry_safe(gl, next, &lru_list, gl_lru) {
if (nr-- <= 0)
break;
/* Test for being demotable */
if (!test_bit(GLF_LOCK, &gl->gl_flags)) {
if (!spin_trylock(&gl->gl_lockref.lock))
continue;
if (gl->gl_lockref.count <= 1 &&
(gl->gl_state == LM_ST_UNLOCKED ||
demote_ok(gl))) {
list_move(&gl->gl_lru, &dispose);
atomic_dec(&lru_count);
freed++;
}
spin_unlock(&gl->gl_lockref.lock);
}
}
if (!list_empty(&dispose))
gfs2_dispose_glock_lru(&dispose);
spin_unlock(&lru_lock);
return freed;
}
static unsigned long gfs2_glock_shrink_scan(struct shrinker *shrink,
struct shrink_control *sc)
{
if (!(sc->gfp_mask & __GFP_FS))
return SHRINK_STOP;
return gfs2_scan_glock_lru(sc->nr_to_scan);
}
static unsigned long gfs2_glock_shrink_count(struct shrinker *shrink,
struct shrink_control *sc)
{
return vfs_pressure_ratio(atomic_read(&lru_count));
}
static struct shrinker glock_shrinker = {
.seeks = DEFAULT_SEEKS,
.count_objects = gfs2_glock_shrink_count,
.scan_objects = gfs2_glock_shrink_scan,
};
/**
* glock_hash_walk - Call a function for glock in a hash bucket
* @examiner: the function
* @sdp: the filesystem
*
* Note that the function can be called multiple times on the same
* object. So the user must ensure that the function can cope with
* that.
*/
static void glock_hash_walk(glock_examiner examiner, const struct gfs2_sbd *sdp)
{
struct gfs2_glock *gl;
struct rhashtable_iter iter;
rhashtable_walk_enter(&gl_hash_table, &iter);
do {
rhashtable_walk_start(&iter);
while ((gl = rhashtable_walk_next(&iter)) && !IS_ERR(gl)) {
if (gl->gl_name.ln_sbd == sdp)
examiner(gl);
}
rhashtable_walk_stop(&iter);
} while (cond_resched(), gl == ERR_PTR(-EAGAIN));
rhashtable_walk_exit(&iter);
}
void gfs2_cancel_delete_work(struct gfs2_glock *gl)
{
clear_bit(GLF_TRY_TO_EVICT, &gl->gl_flags);
clear_bit(GLF_VERIFY_EVICT, &gl->gl_flags);
if (cancel_delayed_work(&gl->gl_delete))
gfs2_glock_put(gl);
}
static void flush_delete_work(struct gfs2_glock *gl)
{
if (gl->gl_name.ln_type == LM_TYPE_IOPEN) {
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
if (cancel_delayed_work(&gl->gl_delete)) {
queue_delayed_work(sdp->sd_delete_wq,
&gl->gl_delete, 0);
}
}
}
void gfs2_flush_delete_work(struct gfs2_sbd *sdp)
{
glock_hash_walk(flush_delete_work, sdp);
flush_workqueue(sdp->sd_delete_wq);
}
/**
* thaw_glock - thaw out a glock which has an unprocessed reply waiting
* @gl: The glock to thaw
*
*/
static void thaw_glock(struct gfs2_glock *gl)
{
if (!test_and_clear_bit(GLF_FROZEN, &gl->gl_flags))
return;
if (!lockref_get_not_dead(&gl->gl_lockref))
return;
set_bit(GLF_REPLY_PENDING, &gl->gl_flags);
gfs2_glock_queue_work(gl, 0);
}
/**
* clear_glock - look at a glock and see if we can free it from glock cache
* @gl: the glock to look at
*
*/
static void clear_glock(struct gfs2_glock *gl)
{
gfs2_glock_remove_from_lru(gl);
spin_lock(&gl->gl_lockref.lock);
if (!__lockref_is_dead(&gl->gl_lockref)) {
gl->gl_lockref.count++;
if (gl->gl_state != LM_ST_UNLOCKED)
handle_callback(gl, LM_ST_UNLOCKED, 0, false);
__gfs2_glock_queue_work(gl, 0);
}
spin_unlock(&gl->gl_lockref.lock);
}
/**
* gfs2_glock_thaw - Thaw any frozen glocks
* @sdp: The super block
*
*/
void gfs2_glock_thaw(struct gfs2_sbd *sdp)
{
glock_hash_walk(thaw_glock, sdp);
}
static void dump_glock(struct seq_file *seq, struct gfs2_glock *gl, bool fsid)
{
spin_lock(&gl->gl_lockref.lock);
gfs2_dump_glock(seq, gl, fsid);
spin_unlock(&gl->gl_lockref.lock);
}
static void dump_glock_func(struct gfs2_glock *gl)
{
dump_glock(NULL, gl, true);
}
static void withdraw_dq(struct gfs2_glock *gl)
{
spin_lock(&gl->gl_lockref.lock);
if (!__lockref_is_dead(&gl->gl_lockref) &&
glock_blocked_by_withdraw(gl))
do_error(gl, LM_OUT_ERROR); /* remove pending waiters */
spin_unlock(&gl->gl_lockref.lock);
}
void gfs2_gl_dq_holders(struct gfs2_sbd *sdp)
{
glock_hash_walk(withdraw_dq, sdp);
}
/**
* gfs2_gl_hash_clear - Empty out the glock hash table
* @sdp: the filesystem
*
* Called when unmounting the filesystem.
*/
void gfs2_gl_hash_clear(struct gfs2_sbd *sdp)
{
set_bit(SDF_SKIP_DLM_UNLOCK, &sdp->sd_flags);
flush_workqueue(glock_workqueue);
glock_hash_walk(clear_glock, sdp);
flush_workqueue(glock_workqueue);
wait_event_timeout(sdp->sd_kill_wait,
atomic_read(&sdp->sd_glock_disposal) == 0,
HZ * 600);
glock_hash_walk(dump_glock_func, sdp);
}
static const char *state2str(unsigned state)
{
switch(state) {
case LM_ST_UNLOCKED:
return "UN";
case LM_ST_SHARED:
return "SH";
case LM_ST_DEFERRED:
return "DF";
case LM_ST_EXCLUSIVE:
return "EX";
}
return "??";
}
static const char *hflags2str(char *buf, u16 flags, unsigned long iflags)
{
char *p = buf;
if (flags & LM_FLAG_TRY)
*p++ = 't';
if (flags & LM_FLAG_TRY_1CB)
*p++ = 'T';
if (flags & LM_FLAG_NOEXP)
*p++ = 'e';
if (flags & LM_FLAG_ANY)
*p++ = 'A';
if (flags & LM_FLAG_NODE_SCOPE)
*p++ = 'n';
if (flags & GL_ASYNC)
*p++ = 'a';
if (flags & GL_EXACT)
*p++ = 'E';
if (flags & GL_NOCACHE)
*p++ = 'c';
if (test_bit(HIF_HOLDER, &iflags))
*p++ = 'H';
if (test_bit(HIF_WAIT, &iflags))
*p++ = 'W';
if (flags & GL_SKIP)
*p++ = 's';
*p = 0;
return buf;
}
/**
* dump_holder - print information about a glock holder
* @seq: the seq_file struct
* @gh: the glock holder
* @fs_id_buf: pointer to file system id (if requested)
*
*/
static void dump_holder(struct seq_file *seq, const struct gfs2_holder *gh,
const char *fs_id_buf)
{
const char *comm = "(none)";
pid_t owner_pid = 0;
char flags_buf[32];
rcu_read_lock();
if (pid_is_meaningful(gh)) {
struct task_struct *gh_owner;
comm = "(ended)";
owner_pid = pid_nr(gh->gh_owner_pid);
gh_owner = pid_task(gh->gh_owner_pid, PIDTYPE_PID);
if (gh_owner)
comm = gh_owner->comm;
}
gfs2_print_dbg(seq, "%s H: s:%s f:%s e:%d p:%ld [%s] %pS\n",
fs_id_buf, state2str(gh->gh_state),
hflags2str(flags_buf, gh->gh_flags, gh->gh_iflags),
gh->gh_error, (long)owner_pid, comm, (void *)gh->gh_ip);
rcu_read_unlock();
}
static const char *gflags2str(char *buf, const struct gfs2_glock *gl)
{
const unsigned long *gflags = &gl->gl_flags;
char *p = buf;
if (test_bit(GLF_LOCK, gflags))
*p++ = 'l';
if (test_bit(GLF_DEMOTE, gflags))
*p++ = 'D';
if (test_bit(GLF_PENDING_DEMOTE, gflags))
*p++ = 'd';
if (test_bit(GLF_DEMOTE_IN_PROGRESS, gflags))
*p++ = 'p';
if (test_bit(GLF_DIRTY, gflags))
*p++ = 'y';
if (test_bit(GLF_LFLUSH, gflags))
*p++ = 'f';
if (test_bit(GLF_INVALIDATE_IN_PROGRESS, gflags))
*p++ = 'i';
if (test_bit(GLF_REPLY_PENDING, gflags))
*p++ = 'r';
if (test_bit(GLF_INITIAL, gflags))
*p++ = 'I';
if (test_bit(GLF_FROZEN, gflags))
*p++ = 'F';
if (!list_empty(&gl->gl_holders))
*p++ = 'q';
if (test_bit(GLF_LRU, gflags))
*p++ = 'L';
if (gl->gl_object)
*p++ = 'o';
if (test_bit(GLF_BLOCKING, gflags))
*p++ = 'b';
if (test_bit(GLF_FREEING, gflags))
*p++ = 'x';
if (test_bit(GLF_INSTANTIATE_NEEDED, gflags))
*p++ = 'n';
if (test_bit(GLF_INSTANTIATE_IN_PROG, gflags))
*p++ = 'N';
if (test_bit(GLF_TRY_TO_EVICT, gflags))
*p++ = 'e';
if (test_bit(GLF_VERIFY_EVICT, gflags))
*p++ = 'E';
*p = 0;
return buf;
}
/**
* gfs2_dump_glock - print information about a glock
* @seq: The seq_file struct
* @gl: the glock
* @fsid: If true, also dump the file system id
*
* The file format is as follows:
* One line per object, capital letters are used to indicate objects
* G = glock, I = Inode, R = rgrp, H = holder. Glocks are not indented,
* other objects are indented by a single space and follow the glock to
* which they are related. Fields are indicated by lower case letters
* followed by a colon and the field value, except for strings which are in
* [] so that its possible to see if they are composed of spaces for
* example. The field's are n = number (id of the object), f = flags,
* t = type, s = state, r = refcount, e = error, p = pid.
*
*/
void gfs2_dump_glock(struct seq_file *seq, struct gfs2_glock *gl, bool fsid)
{
const struct gfs2_glock_operations *glops = gl->gl_ops;
unsigned long long dtime;
const struct gfs2_holder *gh;
char gflags_buf[32];
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
char fs_id_buf[sizeof(sdp->sd_fsname) + 7];
unsigned long nrpages = 0;
if (gl->gl_ops->go_flags & GLOF_ASPACE) {
struct address_space *mapping = gfs2_glock2aspace(gl);
nrpages = mapping->nrpages;
}
memset(fs_id_buf, 0, sizeof(fs_id_buf));
if (fsid && sdp) /* safety precaution */
sprintf(fs_id_buf, "fsid=%s: ", sdp->sd_fsname);
dtime = jiffies - gl->gl_demote_time;
dtime *= 1000000/HZ; /* demote time in uSec */
if (!test_bit(GLF_DEMOTE, &gl->gl_flags))
dtime = 0;
gfs2_print_dbg(seq, "%sG: s:%s n:%u/%llx f:%s t:%s d:%s/%llu a:%d "
"v:%d r:%d m:%ld p:%lu\n",
fs_id_buf, state2str(gl->gl_state),
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number,
gflags2str(gflags_buf, gl),
state2str(gl->gl_target),
state2str(gl->gl_demote_state), dtime,
atomic_read(&gl->gl_ail_count),
atomic_read(&gl->gl_revokes),
(int)gl->gl_lockref.count, gl->gl_hold_time, nrpages);
list_for_each_entry(gh, &gl->gl_holders, gh_list)
dump_holder(seq, gh, fs_id_buf);
if (gl->gl_state != LM_ST_UNLOCKED && glops->go_dump)
glops->go_dump(seq, gl, fs_id_buf);
}
static int gfs2_glstats_seq_show(struct seq_file *seq, void *iter_ptr)
{
struct gfs2_glock *gl = iter_ptr;
seq_printf(seq, "G: n:%u/%llx rtt:%llu/%llu rttb:%llu/%llu irt:%llu/%llu dcnt: %llu qcnt: %llu\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number,
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SRTT],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SRTTVAR],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SRTTB],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SRTTVARB],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SIRT],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_SIRTVAR],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_DCOUNT],
(unsigned long long)gl->gl_stats.stats[GFS2_LKS_QCOUNT]);
return 0;
}
static const char *gfs2_gltype[] = {
"type",
"reserved",
"nondisk",
"inode",
"rgrp",
"meta",
"iopen",
"flock",
"plock",
"quota",
"journal",
};
static const char *gfs2_stype[] = {
[GFS2_LKS_SRTT] = "srtt",
[GFS2_LKS_SRTTVAR] = "srttvar",
[GFS2_LKS_SRTTB] = "srttb",
[GFS2_LKS_SRTTVARB] = "srttvarb",
[GFS2_LKS_SIRT] = "sirt",
[GFS2_LKS_SIRTVAR] = "sirtvar",
[GFS2_LKS_DCOUNT] = "dlm",
[GFS2_LKS_QCOUNT] = "queue",
};
#define GFS2_NR_SBSTATS (ARRAY_SIZE(gfs2_gltype) * ARRAY_SIZE(gfs2_stype))
static int gfs2_sbstats_seq_show(struct seq_file *seq, void *iter_ptr)
{
struct gfs2_sbd *sdp = seq->private;
loff_t pos = *(loff_t *)iter_ptr;
unsigned index = pos >> 3;
unsigned subindex = pos & 0x07;
int i;
if (index == 0 && subindex != 0)
return 0;
seq_printf(seq, "%-10s %8s:", gfs2_gltype[index],
(index == 0) ? "cpu": gfs2_stype[subindex]);
for_each_possible_cpu(i) {
const struct gfs2_pcpu_lkstats *lkstats = per_cpu_ptr(sdp->sd_lkstats, i);
if (index == 0)
seq_printf(seq, " %15u", i);
else
seq_printf(seq, " %15llu", (unsigned long long)lkstats->
lkstats[index - 1].stats[subindex]);
}
seq_putc(seq, '\n');
return 0;
}
int __init gfs2_glock_init(void)
{
int i, ret;
ret = rhashtable_init(&gl_hash_table, &ht_parms);
if (ret < 0)
return ret;
glock_workqueue = alloc_workqueue("glock_workqueue", WQ_MEM_RECLAIM |
WQ_HIGHPRI | WQ_FREEZABLE, 0);
if (!glock_workqueue) {
rhashtable_destroy(&gl_hash_table);
return -ENOMEM;
}
ret = register_shrinker(&glock_shrinker, "gfs2-glock");
if (ret) {
destroy_workqueue(glock_workqueue);
rhashtable_destroy(&gl_hash_table);
return ret;
}
for (i = 0; i < GLOCK_WAIT_TABLE_SIZE; i++)
init_waitqueue_head(glock_wait_table + i);
return 0;
}
void gfs2_glock_exit(void)
{
unregister_shrinker(&glock_shrinker);
rhashtable_destroy(&gl_hash_table);
destroy_workqueue(glock_workqueue);
}
static void gfs2_glock_iter_next(struct gfs2_glock_iter *gi, loff_t n)
{
struct gfs2_glock *gl = gi->gl;
if (gl) {
if (n == 0)
return;
if (!lockref_put_not_zero(&gl->gl_lockref))
gfs2_glock_queue_put(gl);
}
for (;;) {
gl = rhashtable_walk_next(&gi->hti);
if (IS_ERR_OR_NULL(gl)) {
if (gl == ERR_PTR(-EAGAIN)) {
n = 1;
continue;
}
gl = NULL;
break;
}
if (gl->gl_name.ln_sbd != gi->sdp)
continue;
if (n <= 1) {
if (!lockref_get_not_dead(&gl->gl_lockref))
continue;
break;
} else {
if (__lockref_is_dead(&gl->gl_lockref))
continue;
n--;
}
}
gi->gl = gl;
}
static void *gfs2_glock_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct gfs2_glock_iter *gi = seq->private;
loff_t n;
/*
* We can either stay where we are, skip to the next hash table
* entry, or start from the beginning.
*/
if (*pos < gi->last_pos) {
rhashtable_walk_exit(&gi->hti);
rhashtable_walk_enter(&gl_hash_table, &gi->hti);
n = *pos + 1;
} else {
n = *pos - gi->last_pos;
}
rhashtable_walk_start(&gi->hti);
gfs2_glock_iter_next(gi, n);
gi->last_pos = *pos;
return gi->gl;
}
static void *gfs2_glock_seq_next(struct seq_file *seq, void *iter_ptr,
loff_t *pos)
{
struct gfs2_glock_iter *gi = seq->private;
(*pos)++;
gi->last_pos = *pos;
gfs2_glock_iter_next(gi, 1);
return gi->gl;
}
static void gfs2_glock_seq_stop(struct seq_file *seq, void *iter_ptr)
__releases(RCU)
{
struct gfs2_glock_iter *gi = seq->private;
rhashtable_walk_stop(&gi->hti);
}
static int gfs2_glock_seq_show(struct seq_file *seq, void *iter_ptr)
{
dump_glock(seq, iter_ptr, false);
return 0;
}
static void *gfs2_sbstats_seq_start(struct seq_file *seq, loff_t *pos)
{
preempt_disable();
if (*pos >= GFS2_NR_SBSTATS)
return NULL;
return pos;
}
static void *gfs2_sbstats_seq_next(struct seq_file *seq, void *iter_ptr,
loff_t *pos)
{
(*pos)++;
if (*pos >= GFS2_NR_SBSTATS)
return NULL;
return pos;
}
static void gfs2_sbstats_seq_stop(struct seq_file *seq, void *iter_ptr)
{
preempt_enable();
}
static const struct seq_operations gfs2_glock_seq_ops = {
.start = gfs2_glock_seq_start,
.next = gfs2_glock_seq_next,
.stop = gfs2_glock_seq_stop,
.show = gfs2_glock_seq_show,
};
static const struct seq_operations gfs2_glstats_seq_ops = {
.start = gfs2_glock_seq_start,
.next = gfs2_glock_seq_next,
.stop = gfs2_glock_seq_stop,
.show = gfs2_glstats_seq_show,
};
static const struct seq_operations gfs2_sbstats_sops = {
.start = gfs2_sbstats_seq_start,
.next = gfs2_sbstats_seq_next,
.stop = gfs2_sbstats_seq_stop,
.show = gfs2_sbstats_seq_show,
};
#define GFS2_SEQ_GOODSIZE min(PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER, 65536UL)
static int __gfs2_glocks_open(struct inode *inode, struct file *file,
const struct seq_operations *ops)
{
int ret = seq_open_private(file, ops, sizeof(struct gfs2_glock_iter));
if (ret == 0) {
struct seq_file *seq = file->private_data;
struct gfs2_glock_iter *gi = seq->private;
gi->sdp = inode->i_private;
seq->buf = kmalloc(GFS2_SEQ_GOODSIZE, GFP_KERNEL | __GFP_NOWARN);
if (seq->buf)
seq->size = GFS2_SEQ_GOODSIZE;
/*
* Initially, we are "before" the first hash table entry; the
* first call to rhashtable_walk_next gets us the first entry.
*/
gi->last_pos = -1;
gi->gl = NULL;
rhashtable_walk_enter(&gl_hash_table, &gi->hti);
}
return ret;
}
static int gfs2_glocks_open(struct inode *inode, struct file *file)
{
return __gfs2_glocks_open(inode, file, &gfs2_glock_seq_ops);
}
static int gfs2_glocks_release(struct inode *inode, struct file *file)
{
struct seq_file *seq = file->private_data;
struct gfs2_glock_iter *gi = seq->private;
if (gi->gl)
gfs2_glock_put(gi->gl);
rhashtable_walk_exit(&gi->hti);
return seq_release_private(inode, file);
}
static int gfs2_glstats_open(struct inode *inode, struct file *file)
{
return __gfs2_glocks_open(inode, file, &gfs2_glstats_seq_ops);
}
static const struct file_operations gfs2_glocks_fops = {
.owner = THIS_MODULE,
.open = gfs2_glocks_open,
.read = seq_read,
.llseek = seq_lseek,
.release = gfs2_glocks_release,
};
static const struct file_operations gfs2_glstats_fops = {
.owner = THIS_MODULE,
.open = gfs2_glstats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = gfs2_glocks_release,
};
struct gfs2_glockfd_iter {
struct super_block *sb;
unsigned int tgid;
struct task_struct *task;
unsigned int fd;
struct file *file;
};
static struct task_struct *gfs2_glockfd_next_task(struct gfs2_glockfd_iter *i)
{
struct pid_namespace *ns = task_active_pid_ns(current);
struct pid *pid;
if (i->task)
put_task_struct(i->task);
rcu_read_lock();
retry:
i->task = NULL;
pid = find_ge_pid(i->tgid, ns);
if (pid) {
i->tgid = pid_nr_ns(pid, ns);
i->task = pid_task(pid, PIDTYPE_TGID);
if (!i->task) {
i->tgid++;
goto retry;
}
get_task_struct(i->task);
}
rcu_read_unlock();
return i->task;
}
static struct file *gfs2_glockfd_next_file(struct gfs2_glockfd_iter *i)
{
if (i->file) {
fput(i->file);
i->file = NULL;
}
rcu_read_lock();
for(;; i->fd++) {
struct inode *inode;
i->file = task_lookup_next_fd_rcu(i->task, &i->fd);
if (!i->file) {
i->fd = 0;
break;
}
inode = file_inode(i->file);
if (inode->i_sb != i->sb)
continue;
if (get_file_rcu(i->file))
break;
}
rcu_read_unlock();
return i->file;
}
static void *gfs2_glockfd_seq_start(struct seq_file *seq, loff_t *pos)
{
struct gfs2_glockfd_iter *i = seq->private;
if (*pos)
return NULL;
while (gfs2_glockfd_next_task(i)) {
if (gfs2_glockfd_next_file(i))
return i;
i->tgid++;
}
return NULL;
}
static void *gfs2_glockfd_seq_next(struct seq_file *seq, void *iter_ptr,
loff_t *pos)
{
struct gfs2_glockfd_iter *i = seq->private;
(*pos)++;
i->fd++;
do {
if (gfs2_glockfd_next_file(i))
return i;
i->tgid++;
} while (gfs2_glockfd_next_task(i));
return NULL;
}
static void gfs2_glockfd_seq_stop(struct seq_file *seq, void *iter_ptr)
{
struct gfs2_glockfd_iter *i = seq->private;
if (i->file)
fput(i->file);
if (i->task)
put_task_struct(i->task);
}
static void gfs2_glockfd_seq_show_flock(struct seq_file *seq,
struct gfs2_glockfd_iter *i)
{
struct gfs2_file *fp = i->file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
struct lm_lockname gl_name = { .ln_type = LM_TYPE_RESERVED };
if (!READ_ONCE(fl_gh->gh_gl))
return;
spin_lock(&i->file->f_lock);
if (gfs2_holder_initialized(fl_gh))
gl_name = fl_gh->gh_gl->gl_name;
spin_unlock(&i->file->f_lock);
if (gl_name.ln_type != LM_TYPE_RESERVED) {
seq_printf(seq, "%d %u %u/%llx\n",
i->tgid, i->fd, gl_name.ln_type,
(unsigned long long)gl_name.ln_number);
}
}
static int gfs2_glockfd_seq_show(struct seq_file *seq, void *iter_ptr)
{
struct gfs2_glockfd_iter *i = seq->private;
struct inode *inode = file_inode(i->file);
struct gfs2_glock *gl;
inode_lock_shared(inode);
gl = GFS2_I(inode)->i_iopen_gh.gh_gl;
if (gl) {
seq_printf(seq, "%d %u %u/%llx\n",
i->tgid, i->fd, gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number);
}
gfs2_glockfd_seq_show_flock(seq, i);
inode_unlock_shared(inode);
return 0;
}
static const struct seq_operations gfs2_glockfd_seq_ops = {
.start = gfs2_glockfd_seq_start,
.next = gfs2_glockfd_seq_next,
.stop = gfs2_glockfd_seq_stop,
.show = gfs2_glockfd_seq_show,
};
static int gfs2_glockfd_open(struct inode *inode, struct file *file)
{
struct gfs2_glockfd_iter *i;
struct gfs2_sbd *sdp = inode->i_private;
i = __seq_open_private(file, &gfs2_glockfd_seq_ops,
sizeof(struct gfs2_glockfd_iter));
if (!i)
return -ENOMEM;
i->sb = sdp->sd_vfs;
return 0;
}
static const struct file_operations gfs2_glockfd_fops = {
.owner = THIS_MODULE,
.open = gfs2_glockfd_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
DEFINE_SEQ_ATTRIBUTE(gfs2_sbstats);
void gfs2_create_debugfs_file(struct gfs2_sbd *sdp)
{
sdp->debugfs_dir = debugfs_create_dir(sdp->sd_table_name, gfs2_root);
debugfs_create_file("glocks", S_IFREG | S_IRUGO, sdp->debugfs_dir, sdp,
&gfs2_glocks_fops);
debugfs_create_file("glockfd", S_IFREG | S_IRUGO, sdp->debugfs_dir, sdp,
&gfs2_glockfd_fops);
debugfs_create_file("glstats", S_IFREG | S_IRUGO, sdp->debugfs_dir, sdp,
&gfs2_glstats_fops);
debugfs_create_file("sbstats", S_IFREG | S_IRUGO, sdp->debugfs_dir, sdp,
&gfs2_sbstats_fops);
}
void gfs2_delete_debugfs_file(struct gfs2_sbd *sdp)
{
debugfs_remove_recursive(sdp->debugfs_dir);
sdp->debugfs_dir = NULL;
}
void gfs2_register_debugfs(void)
{
gfs2_root = debugfs_create_dir("gfs2", NULL);
}
void gfs2_unregister_debugfs(void)
{
debugfs_remove(gfs2_root);
gfs2_root = NULL;
}
| linux-master | fs/gfs2/glock.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
/*
* Implements Extendible Hashing as described in:
* "Extendible Hashing" by Fagin, et al in
* __ACM Trans. on Database Systems__, Sept 1979.
*
*
* Here's the layout of dirents which is essentially the same as that of ext2
* within a single block. The field de_name_len is the number of bytes
* actually required for the name (no null terminator). The field de_rec_len
* is the number of bytes allocated to the dirent. The offset of the next
* dirent in the block is (dirent + dirent->de_rec_len). When a dirent is
* deleted, the preceding dirent inherits its allocated space, ie
* prev->de_rec_len += deleted->de_rec_len. Since the next dirent is obtained
* by adding de_rec_len to the current dirent, this essentially causes the
* deleted dirent to get jumped over when iterating through all the dirents.
*
* When deleting the first dirent in a block, there is no previous dirent so
* the field de_ino is set to zero to designate it as deleted. When allocating
* a dirent, gfs2_dirent_alloc iterates through the dirents in a block. If the
* first dirent has (de_ino == 0) and de_rec_len is large enough, this first
* dirent is allocated. Otherwise it must go through all the 'used' dirents
* searching for one in which the amount of total space minus the amount of
* used space will provide enough space for the new dirent.
*
* There are two types of blocks in which dirents reside. In a stuffed dinode,
* the dirents begin at offset sizeof(struct gfs2_dinode) from the beginning of
* the block. In leaves, they begin at offset sizeof(struct gfs2_leaf) from the
* beginning of the leaf block. The dirents reside in leaves when
*
* dip->i_diskflags & GFS2_DIF_EXHASH is true
*
* Otherwise, the dirents are "linear", within a single stuffed dinode block.
*
* When the dirents are in leaves, the actual contents of the directory file are
* used as an array of 64-bit block pointers pointing to the leaf blocks. The
* dirents are NOT in the directory file itself. There can be more than one
* block pointer in the array that points to the same leaf. In fact, when a
* directory is first converted from linear to exhash, all of the pointers
* point to the same leaf.
*
* When a leaf is completely full, the size of the hash table can be
* doubled unless it is already at the maximum size which is hard coded into
* GFS2_DIR_MAX_DEPTH. After that, leaves are chained together in a linked list,
* but never before the maximum hash table size has been reached.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/buffer_head.h>
#include <linux/sort.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/vmalloc.h>
#include <linux/bio.h>
#include "gfs2.h"
#include "incore.h"
#include "dir.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "bmap.h"
#include "util.h"
#define MAX_RA_BLOCKS 32 /* max read-ahead blocks */
#define gfs2_disk_hash2offset(h) (((u64)(h)) >> 1)
#define gfs2_dir_offset2hash(p) ((u32)(((u64)(p)) << 1))
#define GFS2_HASH_INDEX_MASK 0xffffc000
#define GFS2_USE_HASH_FLAG 0x2000
struct qstr gfs2_qdot __read_mostly;
struct qstr gfs2_qdotdot __read_mostly;
typedef int (*gfs2_dscan_t)(const struct gfs2_dirent *dent,
const struct qstr *name, void *opaque);
int gfs2_dir_get_new_buffer(struct gfs2_inode *ip, u64 block,
struct buffer_head **bhp)
{
struct buffer_head *bh;
bh = gfs2_meta_new(ip->i_gl, block);
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_metatype_set(bh, GFS2_METATYPE_JD, GFS2_FORMAT_JD);
gfs2_buffer_clear_tail(bh, sizeof(struct gfs2_meta_header));
*bhp = bh;
return 0;
}
static int gfs2_dir_get_existing_buffer(struct gfs2_inode *ip, u64 block,
struct buffer_head **bhp)
{
struct buffer_head *bh;
int error;
error = gfs2_meta_read(ip->i_gl, block, DIO_WAIT, 0, &bh);
if (error)
return error;
if (gfs2_metatype_check(GFS2_SB(&ip->i_inode), bh, GFS2_METATYPE_JD)) {
brelse(bh);
return -EIO;
}
*bhp = bh;
return 0;
}
static int gfs2_dir_write_stuffed(struct gfs2_inode *ip, const char *buf,
unsigned int offset, unsigned int size)
{
struct buffer_head *dibh;
int error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
gfs2_trans_add_meta(ip->i_gl, dibh);
memcpy(dibh->b_data + offset + sizeof(struct gfs2_dinode), buf, size);
if (ip->i_inode.i_size < offset + size)
i_size_write(&ip->i_inode, offset + size);
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
return size;
}
/**
* gfs2_dir_write_data - Write directory information to the inode
* @ip: The GFS2 inode
* @buf: The buffer containing information to be written
* @offset: The file offset to start writing at
* @size: The amount of data to write
*
* Returns: The number of bytes correctly written or error code
*/
static int gfs2_dir_write_data(struct gfs2_inode *ip, const char *buf,
u64 offset, unsigned int size)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *dibh;
u64 lblock, dblock;
u32 extlen = 0;
unsigned int o;
int copied = 0;
int error = 0;
bool new = false;
if (!size)
return 0;
if (gfs2_is_stuffed(ip) && offset + size <= gfs2_max_stuffed_size(ip))
return gfs2_dir_write_stuffed(ip, buf, (unsigned int)offset,
size);
if (gfs2_assert_warn(sdp, gfs2_is_jdata(ip)))
return -EINVAL;
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip);
if (error)
return error;
}
lblock = offset;
o = do_div(lblock, sdp->sd_jbsize) + sizeof(struct gfs2_meta_header);
while (copied < size) {
unsigned int amount;
struct buffer_head *bh;
amount = size - copied;
if (amount > sdp->sd_sb.sb_bsize - o)
amount = sdp->sd_sb.sb_bsize - o;
if (!extlen) {
extlen = 1;
error = gfs2_alloc_extent(&ip->i_inode, lblock, &dblock,
&extlen, &new);
if (error)
goto fail;
error = -EIO;
if (gfs2_assert_withdraw(sdp, dblock))
goto fail;
}
if (amount == sdp->sd_jbsize || new)
error = gfs2_dir_get_new_buffer(ip, dblock, &bh);
else
error = gfs2_dir_get_existing_buffer(ip, dblock, &bh);
if (error)
goto fail;
gfs2_trans_add_meta(ip->i_gl, bh);
memcpy(bh->b_data + o, buf, amount);
brelse(bh);
buf += amount;
copied += amount;
lblock++;
dblock++;
extlen--;
o = sizeof(struct gfs2_meta_header);
}
out:
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
if (ip->i_inode.i_size < offset + copied)
i_size_write(&ip->i_inode, offset + copied);
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
return copied;
fail:
if (copied)
goto out;
return error;
}
static int gfs2_dir_read_stuffed(struct gfs2_inode *ip, __be64 *buf,
unsigned int size)
{
struct buffer_head *dibh;
int error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (!error) {
memcpy(buf, dibh->b_data + sizeof(struct gfs2_dinode), size);
brelse(dibh);
}
return (error) ? error : size;
}
/**
* gfs2_dir_read_data - Read a data from a directory inode
* @ip: The GFS2 Inode
* @buf: The buffer to place result into
* @size: Amount of data to transfer
*
* Returns: The amount of data actually copied or the error
*/
static int gfs2_dir_read_data(struct gfs2_inode *ip, __be64 *buf,
unsigned int size)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
u64 lblock, dblock;
u32 extlen = 0;
unsigned int o;
int copied = 0;
int error = 0;
if (gfs2_is_stuffed(ip))
return gfs2_dir_read_stuffed(ip, buf, size);
if (gfs2_assert_warn(sdp, gfs2_is_jdata(ip)))
return -EINVAL;
lblock = 0;
o = do_div(lblock, sdp->sd_jbsize) + sizeof(struct gfs2_meta_header);
while (copied < size) {
unsigned int amount;
struct buffer_head *bh;
amount = size - copied;
if (amount > sdp->sd_sb.sb_bsize - o)
amount = sdp->sd_sb.sb_bsize - o;
if (!extlen) {
extlen = 32;
error = gfs2_get_extent(&ip->i_inode, lblock,
&dblock, &extlen);
if (error || !dblock)
goto fail;
BUG_ON(extlen < 1);
bh = gfs2_meta_ra(ip->i_gl, dblock, extlen);
} else {
error = gfs2_meta_read(ip->i_gl, dblock, DIO_WAIT, 0, &bh);
if (error)
goto fail;
}
error = gfs2_metatype_check(sdp, bh, GFS2_METATYPE_JD);
if (error) {
brelse(bh);
goto fail;
}
dblock++;
extlen--;
memcpy(buf, bh->b_data + o, amount);
brelse(bh);
buf += (amount/sizeof(__be64));
copied += amount;
lblock++;
o = sizeof(struct gfs2_meta_header);
}
return copied;
fail:
return (copied) ? copied : error;
}
/**
* gfs2_dir_get_hash_table - Get pointer to the dir hash table
* @ip: The inode in question
*
* Returns: The hash table or an error
*/
static __be64 *gfs2_dir_get_hash_table(struct gfs2_inode *ip)
{
struct inode *inode = &ip->i_inode;
int ret;
u32 hsize;
__be64 *hc;
BUG_ON(!(ip->i_diskflags & GFS2_DIF_EXHASH));
hc = ip->i_hash_cache;
if (hc)
return hc;
hsize = BIT(ip->i_depth);
hsize *= sizeof(__be64);
if (hsize != i_size_read(&ip->i_inode)) {
gfs2_consist_inode(ip);
return ERR_PTR(-EIO);
}
hc = kmalloc(hsize, GFP_NOFS | __GFP_NOWARN);
if (hc == NULL)
hc = __vmalloc(hsize, GFP_NOFS);
if (hc == NULL)
return ERR_PTR(-ENOMEM);
ret = gfs2_dir_read_data(ip, hc, hsize);
if (ret < 0) {
kvfree(hc);
return ERR_PTR(ret);
}
spin_lock(&inode->i_lock);
if (likely(!ip->i_hash_cache)) {
ip->i_hash_cache = hc;
hc = NULL;
}
spin_unlock(&inode->i_lock);
kvfree(hc);
return ip->i_hash_cache;
}
/**
* gfs2_dir_hash_inval - Invalidate dir hash
* @ip: The directory inode
*
* Must be called with an exclusive glock, or during glock invalidation.
*/
void gfs2_dir_hash_inval(struct gfs2_inode *ip)
{
__be64 *hc;
spin_lock(&ip->i_inode.i_lock);
hc = ip->i_hash_cache;
ip->i_hash_cache = NULL;
spin_unlock(&ip->i_inode.i_lock);
kvfree(hc);
}
static inline int gfs2_dirent_sentinel(const struct gfs2_dirent *dent)
{
return dent->de_inum.no_addr == 0 || dent->de_inum.no_formal_ino == 0;
}
static inline int __gfs2_dirent_find(const struct gfs2_dirent *dent,
const struct qstr *name, int ret)
{
if (!gfs2_dirent_sentinel(dent) &&
be32_to_cpu(dent->de_hash) == name->hash &&
be16_to_cpu(dent->de_name_len) == name->len &&
memcmp(dent+1, name->name, name->len) == 0)
return ret;
return 0;
}
static int gfs2_dirent_find(const struct gfs2_dirent *dent,
const struct qstr *name,
void *opaque)
{
return __gfs2_dirent_find(dent, name, 1);
}
static int gfs2_dirent_prev(const struct gfs2_dirent *dent,
const struct qstr *name,
void *opaque)
{
return __gfs2_dirent_find(dent, name, 2);
}
/*
* name->name holds ptr to start of block.
* name->len holds size of block.
*/
static int gfs2_dirent_last(const struct gfs2_dirent *dent,
const struct qstr *name,
void *opaque)
{
const char *start = name->name;
const char *end = (const char *)dent + be16_to_cpu(dent->de_rec_len);
if (name->len == (end - start))
return 1;
return 0;
}
/* Look for the dirent that contains the offset specified in data. Once we
* find that dirent, there must be space available there for the new dirent */
static int gfs2_dirent_find_offset(const struct gfs2_dirent *dent,
const struct qstr *name,
void *ptr)
{
unsigned required = GFS2_DIRENT_SIZE(name->len);
unsigned actual = GFS2_DIRENT_SIZE(be16_to_cpu(dent->de_name_len));
unsigned totlen = be16_to_cpu(dent->de_rec_len);
if (ptr < (void *)dent || ptr >= (void *)dent + totlen)
return 0;
if (gfs2_dirent_sentinel(dent))
actual = 0;
if (ptr < (void *)dent + actual)
return -1;
if ((void *)dent + totlen >= ptr + required)
return 1;
return -1;
}
static int gfs2_dirent_find_space(const struct gfs2_dirent *dent,
const struct qstr *name,
void *opaque)
{
unsigned required = GFS2_DIRENT_SIZE(name->len);
unsigned actual = GFS2_DIRENT_SIZE(be16_to_cpu(dent->de_name_len));
unsigned totlen = be16_to_cpu(dent->de_rec_len);
if (gfs2_dirent_sentinel(dent))
actual = 0;
if (totlen - actual >= required)
return 1;
return 0;
}
struct dirent_gather {
const struct gfs2_dirent **pdent;
unsigned offset;
};
static int gfs2_dirent_gather(const struct gfs2_dirent *dent,
const struct qstr *name,
void *opaque)
{
struct dirent_gather *g = opaque;
if (!gfs2_dirent_sentinel(dent)) {
g->pdent[g->offset++] = dent;
}
return 0;
}
/*
* Other possible things to check:
* - Inode located within filesystem size (and on valid block)
* - Valid directory entry type
* Not sure how heavy-weight we want to make this... could also check
* hash is correct for example, but that would take a lot of extra time.
* For now the most important thing is to check that the various sizes
* are correct.
*/
static int gfs2_check_dirent(struct gfs2_sbd *sdp,
struct gfs2_dirent *dent, unsigned int offset,
unsigned int size, unsigned int len, int first)
{
const char *msg = "gfs2_dirent too small";
if (unlikely(size < sizeof(struct gfs2_dirent)))
goto error;
msg = "gfs2_dirent misaligned";
if (unlikely(offset & 0x7))
goto error;
msg = "gfs2_dirent points beyond end of block";
if (unlikely(offset + size > len))
goto error;
msg = "zero inode number";
if (unlikely(!first && gfs2_dirent_sentinel(dent)))
goto error;
msg = "name length is greater than space in dirent";
if (!gfs2_dirent_sentinel(dent) &&
unlikely(sizeof(struct gfs2_dirent)+be16_to_cpu(dent->de_name_len) >
size))
goto error;
return 0;
error:
fs_warn(sdp, "%s: %s (%s)\n",
__func__, msg, first ? "first in block" : "not first in block");
return -EIO;
}
static int gfs2_dirent_offset(struct gfs2_sbd *sdp, const void *buf)
{
const struct gfs2_meta_header *h = buf;
int offset;
BUG_ON(buf == NULL);
switch(be32_to_cpu(h->mh_type)) {
case GFS2_METATYPE_LF:
offset = sizeof(struct gfs2_leaf);
break;
case GFS2_METATYPE_DI:
offset = sizeof(struct gfs2_dinode);
break;
default:
goto wrong_type;
}
return offset;
wrong_type:
fs_warn(sdp, "%s: wrong block type %u\n", __func__,
be32_to_cpu(h->mh_type));
return -1;
}
static struct gfs2_dirent *gfs2_dirent_scan(struct inode *inode, void *buf,
unsigned int len, gfs2_dscan_t scan,
const struct qstr *name,
void *opaque)
{
struct gfs2_dirent *dent, *prev;
unsigned offset;
unsigned size;
int ret = 0;
ret = gfs2_dirent_offset(GFS2_SB(inode), buf);
if (ret < 0)
goto consist_inode;
offset = ret;
prev = NULL;
dent = buf + offset;
size = be16_to_cpu(dent->de_rec_len);
if (gfs2_check_dirent(GFS2_SB(inode), dent, offset, size, len, 1))
goto consist_inode;
do {
ret = scan(dent, name, opaque);
if (ret)
break;
offset += size;
if (offset == len)
break;
prev = dent;
dent = buf + offset;
size = be16_to_cpu(dent->de_rec_len);
if (gfs2_check_dirent(GFS2_SB(inode), dent, offset, size,
len, 0))
goto consist_inode;
} while(1);
switch(ret) {
case 0:
return NULL;
case 1:
return dent;
case 2:
return prev ? prev : dent;
default:
BUG_ON(ret > 0);
return ERR_PTR(ret);
}
consist_inode:
gfs2_consist_inode(GFS2_I(inode));
return ERR_PTR(-EIO);
}
static int dirent_check_reclen(struct gfs2_inode *dip,
const struct gfs2_dirent *d, const void *end_p)
{
const void *ptr = d;
u16 rec_len = be16_to_cpu(d->de_rec_len);
if (unlikely(rec_len < sizeof(struct gfs2_dirent)))
goto broken;
ptr += rec_len;
if (ptr < end_p)
return rec_len;
if (ptr == end_p)
return -ENOENT;
broken:
gfs2_consist_inode(dip);
return -EIO;
}
/**
* dirent_next - Next dirent
* @dip: the directory
* @bh: The buffer
* @dent: Pointer to list of dirents
*
* Returns: 0 on success, error code otherwise
*/
static int dirent_next(struct gfs2_inode *dip, struct buffer_head *bh,
struct gfs2_dirent **dent)
{
struct gfs2_dirent *cur = *dent, *tmp;
char *bh_end = bh->b_data + bh->b_size;
int ret;
ret = dirent_check_reclen(dip, cur, bh_end);
if (ret < 0)
return ret;
tmp = (void *)cur + ret;
ret = dirent_check_reclen(dip, tmp, bh_end);
if (ret == -EIO)
return ret;
/* Only the first dent could ever have de_inum.no_addr == 0 */
if (gfs2_dirent_sentinel(tmp)) {
gfs2_consist_inode(dip);
return -EIO;
}
*dent = tmp;
return 0;
}
/**
* dirent_del - Delete a dirent
* @dip: The GFS2 inode
* @bh: The buffer
* @prev: The previous dirent
* @cur: The current dirent
*
*/
static void dirent_del(struct gfs2_inode *dip, struct buffer_head *bh,
struct gfs2_dirent *prev, struct gfs2_dirent *cur)
{
u16 cur_rec_len, prev_rec_len;
if (gfs2_dirent_sentinel(cur)) {
gfs2_consist_inode(dip);
return;
}
gfs2_trans_add_meta(dip->i_gl, bh);
/* If there is no prev entry, this is the first entry in the block.
The de_rec_len is already as big as it needs to be. Just zero
out the inode number and return. */
if (!prev) {
cur->de_inum.no_addr = 0;
cur->de_inum.no_formal_ino = 0;
return;
}
/* Combine this dentry with the previous one. */
prev_rec_len = be16_to_cpu(prev->de_rec_len);
cur_rec_len = be16_to_cpu(cur->de_rec_len);
if ((char *)prev + prev_rec_len != (char *)cur)
gfs2_consist_inode(dip);
if ((char *)cur + cur_rec_len > bh->b_data + bh->b_size)
gfs2_consist_inode(dip);
prev_rec_len += cur_rec_len;
prev->de_rec_len = cpu_to_be16(prev_rec_len);
}
static struct gfs2_dirent *do_init_dirent(struct inode *inode,
struct gfs2_dirent *dent,
const struct qstr *name,
struct buffer_head *bh,
unsigned offset)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_dirent *ndent;
unsigned totlen;
totlen = be16_to_cpu(dent->de_rec_len);
BUG_ON(offset + name->len > totlen);
gfs2_trans_add_meta(ip->i_gl, bh);
ndent = (struct gfs2_dirent *)((char *)dent + offset);
dent->de_rec_len = cpu_to_be16(offset);
gfs2_qstr2dirent(name, totlen - offset, ndent);
return ndent;
}
/*
* Takes a dent from which to grab space as an argument. Returns the
* newly created dent.
*/
static struct gfs2_dirent *gfs2_init_dirent(struct inode *inode,
struct gfs2_dirent *dent,
const struct qstr *name,
struct buffer_head *bh)
{
unsigned offset = 0;
if (!gfs2_dirent_sentinel(dent))
offset = GFS2_DIRENT_SIZE(be16_to_cpu(dent->de_name_len));
return do_init_dirent(inode, dent, name, bh, offset);
}
static struct gfs2_dirent *gfs2_dirent_split_alloc(struct inode *inode,
struct buffer_head *bh,
const struct qstr *name,
void *ptr)
{
struct gfs2_dirent *dent;
dent = gfs2_dirent_scan(inode, bh->b_data, bh->b_size,
gfs2_dirent_find_offset, name, ptr);
if (IS_ERR_OR_NULL(dent))
return dent;
return do_init_dirent(inode, dent, name, bh,
(unsigned)(ptr - (void *)dent));
}
static int get_leaf(struct gfs2_inode *dip, u64 leaf_no,
struct buffer_head **bhp)
{
int error;
error = gfs2_meta_read(dip->i_gl, leaf_no, DIO_WAIT, 0, bhp);
if (!error && gfs2_metatype_check(GFS2_SB(&dip->i_inode), *bhp, GFS2_METATYPE_LF)) {
/* pr_info("block num=%llu\n", leaf_no); */
error = -EIO;
}
return error;
}
/**
* get_leaf_nr - Get a leaf number associated with the index
* @dip: The GFS2 inode
* @index: hash table index of the targeted leaf
* @leaf_out: Resulting leaf block number
*
* Returns: 0 on success, error code otherwise
*/
static int get_leaf_nr(struct gfs2_inode *dip, u32 index, u64 *leaf_out)
{
__be64 *hash;
int error;
hash = gfs2_dir_get_hash_table(dip);
error = PTR_ERR_OR_ZERO(hash);
if (!error)
*leaf_out = be64_to_cpu(*(hash + index));
return error;
}
static int get_first_leaf(struct gfs2_inode *dip, u32 index,
struct buffer_head **bh_out)
{
u64 leaf_no;
int error;
error = get_leaf_nr(dip, index, &leaf_no);
if (!error)
error = get_leaf(dip, leaf_no, bh_out);
return error;
}
static struct gfs2_dirent *gfs2_dirent_search(struct inode *inode,
const struct qstr *name,
gfs2_dscan_t scan,
struct buffer_head **pbh)
{
struct buffer_head *bh;
struct gfs2_dirent *dent;
struct gfs2_inode *ip = GFS2_I(inode);
int error;
if (ip->i_diskflags & GFS2_DIF_EXHASH) {
struct gfs2_leaf *leaf;
unsigned int hsize = BIT(ip->i_depth);
unsigned int index;
u64 ln;
if (hsize * sizeof(u64) != i_size_read(inode)) {
gfs2_consist_inode(ip);
return ERR_PTR(-EIO);
}
index = name->hash >> (32 - ip->i_depth);
error = get_first_leaf(ip, index, &bh);
if (error)
return ERR_PTR(error);
do {
dent = gfs2_dirent_scan(inode, bh->b_data, bh->b_size,
scan, name, NULL);
if (dent)
goto got_dent;
leaf = (struct gfs2_leaf *)bh->b_data;
ln = be64_to_cpu(leaf->lf_next);
brelse(bh);
if (!ln)
break;
error = get_leaf(ip, ln, &bh);
} while(!error);
return error ? ERR_PTR(error) : NULL;
}
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
return ERR_PTR(error);
dent = gfs2_dirent_scan(inode, bh->b_data, bh->b_size, scan, name, NULL);
got_dent:
if (IS_ERR_OR_NULL(dent)) {
brelse(bh);
bh = NULL;
}
*pbh = bh;
return dent;
}
static struct gfs2_leaf *new_leaf(struct inode *inode, struct buffer_head **pbh, u16 depth)
{
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int n = 1;
u64 bn;
int error;
struct buffer_head *bh;
struct gfs2_leaf *leaf;
struct gfs2_dirent *dent;
struct timespec64 tv = current_time(inode);
error = gfs2_alloc_blocks(ip, &bn, &n, 0, NULL);
if (error)
return NULL;
bh = gfs2_meta_new(ip->i_gl, bn);
if (!bh)
return NULL;
gfs2_trans_remove_revoke(GFS2_SB(inode), bn, 1);
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_metatype_set(bh, GFS2_METATYPE_LF, GFS2_FORMAT_LF);
leaf = (struct gfs2_leaf *)bh->b_data;
leaf->lf_depth = cpu_to_be16(depth);
leaf->lf_entries = 0;
leaf->lf_dirent_format = cpu_to_be32(GFS2_FORMAT_DE);
leaf->lf_next = 0;
leaf->lf_inode = cpu_to_be64(ip->i_no_addr);
leaf->lf_dist = cpu_to_be32(1);
leaf->lf_nsec = cpu_to_be32(tv.tv_nsec);
leaf->lf_sec = cpu_to_be64(tv.tv_sec);
memset(leaf->lf_reserved2, 0, sizeof(leaf->lf_reserved2));
dent = (struct gfs2_dirent *)(leaf+1);
gfs2_qstr2dirent(&empty_name, bh->b_size - sizeof(struct gfs2_leaf), dent);
*pbh = bh;
return leaf;
}
/**
* dir_make_exhash - Convert a stuffed directory into an ExHash directory
* @inode: The directory inode to be converted to exhash
*
* Returns: 0 on success, error code otherwise
*/
static int dir_make_exhash(struct inode *inode)
{
struct gfs2_inode *dip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_dirent *dent;
struct qstr args;
struct buffer_head *bh, *dibh;
struct gfs2_leaf *leaf;
int y;
u32 x;
__be64 *lp;
u64 bn;
int error;
error = gfs2_meta_inode_buffer(dip, &dibh);
if (error)
return error;
/* Turn over a new leaf */
leaf = new_leaf(inode, &bh, 0);
if (!leaf)
return -ENOSPC;
bn = bh->b_blocknr;
gfs2_assert(sdp, dip->i_entries < BIT(16));
leaf->lf_entries = cpu_to_be16(dip->i_entries);
/* Copy dirents */
gfs2_buffer_copy_tail(bh, sizeof(struct gfs2_leaf), dibh,
sizeof(struct gfs2_dinode));
/* Find last entry */
x = 0;
args.len = bh->b_size - sizeof(struct gfs2_dinode) +
sizeof(struct gfs2_leaf);
args.name = bh->b_data;
dent = gfs2_dirent_scan(&dip->i_inode, bh->b_data, bh->b_size,
gfs2_dirent_last, &args, NULL);
if (!dent) {
brelse(bh);
brelse(dibh);
return -EIO;
}
if (IS_ERR(dent)) {
brelse(bh);
brelse(dibh);
return PTR_ERR(dent);
}
/* Adjust the last dirent's record length
(Remember that dent still points to the last entry.) */
dent->de_rec_len = cpu_to_be16(be16_to_cpu(dent->de_rec_len) +
sizeof(struct gfs2_dinode) -
sizeof(struct gfs2_leaf));
brelse(bh);
/* We're done with the new leaf block, now setup the new
hash table. */
gfs2_trans_add_meta(dip->i_gl, dibh);
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
lp = (__be64 *)(dibh->b_data + sizeof(struct gfs2_dinode));
for (x = sdp->sd_hash_ptrs; x--; lp++)
*lp = cpu_to_be64(bn);
i_size_write(inode, sdp->sd_sb.sb_bsize / 2);
gfs2_add_inode_blocks(&dip->i_inode, 1);
dip->i_diskflags |= GFS2_DIF_EXHASH;
for (x = sdp->sd_hash_ptrs, y = -1; x; x >>= 1, y++) ;
dip->i_depth = y;
gfs2_dinode_out(dip, dibh->b_data);
brelse(dibh);
return 0;
}
/**
* dir_split_leaf - Split a leaf block into two
* @inode: The directory inode to be split
* @name: name of the dirent we're trying to insert
*
* Returns: 0 on success, error code on failure
*/
static int dir_split_leaf(struct inode *inode, const struct qstr *name)
{
struct gfs2_inode *dip = GFS2_I(inode);
struct buffer_head *nbh, *obh, *dibh;
struct gfs2_leaf *nleaf, *oleaf;
struct gfs2_dirent *dent = NULL, *prev = NULL, *next = NULL, *new;
u32 start, len, half_len, divider;
u64 bn, leaf_no;
__be64 *lp;
u32 index;
int x;
int error;
index = name->hash >> (32 - dip->i_depth);
error = get_leaf_nr(dip, index, &leaf_no);
if (error)
return error;
/* Get the old leaf block */
error = get_leaf(dip, leaf_no, &obh);
if (error)
return error;
oleaf = (struct gfs2_leaf *)obh->b_data;
if (dip->i_depth == be16_to_cpu(oleaf->lf_depth)) {
brelse(obh);
return 1; /* can't split */
}
gfs2_trans_add_meta(dip->i_gl, obh);
nleaf = new_leaf(inode, &nbh, be16_to_cpu(oleaf->lf_depth) + 1);
if (!nleaf) {
brelse(obh);
return -ENOSPC;
}
bn = nbh->b_blocknr;
/* Compute the start and len of leaf pointers in the hash table. */
len = BIT(dip->i_depth - be16_to_cpu(oleaf->lf_depth));
half_len = len >> 1;
if (!half_len) {
fs_warn(GFS2_SB(inode), "i_depth %u lf_depth %u index %u\n",
dip->i_depth, be16_to_cpu(oleaf->lf_depth), index);
gfs2_consist_inode(dip);
error = -EIO;
goto fail_brelse;
}
start = (index & ~(len - 1));
/* Change the pointers.
Don't bother distinguishing stuffed from non-stuffed.
This code is complicated enough already. */
lp = kmalloc_array(half_len, sizeof(__be64), GFP_NOFS);
if (!lp) {
error = -ENOMEM;
goto fail_brelse;
}
/* Change the pointers */
for (x = 0; x < half_len; x++)
lp[x] = cpu_to_be64(bn);
gfs2_dir_hash_inval(dip);
error = gfs2_dir_write_data(dip, (char *)lp, start * sizeof(u64),
half_len * sizeof(u64));
if (error != half_len * sizeof(u64)) {
if (error >= 0)
error = -EIO;
goto fail_lpfree;
}
kfree(lp);
/* Compute the divider */
divider = (start + half_len) << (32 - dip->i_depth);
/* Copy the entries */
dent = (struct gfs2_dirent *)(obh->b_data + sizeof(struct gfs2_leaf));
do {
next = dent;
if (dirent_next(dip, obh, &next))
next = NULL;
if (!gfs2_dirent_sentinel(dent) &&
be32_to_cpu(dent->de_hash) < divider) {
struct qstr str;
void *ptr = ((char *)dent - obh->b_data) + nbh->b_data;
str.name = (char*)(dent+1);
str.len = be16_to_cpu(dent->de_name_len);
str.hash = be32_to_cpu(dent->de_hash);
new = gfs2_dirent_split_alloc(inode, nbh, &str, ptr);
if (IS_ERR(new)) {
error = PTR_ERR(new);
break;
}
new->de_inum = dent->de_inum; /* No endian worries */
new->de_type = dent->de_type; /* No endian worries */
be16_add_cpu(&nleaf->lf_entries, 1);
dirent_del(dip, obh, prev, dent);
if (!oleaf->lf_entries)
gfs2_consist_inode(dip);
be16_add_cpu(&oleaf->lf_entries, -1);
if (!prev)
prev = dent;
} else {
prev = dent;
}
dent = next;
} while (dent);
oleaf->lf_depth = nleaf->lf_depth;
error = gfs2_meta_inode_buffer(dip, &dibh);
if (!gfs2_assert_withdraw(GFS2_SB(&dip->i_inode), !error)) {
gfs2_trans_add_meta(dip->i_gl, dibh);
gfs2_add_inode_blocks(&dip->i_inode, 1);
gfs2_dinode_out(dip, dibh->b_data);
brelse(dibh);
}
brelse(obh);
brelse(nbh);
return error;
fail_lpfree:
kfree(lp);
fail_brelse:
brelse(obh);
brelse(nbh);
return error;
}
/**
* dir_double_exhash - Double size of ExHash table
* @dip: The GFS2 dinode
*
* Returns: 0 on success, error code on failure
*/
static int dir_double_exhash(struct gfs2_inode *dip)
{
struct buffer_head *dibh;
u32 hsize;
u32 hsize_bytes;
__be64 *hc;
__be64 *hc2, *h;
int x;
int error = 0;
hsize = BIT(dip->i_depth);
hsize_bytes = hsize * sizeof(__be64);
hc = gfs2_dir_get_hash_table(dip);
if (IS_ERR(hc))
return PTR_ERR(hc);
hc2 = kmalloc_array(hsize_bytes, 2, GFP_NOFS | __GFP_NOWARN);
if (hc2 == NULL)
hc2 = __vmalloc(hsize_bytes * 2, GFP_NOFS);
if (!hc2)
return -ENOMEM;
h = hc2;
error = gfs2_meta_inode_buffer(dip, &dibh);
if (error)
goto out_kfree;
for (x = 0; x < hsize; x++) {
*h++ = *hc;
*h++ = *hc;
hc++;
}
error = gfs2_dir_write_data(dip, (char *)hc2, 0, hsize_bytes * 2);
if (error != (hsize_bytes * 2))
goto fail;
gfs2_dir_hash_inval(dip);
dip->i_hash_cache = hc2;
dip->i_depth++;
gfs2_dinode_out(dip, dibh->b_data);
brelse(dibh);
return 0;
fail:
/* Replace original hash table & size */
gfs2_dir_write_data(dip, (char *)hc, 0, hsize_bytes);
i_size_write(&dip->i_inode, hsize_bytes);
gfs2_dinode_out(dip, dibh->b_data);
brelse(dibh);
out_kfree:
kvfree(hc2);
return error;
}
/**
* compare_dents - compare directory entries by hash value
* @a: first dent
* @b: second dent
*
* When comparing the hash entries of @a to @b:
* gt: returns 1
* lt: returns -1
* eq: returns 0
*/
static int compare_dents(const void *a, const void *b)
{
const struct gfs2_dirent *dent_a, *dent_b;
u32 hash_a, hash_b;
int ret = 0;
dent_a = *(const struct gfs2_dirent **)a;
hash_a = dent_a->de_cookie;
dent_b = *(const struct gfs2_dirent **)b;
hash_b = dent_b->de_cookie;
if (hash_a > hash_b)
ret = 1;
else if (hash_a < hash_b)
ret = -1;
else {
unsigned int len_a = be16_to_cpu(dent_a->de_name_len);
unsigned int len_b = be16_to_cpu(dent_b->de_name_len);
if (len_a > len_b)
ret = 1;
else if (len_a < len_b)
ret = -1;
else
ret = memcmp(dent_a + 1, dent_b + 1, len_a);
}
return ret;
}
/**
* do_filldir_main - read out directory entries
* @dip: The GFS2 inode
* @ctx: what to feed the entries to
* @darr: an array of struct gfs2_dirent pointers to read
* @entries: the number of entries in darr
* @sort_start: index of the directory array to start our sort
* @copied: pointer to int that's non-zero if a entry has been copied out
*
* Jump through some hoops to make sure that if there are hash collsions,
* they are read out at the beginning of a buffer. We want to minimize
* the possibility that they will fall into different readdir buffers or
* that someone will want to seek to that location.
*
* Returns: errno, >0 if the actor tells you to stop
*/
static int do_filldir_main(struct gfs2_inode *dip, struct dir_context *ctx,
struct gfs2_dirent **darr, u32 entries,
u32 sort_start, int *copied)
{
const struct gfs2_dirent *dent, *dent_next;
u64 off, off_next;
unsigned int x, y;
int run = 0;
if (sort_start < entries)
sort(&darr[sort_start], entries - sort_start,
sizeof(struct gfs2_dirent *), compare_dents, NULL);
dent_next = darr[0];
off_next = dent_next->de_cookie;
for (x = 0, y = 1; x < entries; x++, y++) {
dent = dent_next;
off = off_next;
if (y < entries) {
dent_next = darr[y];
off_next = dent_next->de_cookie;
if (off < ctx->pos)
continue;
ctx->pos = off;
if (off_next == off) {
if (*copied && !run)
return 1;
run = 1;
} else
run = 0;
} else {
if (off < ctx->pos)
continue;
ctx->pos = off;
}
if (!dir_emit(ctx, (const char *)(dent + 1),
be16_to_cpu(dent->de_name_len),
be64_to_cpu(dent->de_inum.no_addr),
be16_to_cpu(dent->de_type)))
return 1;
*copied = 1;
}
/* Increment the ctx->pos by one, so the next time we come into the
do_filldir fxn, we get the next entry instead of the last one in the
current leaf */
ctx->pos++;
return 0;
}
static void *gfs2_alloc_sort_buffer(unsigned size)
{
void *ptr = NULL;
if (size < KMALLOC_MAX_SIZE)
ptr = kmalloc(size, GFP_NOFS | __GFP_NOWARN);
if (!ptr)
ptr = __vmalloc(size, GFP_NOFS);
return ptr;
}
static int gfs2_set_cookies(struct gfs2_sbd *sdp, struct buffer_head *bh,
unsigned leaf_nr, struct gfs2_dirent **darr,
unsigned entries)
{
int sort_id = -1;
int i;
for (i = 0; i < entries; i++) {
unsigned offset;
darr[i]->de_cookie = be32_to_cpu(darr[i]->de_hash);
darr[i]->de_cookie = gfs2_disk_hash2offset(darr[i]->de_cookie);
if (!sdp->sd_args.ar_loccookie)
continue;
offset = (char *)(darr[i]) -
(bh->b_data + gfs2_dirent_offset(sdp, bh->b_data));
offset /= GFS2_MIN_DIRENT_SIZE;
offset += leaf_nr * sdp->sd_max_dents_per_leaf;
if (offset >= GFS2_USE_HASH_FLAG ||
leaf_nr >= GFS2_USE_HASH_FLAG) {
darr[i]->de_cookie |= GFS2_USE_HASH_FLAG;
if (sort_id < 0)
sort_id = i;
continue;
}
darr[i]->de_cookie &= GFS2_HASH_INDEX_MASK;
darr[i]->de_cookie |= offset;
}
return sort_id;
}
static int gfs2_dir_read_leaf(struct inode *inode, struct dir_context *ctx,
int *copied, unsigned *depth,
u64 leaf_no)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *bh;
struct gfs2_leaf *lf;
unsigned entries = 0, entries2 = 0;
unsigned leaves = 0, leaf = 0, offset, sort_offset;
struct gfs2_dirent **darr, *dent;
struct dirent_gather g;
struct buffer_head **larr;
int error, i, need_sort = 0, sort_id;
u64 lfn = leaf_no;
do {
error = get_leaf(ip, lfn, &bh);
if (error)
goto out;
lf = (struct gfs2_leaf *)bh->b_data;
if (leaves == 0)
*depth = be16_to_cpu(lf->lf_depth);
entries += be16_to_cpu(lf->lf_entries);
leaves++;
lfn = be64_to_cpu(lf->lf_next);
brelse(bh);
} while(lfn);
if (*depth < GFS2_DIR_MAX_DEPTH || !sdp->sd_args.ar_loccookie) {
need_sort = 1;
sort_offset = 0;
}
if (!entries)
return 0;
error = -ENOMEM;
/*
* The extra 99 entries are not normally used, but are a buffer
* zone in case the number of entries in the leaf is corrupt.
* 99 is the maximum number of entries that can fit in a single
* leaf block.
*/
larr = gfs2_alloc_sort_buffer((leaves + entries + 99) * sizeof(void *));
if (!larr)
goto out;
darr = (struct gfs2_dirent **)(larr + leaves);
g.pdent = (const struct gfs2_dirent **)darr;
g.offset = 0;
lfn = leaf_no;
do {
error = get_leaf(ip, lfn, &bh);
if (error)
goto out_free;
lf = (struct gfs2_leaf *)bh->b_data;
lfn = be64_to_cpu(lf->lf_next);
if (lf->lf_entries) {
offset = g.offset;
entries2 += be16_to_cpu(lf->lf_entries);
dent = gfs2_dirent_scan(inode, bh->b_data, bh->b_size,
gfs2_dirent_gather, NULL, &g);
error = PTR_ERR(dent);
if (IS_ERR(dent))
goto out_free;
if (entries2 != g.offset) {
fs_warn(sdp, "Number of entries corrupt in dir "
"leaf %llu, entries2 (%u) != "
"g.offset (%u)\n",
(unsigned long long)bh->b_blocknr,
entries2, g.offset);
gfs2_consist_inode(ip);
error = -EIO;
goto out_free;
}
error = 0;
sort_id = gfs2_set_cookies(sdp, bh, leaf, &darr[offset],
be16_to_cpu(lf->lf_entries));
if (!need_sort && sort_id >= 0) {
need_sort = 1;
sort_offset = offset + sort_id;
}
larr[leaf++] = bh;
} else {
larr[leaf++] = NULL;
brelse(bh);
}
} while(lfn);
BUG_ON(entries2 != entries);
error = do_filldir_main(ip, ctx, darr, entries, need_sort ?
sort_offset : entries, copied);
out_free:
for(i = 0; i < leaf; i++)
brelse(larr[i]);
kvfree(larr);
out:
return error;
}
/**
* gfs2_dir_readahead - Issue read-ahead requests for leaf blocks.
* @inode: the directory inode
* @hsize: hash table size
* @index: index into the hash table
* @f_ra: read-ahead parameters
*
* Note: we can't calculate each index like dir_e_read can because we don't
* have the leaf, and therefore we don't have the depth, and therefore we
* don't have the length. So we have to just read enough ahead to make up
* for the loss of information.
*/
static void gfs2_dir_readahead(struct inode *inode, unsigned hsize, u32 index,
struct file_ra_state *f_ra)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_glock *gl = ip->i_gl;
struct buffer_head *bh;
u64 blocknr = 0, last;
unsigned count;
/* First check if we've already read-ahead for the whole range. */
if (index + MAX_RA_BLOCKS < f_ra->start)
return;
f_ra->start = max((pgoff_t)index, f_ra->start);
for (count = 0; count < MAX_RA_BLOCKS; count++) {
if (f_ra->start >= hsize) /* if exceeded the hash table */
break;
last = blocknr;
blocknr = be64_to_cpu(ip->i_hash_cache[f_ra->start]);
f_ra->start++;
if (blocknr == last)
continue;
bh = gfs2_getbuf(gl, blocknr, 1);
if (trylock_buffer(bh)) {
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
brelse(bh);
continue;
}
bh->b_end_io = end_buffer_read_sync;
submit_bh(REQ_OP_READ | REQ_RAHEAD | REQ_META |
REQ_PRIO, bh);
continue;
}
brelse(bh);
}
}
/**
* dir_e_read - Reads the entries from a directory into a filldir buffer
* @inode: the directory inode
* @ctx: actor to feed the entries to
* @f_ra: read-ahead parameters
*
* Returns: errno
*/
static int dir_e_read(struct inode *inode, struct dir_context *ctx,
struct file_ra_state *f_ra)
{
struct gfs2_inode *dip = GFS2_I(inode);
u32 hsize, len = 0;
u32 hash, index;
__be64 *lp;
int copied = 0;
int error = 0;
unsigned depth = 0;
hsize = BIT(dip->i_depth);
hash = gfs2_dir_offset2hash(ctx->pos);
index = hash >> (32 - dip->i_depth);
if (dip->i_hash_cache == NULL)
f_ra->start = 0;
lp = gfs2_dir_get_hash_table(dip);
if (IS_ERR(lp))
return PTR_ERR(lp);
gfs2_dir_readahead(inode, hsize, index, f_ra);
while (index < hsize) {
error = gfs2_dir_read_leaf(inode, ctx,
&copied, &depth,
be64_to_cpu(lp[index]));
if (error)
break;
len = BIT(dip->i_depth - depth);
index = (index & ~(len - 1)) + len;
}
if (error > 0)
error = 0;
return error;
}
int gfs2_dir_read(struct inode *inode, struct dir_context *ctx,
struct file_ra_state *f_ra)
{
struct gfs2_inode *dip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct dirent_gather g;
struct gfs2_dirent **darr, *dent;
struct buffer_head *dibh;
int copied = 0;
int error;
if (!dip->i_entries)
return 0;
if (dip->i_diskflags & GFS2_DIF_EXHASH)
return dir_e_read(inode, ctx, f_ra);
if (!gfs2_is_stuffed(dip)) {
gfs2_consist_inode(dip);
return -EIO;
}
error = gfs2_meta_inode_buffer(dip, &dibh);
if (error)
return error;
error = -ENOMEM;
/* 96 is max number of dirents which can be stuffed into an inode */
darr = kmalloc_array(96, sizeof(struct gfs2_dirent *), GFP_NOFS);
if (darr) {
g.pdent = (const struct gfs2_dirent **)darr;
g.offset = 0;
dent = gfs2_dirent_scan(inode, dibh->b_data, dibh->b_size,
gfs2_dirent_gather, NULL, &g);
if (IS_ERR(dent)) {
error = PTR_ERR(dent);
goto out;
}
if (dip->i_entries != g.offset) {
fs_warn(sdp, "Number of entries corrupt in dir %llu, "
"ip->i_entries (%u) != g.offset (%u)\n",
(unsigned long long)dip->i_no_addr,
dip->i_entries,
g.offset);
gfs2_consist_inode(dip);
error = -EIO;
goto out;
}
gfs2_set_cookies(sdp, dibh, 0, darr, dip->i_entries);
error = do_filldir_main(dip, ctx, darr,
dip->i_entries, 0, &copied);
out:
kfree(darr);
}
if (error > 0)
error = 0;
brelse(dibh);
return error;
}
/**
* gfs2_dir_search - Search a directory
* @dir: The GFS2 directory inode
* @name: The name we are looking up
* @fail_on_exist: Fail if the name exists rather than looking it up
*
* This routine searches a directory for a file or another directory.
* Assumes a glock is held on dip.
*
* Returns: errno
*/
struct inode *gfs2_dir_search(struct inode *dir, const struct qstr *name,
bool fail_on_exist)
{
struct buffer_head *bh;
struct gfs2_dirent *dent;
u64 addr, formal_ino;
u16 dtype;
dent = gfs2_dirent_search(dir, name, gfs2_dirent_find, &bh);
if (dent) {
struct inode *inode;
u16 rahead;
if (IS_ERR(dent))
return ERR_CAST(dent);
dtype = be16_to_cpu(dent->de_type);
rahead = be16_to_cpu(dent->de_rahead);
addr = be64_to_cpu(dent->de_inum.no_addr);
formal_ino = be64_to_cpu(dent->de_inum.no_formal_ino);
brelse(bh);
if (fail_on_exist)
return ERR_PTR(-EEXIST);
inode = gfs2_inode_lookup(dir->i_sb, dtype, addr, formal_ino,
GFS2_BLKST_FREE /* ignore */);
if (!IS_ERR(inode))
GFS2_I(inode)->i_rahead = rahead;
return inode;
}
return ERR_PTR(-ENOENT);
}
int gfs2_dir_check(struct inode *dir, const struct qstr *name,
const struct gfs2_inode *ip)
{
struct buffer_head *bh;
struct gfs2_dirent *dent;
int ret = -ENOENT;
dent = gfs2_dirent_search(dir, name, gfs2_dirent_find, &bh);
if (dent) {
if (IS_ERR(dent))
return PTR_ERR(dent);
if (ip) {
if (be64_to_cpu(dent->de_inum.no_addr) != ip->i_no_addr)
goto out;
if (be64_to_cpu(dent->de_inum.no_formal_ino) !=
ip->i_no_formal_ino)
goto out;
if (unlikely(IF2DT(ip->i_inode.i_mode) !=
be16_to_cpu(dent->de_type))) {
gfs2_consist_inode(GFS2_I(dir));
ret = -EIO;
goto out;
}
}
ret = 0;
out:
brelse(bh);
}
return ret;
}
/**
* dir_new_leaf - Add a new leaf onto hash chain
* @inode: The directory
* @name: The name we are adding
*
* This adds a new dir leaf onto an existing leaf when there is not
* enough space to add a new dir entry. This is a last resort after
* we've expanded the hash table to max size and also split existing
* leaf blocks, so it will only occur for very large directories.
*
* The dist parameter is set to 1 for leaf blocks directly attached
* to the hash table, 2 for one layer of indirection, 3 for two layers
* etc. We are thus able to tell the difference between an old leaf
* with dist set to zero (i.e. "don't know") and a new one where we
* set this information for debug/fsck purposes.
*
* Returns: 0 on success, or -ve on error
*/
static int dir_new_leaf(struct inode *inode, const struct qstr *name)
{
struct buffer_head *bh, *obh;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_leaf *leaf, *oleaf;
u32 dist = 1;
int error;
u32 index;
u64 bn;
index = name->hash >> (32 - ip->i_depth);
error = get_first_leaf(ip, index, &obh);
if (error)
return error;
do {
dist++;
oleaf = (struct gfs2_leaf *)obh->b_data;
bn = be64_to_cpu(oleaf->lf_next);
if (!bn)
break;
brelse(obh);
error = get_leaf(ip, bn, &obh);
if (error)
return error;
} while(1);
gfs2_trans_add_meta(ip->i_gl, obh);
leaf = new_leaf(inode, &bh, be16_to_cpu(oleaf->lf_depth));
if (!leaf) {
brelse(obh);
return -ENOSPC;
}
leaf->lf_dist = cpu_to_be32(dist);
oleaf->lf_next = cpu_to_be64(bh->b_blocknr);
brelse(bh);
brelse(obh);
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
return error;
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_add_inode_blocks(&ip->i_inode, 1);
gfs2_dinode_out(ip, bh->b_data);
brelse(bh);
return 0;
}
static u16 gfs2_inode_ra_len(const struct gfs2_inode *ip)
{
u64 where = ip->i_no_addr + 1;
if (ip->i_eattr == where)
return 1;
return 0;
}
/**
* gfs2_dir_add - Add new filename into directory
* @inode: The directory inode
* @name: The new name
* @nip: The GFS2 inode to be linked in to the directory
* @da: The directory addition info
*
* If the call to gfs2_diradd_alloc_required resulted in there being
* no need to allocate any new directory blocks, then it will contain
* a pointer to the directory entry and the bh in which it resides. We
* can use that without having to repeat the search. If there was no
* free space, then we must now create more space.
*
* Returns: 0 on success, error code on failure
*/
int gfs2_dir_add(struct inode *inode, const struct qstr *name,
const struct gfs2_inode *nip, struct gfs2_diradd *da)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *bh = da->bh;
struct gfs2_dirent *dent = da->dent;
struct timespec64 tv;
struct gfs2_leaf *leaf;
int error;
while(1) {
if (da->bh == NULL) {
dent = gfs2_dirent_search(inode, name,
gfs2_dirent_find_space, &bh);
}
if (dent) {
if (IS_ERR(dent))
return PTR_ERR(dent);
dent = gfs2_init_dirent(inode, dent, name, bh);
gfs2_inum_out(nip, dent);
dent->de_type = cpu_to_be16(IF2DT(nip->i_inode.i_mode));
dent->de_rahead = cpu_to_be16(gfs2_inode_ra_len(nip));
tv = inode_set_ctime_current(&ip->i_inode);
if (ip->i_diskflags & GFS2_DIF_EXHASH) {
leaf = (struct gfs2_leaf *)bh->b_data;
be16_add_cpu(&leaf->lf_entries, 1);
leaf->lf_nsec = cpu_to_be32(tv.tv_nsec);
leaf->lf_sec = cpu_to_be64(tv.tv_sec);
}
da->dent = NULL;
da->bh = NULL;
brelse(bh);
ip->i_entries++;
ip->i_inode.i_mtime = tv;
if (S_ISDIR(nip->i_inode.i_mode))
inc_nlink(&ip->i_inode);
mark_inode_dirty(inode);
error = 0;
break;
}
if (!(ip->i_diskflags & GFS2_DIF_EXHASH)) {
error = dir_make_exhash(inode);
if (error)
break;
continue;
}
error = dir_split_leaf(inode, name);
if (error == 0)
continue;
if (error < 0)
break;
if (ip->i_depth < GFS2_DIR_MAX_DEPTH) {
error = dir_double_exhash(ip);
if (error)
break;
error = dir_split_leaf(inode, name);
if (error < 0)
break;
if (error == 0)
continue;
}
error = dir_new_leaf(inode, name);
if (!error)
continue;
error = -ENOSPC;
break;
}
return error;
}
/**
* gfs2_dir_del - Delete a directory entry
* @dip: The GFS2 inode
* @dentry: The directory entry we want to delete
*
* Returns: 0 on success, error code on failure
*/
int gfs2_dir_del(struct gfs2_inode *dip, const struct dentry *dentry)
{
const struct qstr *name = &dentry->d_name;
struct gfs2_dirent *dent, *prev = NULL;
struct buffer_head *bh;
struct timespec64 tv;
/* Returns _either_ the entry (if its first in block) or the
previous entry otherwise */
dent = gfs2_dirent_search(&dip->i_inode, name, gfs2_dirent_prev, &bh);
if (!dent) {
gfs2_consist_inode(dip);
return -EIO;
}
if (IS_ERR(dent)) {
gfs2_consist_inode(dip);
return PTR_ERR(dent);
}
/* If not first in block, adjust pointers accordingly */
if (gfs2_dirent_find(dent, name, NULL) == 0) {
prev = dent;
dent = (struct gfs2_dirent *)((char *)dent + be16_to_cpu(prev->de_rec_len));
}
dirent_del(dip, bh, prev, dent);
tv = inode_set_ctime_current(&dip->i_inode);
if (dip->i_diskflags & GFS2_DIF_EXHASH) {
struct gfs2_leaf *leaf = (struct gfs2_leaf *)bh->b_data;
u16 entries = be16_to_cpu(leaf->lf_entries);
if (!entries)
gfs2_consist_inode(dip);
leaf->lf_entries = cpu_to_be16(--entries);
leaf->lf_nsec = cpu_to_be32(tv.tv_nsec);
leaf->lf_sec = cpu_to_be64(tv.tv_sec);
}
brelse(bh);
if (!dip->i_entries)
gfs2_consist_inode(dip);
dip->i_entries--;
dip->i_inode.i_mtime = tv;
if (d_is_dir(dentry))
drop_nlink(&dip->i_inode);
mark_inode_dirty(&dip->i_inode);
return 0;
}
/**
* gfs2_dir_mvino - Change inode number of directory entry
* @dip: The GFS2 directory inode
* @filename: the filename to be moved
* @nip: the new GFS2 inode
* @new_type: the de_type of the new dirent
*
* This routine changes the inode number of a directory entry. It's used
* by rename to change ".." when a directory is moved.
* Assumes a glock is held on dvp.
*
* Returns: errno
*/
int gfs2_dir_mvino(struct gfs2_inode *dip, const struct qstr *filename,
const struct gfs2_inode *nip, unsigned int new_type)
{
struct buffer_head *bh;
struct gfs2_dirent *dent;
dent = gfs2_dirent_search(&dip->i_inode, filename, gfs2_dirent_find, &bh);
if (!dent) {
gfs2_consist_inode(dip);
return -EIO;
}
if (IS_ERR(dent))
return PTR_ERR(dent);
gfs2_trans_add_meta(dip->i_gl, bh);
gfs2_inum_out(nip, dent);
dent->de_type = cpu_to_be16(new_type);
brelse(bh);
dip->i_inode.i_mtime = inode_set_ctime_current(&dip->i_inode);
mark_inode_dirty_sync(&dip->i_inode);
return 0;
}
/**
* leaf_dealloc - Deallocate a directory leaf
* @dip: the directory
* @index: the hash table offset in the directory
* @len: the number of pointers to this leaf
* @leaf_no: the leaf number
* @leaf_bh: buffer_head for the starting leaf
* @last_dealloc: 1 if this is the final dealloc for the leaf, else 0
*
* Returns: errno
*/
static int leaf_dealloc(struct gfs2_inode *dip, u32 index, u32 len,
u64 leaf_no, struct buffer_head *leaf_bh,
int last_dealloc)
{
struct gfs2_sbd *sdp = GFS2_SB(&dip->i_inode);
struct gfs2_leaf *tmp_leaf;
struct gfs2_rgrp_list rlist;
struct buffer_head *bh, *dibh;
u64 blk, nblk;
unsigned int rg_blocks = 0, l_blocks = 0;
char *ht;
unsigned int x, size = len * sizeof(u64);
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
memset(&rlist, 0, sizeof(struct gfs2_rgrp_list));
ht = kzalloc(size, GFP_NOFS | __GFP_NOWARN);
if (ht == NULL)
ht = __vmalloc(size, GFP_NOFS | __GFP_NOWARN | __GFP_ZERO);
if (!ht)
return -ENOMEM;
error = gfs2_quota_hold(dip, NO_UID_QUOTA_CHANGE, NO_GID_QUOTA_CHANGE);
if (error)
goto out;
/* Count the number of leaves */
bh = leaf_bh;
for (blk = leaf_no; blk; blk = nblk) {
if (blk != leaf_no) {
error = get_leaf(dip, blk, &bh);
if (error)
goto out_rlist;
}
tmp_leaf = (struct gfs2_leaf *)bh->b_data;
nblk = be64_to_cpu(tmp_leaf->lf_next);
if (blk != leaf_no)
brelse(bh);
gfs2_rlist_add(dip, &rlist, blk);
l_blocks++;
}
gfs2_rlist_alloc(&rlist, LM_ST_EXCLUSIVE, LM_FLAG_NODE_SCOPE);
for (x = 0; x < rlist.rl_rgrps; x++) {
struct gfs2_rgrpd *rgd = gfs2_glock2rgrp(rlist.rl_ghs[x].gh_gl);
rg_blocks += rgd->rd_length;
}
error = gfs2_glock_nq_m(rlist.rl_rgrps, rlist.rl_ghs);
if (error)
goto out_rlist;
error = gfs2_trans_begin(sdp,
rg_blocks + (DIV_ROUND_UP(size, sdp->sd_jbsize) + 1) +
RES_DINODE + RES_STATFS + RES_QUOTA, RES_DINODE +
l_blocks);
if (error)
goto out_rg_gunlock;
bh = leaf_bh;
for (blk = leaf_no; blk; blk = nblk) {
struct gfs2_rgrpd *rgd;
if (blk != leaf_no) {
error = get_leaf(dip, blk, &bh);
if (error)
goto out_end_trans;
}
tmp_leaf = (struct gfs2_leaf *)bh->b_data;
nblk = be64_to_cpu(tmp_leaf->lf_next);
if (blk != leaf_no)
brelse(bh);
rgd = gfs2_blk2rgrpd(sdp, blk, true);
gfs2_free_meta(dip, rgd, blk, 1);
gfs2_add_inode_blocks(&dip->i_inode, -1);
}
error = gfs2_dir_write_data(dip, ht, index * sizeof(u64), size);
if (error != size) {
if (error >= 0)
error = -EIO;
goto out_end_trans;
}
error = gfs2_meta_inode_buffer(dip, &dibh);
if (error)
goto out_end_trans;
gfs2_trans_add_meta(dip->i_gl, dibh);
/* On the last dealloc, make this a regular file in case we crash.
(We don't want to free these blocks a second time.) */
if (last_dealloc)
dip->i_inode.i_mode = S_IFREG;
gfs2_dinode_out(dip, dibh->b_data);
brelse(dibh);
out_end_trans:
gfs2_trans_end(sdp);
out_rg_gunlock:
gfs2_glock_dq_m(rlist.rl_rgrps, rlist.rl_ghs);
out_rlist:
gfs2_rlist_free(&rlist);
gfs2_quota_unhold(dip);
out:
kvfree(ht);
return error;
}
/**
* gfs2_dir_exhash_dealloc - free all the leaf blocks in a directory
* @dip: the directory
*
* Dealloc all on-disk directory leaves to FREEMETA state
* Change on-disk inode type to "regular file"
*
* Returns: errno
*/
int gfs2_dir_exhash_dealloc(struct gfs2_inode *dip)
{
struct buffer_head *bh;
struct gfs2_leaf *leaf;
u32 hsize, len;
u32 index = 0, next_index;
__be64 *lp;
u64 leaf_no;
int error = 0, last;
hsize = BIT(dip->i_depth);
lp = gfs2_dir_get_hash_table(dip);
if (IS_ERR(lp))
return PTR_ERR(lp);
while (index < hsize) {
leaf_no = be64_to_cpu(lp[index]);
if (leaf_no) {
error = get_leaf(dip, leaf_no, &bh);
if (error)
goto out;
leaf = (struct gfs2_leaf *)bh->b_data;
len = BIT(dip->i_depth - be16_to_cpu(leaf->lf_depth));
next_index = (index & ~(len - 1)) + len;
last = ((next_index >= hsize) ? 1 : 0);
error = leaf_dealloc(dip, index, len, leaf_no, bh,
last);
brelse(bh);
if (error)
goto out;
index = next_index;
} else
index++;
}
if (index != hsize) {
gfs2_consist_inode(dip);
error = -EIO;
}
out:
return error;
}
/**
* gfs2_diradd_alloc_required - find if adding entry will require an allocation
* @inode: the directory inode being written to
* @name: the filename that's going to be added
* @da: The structure to return dir alloc info
*
* Returns: 0 if ok, -ve on error
*/
int gfs2_diradd_alloc_required(struct inode *inode, const struct qstr *name,
struct gfs2_diradd *da)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
const unsigned int extra = sizeof(struct gfs2_dinode) - sizeof(struct gfs2_leaf);
struct gfs2_dirent *dent;
struct buffer_head *bh;
da->nr_blocks = 0;
da->bh = NULL;
da->dent = NULL;
dent = gfs2_dirent_search(inode, name, gfs2_dirent_find_space, &bh);
if (!dent) {
da->nr_blocks = sdp->sd_max_dirres;
if (!(ip->i_diskflags & GFS2_DIF_EXHASH) &&
(GFS2_DIRENT_SIZE(name->len) < extra))
da->nr_blocks = 1;
return 0;
}
if (IS_ERR(dent))
return PTR_ERR(dent);
if (da->save_loc) {
da->bh = bh;
da->dent = dent;
} else {
brelse(bh);
}
return 0;
}
| linux-master | fs/gfs2/dir.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/mempool.h>
#include <linux/gfs2_ondisk.h>
#include <linux/bio.h>
#include <linux/fs.h>
#include <linux/list_sort.h>
#include <linux/blkdev.h>
#include "bmap.h"
#include "dir.h"
#include "gfs2.h"
#include "incore.h"
#include "inode.h"
#include "glock.h"
#include "glops.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "recovery.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
#include "trace_gfs2.h"
/**
* gfs2_pin - Pin a buffer in memory
* @sdp: The superblock
* @bh: The buffer to be pinned
*
* The log lock must be held when calling this function
*/
void gfs2_pin(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
struct gfs2_bufdata *bd;
BUG_ON(!current->journal_info);
clear_buffer_dirty(bh);
if (test_set_buffer_pinned(bh))
gfs2_assert_withdraw(sdp, 0);
if (!buffer_uptodate(bh))
gfs2_io_error_bh_wd(sdp, bh);
bd = bh->b_private;
/* If this buffer is in the AIL and it has already been written
* to in-place disk block, remove it from the AIL.
*/
spin_lock(&sdp->sd_ail_lock);
if (bd->bd_tr)
list_move(&bd->bd_ail_st_list, &bd->bd_tr->tr_ail2_list);
spin_unlock(&sdp->sd_ail_lock);
get_bh(bh);
atomic_inc(&sdp->sd_log_pinned);
trace_gfs2_pin(bd, 1);
}
static bool buffer_is_rgrp(const struct gfs2_bufdata *bd)
{
return bd->bd_gl->gl_name.ln_type == LM_TYPE_RGRP;
}
static void maybe_release_space(struct gfs2_bufdata *bd)
{
struct gfs2_glock *gl = bd->bd_gl;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_rgrpd *rgd = gfs2_glock2rgrp(gl);
unsigned int index = bd->bd_bh->b_blocknr - gl->gl_name.ln_number;
struct gfs2_bitmap *bi = rgd->rd_bits + index;
rgrp_lock_local(rgd);
if (bi->bi_clone == NULL)
goto out;
if (sdp->sd_args.ar_discard)
gfs2_rgrp_send_discards(sdp, rgd->rd_data0, bd->bd_bh, bi, 1, NULL);
memcpy(bi->bi_clone + bi->bi_offset,
bd->bd_bh->b_data + bi->bi_offset, bi->bi_bytes);
clear_bit(GBF_FULL, &bi->bi_flags);
rgd->rd_free_clone = rgd->rd_free;
BUG_ON(rgd->rd_free_clone < rgd->rd_reserved);
rgd->rd_extfail_pt = rgd->rd_free;
out:
rgrp_unlock_local(rgd);
}
/**
* gfs2_unpin - Unpin a buffer
* @sdp: the filesystem the buffer belongs to
* @bh: The buffer to unpin
* @tr: The system transaction being flushed
*/
static void gfs2_unpin(struct gfs2_sbd *sdp, struct buffer_head *bh,
struct gfs2_trans *tr)
{
struct gfs2_bufdata *bd = bh->b_private;
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!buffer_pinned(bh));
lock_buffer(bh);
mark_buffer_dirty(bh);
clear_buffer_pinned(bh);
if (buffer_is_rgrp(bd))
maybe_release_space(bd);
spin_lock(&sdp->sd_ail_lock);
if (bd->bd_tr) {
list_del(&bd->bd_ail_st_list);
brelse(bh);
} else {
struct gfs2_glock *gl = bd->bd_gl;
list_add(&bd->bd_ail_gl_list, &gl->gl_ail_list);
atomic_inc(&gl->gl_ail_count);
}
bd->bd_tr = tr;
list_add(&bd->bd_ail_st_list, &tr->tr_ail1_list);
spin_unlock(&sdp->sd_ail_lock);
clear_bit(GLF_LFLUSH, &bd->bd_gl->gl_flags);
trace_gfs2_pin(bd, 0);
unlock_buffer(bh);
atomic_dec(&sdp->sd_log_pinned);
}
void gfs2_log_incr_head(struct gfs2_sbd *sdp)
{
BUG_ON((sdp->sd_log_flush_head == sdp->sd_log_tail) &&
(sdp->sd_log_flush_head != sdp->sd_log_head));
if (++sdp->sd_log_flush_head == sdp->sd_jdesc->jd_blocks)
sdp->sd_log_flush_head = 0;
}
u64 gfs2_log_bmap(struct gfs2_jdesc *jd, unsigned int lblock)
{
struct gfs2_journal_extent *je;
list_for_each_entry(je, &jd->extent_list, list) {
if (lblock >= je->lblock && lblock < je->lblock + je->blocks)
return je->dblock + lblock - je->lblock;
}
return -1;
}
/**
* gfs2_end_log_write_bh - end log write of pagecache data with buffers
* @sdp: The superblock
* @bvec: The bio_vec
* @error: The i/o status
*
* This finds the relevant buffers and unlocks them and sets the
* error flag according to the status of the i/o request. This is
* used when the log is writing data which has an in-place version
* that is pinned in the pagecache.
*/
static void gfs2_end_log_write_bh(struct gfs2_sbd *sdp,
struct bio_vec *bvec,
blk_status_t error)
{
struct buffer_head *bh, *next;
struct page *page = bvec->bv_page;
unsigned size;
bh = page_buffers(page);
size = bvec->bv_len;
while (bh_offset(bh) < bvec->bv_offset)
bh = bh->b_this_page;
do {
if (error)
mark_buffer_write_io_error(bh);
unlock_buffer(bh);
next = bh->b_this_page;
size -= bh->b_size;
brelse(bh);
bh = next;
} while(bh && size);
}
/**
* gfs2_end_log_write - end of i/o to the log
* @bio: The bio
*
* Each bio_vec contains either data from the pagecache or data
* relating to the log itself. Here we iterate over the bio_vec
* array, processing both kinds of data.
*
*/
static void gfs2_end_log_write(struct bio *bio)
{
struct gfs2_sbd *sdp = bio->bi_private;
struct bio_vec *bvec;
struct page *page;
struct bvec_iter_all iter_all;
if (bio->bi_status) {
if (!cmpxchg(&sdp->sd_log_error, 0, (int)bio->bi_status))
fs_err(sdp, "Error %d writing to journal, jid=%u\n",
bio->bi_status, sdp->sd_jdesc->jd_jid);
gfs2_withdraw_delayed(sdp);
/* prevent more writes to the journal */
clear_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags);
wake_up(&sdp->sd_logd_waitq);
}
bio_for_each_segment_all(bvec, bio, iter_all) {
page = bvec->bv_page;
if (page_has_buffers(page))
gfs2_end_log_write_bh(sdp, bvec, bio->bi_status);
else
mempool_free(page, gfs2_page_pool);
}
bio_put(bio);
if (atomic_dec_and_test(&sdp->sd_log_in_flight))
wake_up(&sdp->sd_log_flush_wait);
}
/**
* gfs2_log_submit_bio - Submit any pending log bio
* @biop: Address of the bio pointer
* @opf: REQ_OP | op_flags
*
* Submit any pending part-built or full bio to the block device. If
* there is no pending bio, then this is a no-op.
*/
void gfs2_log_submit_bio(struct bio **biop, blk_opf_t opf)
{
struct bio *bio = *biop;
if (bio) {
struct gfs2_sbd *sdp = bio->bi_private;
atomic_inc(&sdp->sd_log_in_flight);
bio->bi_opf = opf;
submit_bio(bio);
*biop = NULL;
}
}
/**
* gfs2_log_alloc_bio - Allocate a bio
* @sdp: The super block
* @blkno: The device block number we want to write to
* @end_io: The bi_end_io callback
*
* Allocate a new bio, initialize it with the given parameters and return it.
*
* Returns: The newly allocated bio
*/
static struct bio *gfs2_log_alloc_bio(struct gfs2_sbd *sdp, u64 blkno,
bio_end_io_t *end_io)
{
struct super_block *sb = sdp->sd_vfs;
struct bio *bio = bio_alloc(sb->s_bdev, BIO_MAX_VECS, 0, GFP_NOIO);
bio->bi_iter.bi_sector = blkno << sdp->sd_fsb2bb_shift;
bio->bi_end_io = end_io;
bio->bi_private = sdp;
return bio;
}
/**
* gfs2_log_get_bio - Get cached log bio, or allocate a new one
* @sdp: The super block
* @blkno: The device block number we want to write to
* @biop: The bio to get or allocate
* @op: REQ_OP
* @end_io: The bi_end_io callback
* @flush: Always flush the current bio and allocate a new one?
*
* If there is a cached bio, then if the next block number is sequential
* with the previous one, return it, otherwise flush the bio to the
* device. If there is no cached bio, or we just flushed it, then
* allocate a new one.
*
* Returns: The bio to use for log writes
*/
static struct bio *gfs2_log_get_bio(struct gfs2_sbd *sdp, u64 blkno,
struct bio **biop, enum req_op op,
bio_end_io_t *end_io, bool flush)
{
struct bio *bio = *biop;
if (bio) {
u64 nblk;
nblk = bio_end_sector(bio);
nblk >>= sdp->sd_fsb2bb_shift;
if (blkno == nblk && !flush)
return bio;
gfs2_log_submit_bio(biop, op);
}
*biop = gfs2_log_alloc_bio(sdp, blkno, end_io);
return *biop;
}
/**
* gfs2_log_write - write to log
* @sdp: the filesystem
* @jd: The journal descriptor
* @page: the page to write
* @size: the size of the data to write
* @offset: the offset within the page
* @blkno: block number of the log entry
*
* Try and add the page segment to the current bio. If that fails,
* submit the current bio to the device and create a new one, and
* then add the page segment to that.
*/
void gfs2_log_write(struct gfs2_sbd *sdp, struct gfs2_jdesc *jd,
struct page *page, unsigned size, unsigned offset,
u64 blkno)
{
struct bio *bio;
int ret;
bio = gfs2_log_get_bio(sdp, blkno, &jd->jd_log_bio, REQ_OP_WRITE,
gfs2_end_log_write, false);
ret = bio_add_page(bio, page, size, offset);
if (ret == 0) {
bio = gfs2_log_get_bio(sdp, blkno, &jd->jd_log_bio,
REQ_OP_WRITE, gfs2_end_log_write, true);
ret = bio_add_page(bio, page, size, offset);
WARN_ON(ret == 0);
}
}
/**
* gfs2_log_write_bh - write a buffer's content to the log
* @sdp: The super block
* @bh: The buffer pointing to the in-place location
*
* This writes the content of the buffer to the next available location
* in the log. The buffer will be unlocked once the i/o to the log has
* completed.
*/
static void gfs2_log_write_bh(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
u64 dblock;
dblock = gfs2_log_bmap(sdp->sd_jdesc, sdp->sd_log_flush_head);
gfs2_log_incr_head(sdp);
gfs2_log_write(sdp, sdp->sd_jdesc, bh->b_page, bh->b_size,
bh_offset(bh), dblock);
}
/**
* gfs2_log_write_page - write one block stored in a page, into the log
* @sdp: The superblock
* @page: The struct page
*
* This writes the first block-sized part of the page into the log. Note
* that the page must have been allocated from the gfs2_page_pool mempool
* and that after this has been called, ownership has been transferred and
* the page may be freed at any time.
*/
static void gfs2_log_write_page(struct gfs2_sbd *sdp, struct page *page)
{
struct super_block *sb = sdp->sd_vfs;
u64 dblock;
dblock = gfs2_log_bmap(sdp->sd_jdesc, sdp->sd_log_flush_head);
gfs2_log_incr_head(sdp);
gfs2_log_write(sdp, sdp->sd_jdesc, page, sb->s_blocksize, 0, dblock);
}
/**
* gfs2_end_log_read - end I/O callback for reads from the log
* @bio: The bio
*
* Simply unlock the pages in the bio. The main thread will wait on them and
* process them in order as necessary.
*/
static void gfs2_end_log_read(struct bio *bio)
{
struct page *page;
struct bio_vec *bvec;
struct bvec_iter_all iter_all;
bio_for_each_segment_all(bvec, bio, iter_all) {
page = bvec->bv_page;
if (bio->bi_status) {
int err = blk_status_to_errno(bio->bi_status);
SetPageError(page);
mapping_set_error(page->mapping, err);
}
unlock_page(page);
}
bio_put(bio);
}
/**
* gfs2_jhead_pg_srch - Look for the journal head in a given page.
* @jd: The journal descriptor
* @head: The journal head to start from
* @page: The page to look in
*
* Returns: 1 if found, 0 otherwise.
*/
static bool gfs2_jhead_pg_srch(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head,
struct page *page)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_log_header_host lh;
void *kaddr;
unsigned int offset;
bool ret = false;
kaddr = kmap_local_page(page);
for (offset = 0; offset < PAGE_SIZE; offset += sdp->sd_sb.sb_bsize) {
if (!__get_log_header(sdp, kaddr + offset, 0, &lh)) {
if (lh.lh_sequence >= head->lh_sequence)
*head = lh;
else {
ret = true;
break;
}
}
}
kunmap_local(kaddr);
return ret;
}
/**
* gfs2_jhead_process_page - Search/cleanup a page
* @jd: The journal descriptor
* @index: Index of the page to look into
* @head: The journal head to start from
* @done: If set, perform only cleanup, else search and set if found.
*
* Find the folio with 'index' in the journal's mapping. Search the folio for
* the journal head if requested (cleanup == false). Release refs on the
* folio so the page cache can reclaim it. We grabbed a
* reference on this folio twice, first when we did a grab_cache_page()
* to obtain the folio to add it to the bio and second when we do a
* filemap_get_folio() here to get the folio to wait on while I/O on it is being
* completed.
* This function is also used to free up a folio we might've grabbed but not
* used. Maybe we added it to a bio, but not submitted it for I/O. Or we
* submitted the I/O, but we already found the jhead so we only need to drop
* our references to the folio.
*/
static void gfs2_jhead_process_page(struct gfs2_jdesc *jd, unsigned long index,
struct gfs2_log_header_host *head,
bool *done)
{
struct folio *folio;
folio = filemap_get_folio(jd->jd_inode->i_mapping, index);
folio_wait_locked(folio);
if (folio_test_error(folio))
*done = true;
if (!*done)
*done = gfs2_jhead_pg_srch(jd, head, &folio->page);
/* filemap_get_folio() and the earlier grab_cache_page() */
folio_put_refs(folio, 2);
}
static struct bio *gfs2_chain_bio(struct bio *prev, unsigned int nr_iovecs)
{
struct bio *new;
new = bio_alloc(prev->bi_bdev, nr_iovecs, prev->bi_opf, GFP_NOIO);
bio_clone_blkg_association(new, prev);
new->bi_iter.bi_sector = bio_end_sector(prev);
bio_chain(new, prev);
submit_bio(prev);
return new;
}
/**
* gfs2_find_jhead - find the head of a log
* @jd: The journal descriptor
* @head: The log descriptor for the head of the log is returned here
* @keep_cache: If set inode pages will not be truncated
*
* Do a search of a journal by reading it in large chunks using bios and find
* the valid log entry with the highest sequence number. (i.e. the log head)
*
* Returns: 0 on success, errno otherwise
*/
int gfs2_find_jhead(struct gfs2_jdesc *jd, struct gfs2_log_header_host *head,
bool keep_cache)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct address_space *mapping = jd->jd_inode->i_mapping;
unsigned int block = 0, blocks_submitted = 0, blocks_read = 0;
unsigned int bsize = sdp->sd_sb.sb_bsize, off;
unsigned int bsize_shift = sdp->sd_sb.sb_bsize_shift;
unsigned int shift = PAGE_SHIFT - bsize_shift;
unsigned int max_blocks = 2 * 1024 * 1024 >> bsize_shift;
struct gfs2_journal_extent *je;
int sz, ret = 0;
struct bio *bio = NULL;
struct page *page = NULL;
bool done = false;
errseq_t since;
memset(head, 0, sizeof(*head));
if (list_empty(&jd->extent_list))
gfs2_map_journal_extents(sdp, jd);
since = filemap_sample_wb_err(mapping);
list_for_each_entry(je, &jd->extent_list, list) {
u64 dblock = je->dblock;
for (; block < je->lblock + je->blocks; block++, dblock++) {
if (!page) {
page = grab_cache_page(mapping, block >> shift);
if (!page) {
ret = -ENOMEM;
done = true;
goto out;
}
off = 0;
}
if (bio && (off || block < blocks_submitted + max_blocks)) {
sector_t sector = dblock << sdp->sd_fsb2bb_shift;
if (bio_end_sector(bio) == sector) {
sz = bio_add_page(bio, page, bsize, off);
if (sz == bsize)
goto block_added;
}
if (off) {
unsigned int blocks =
(PAGE_SIZE - off) >> bsize_shift;
bio = gfs2_chain_bio(bio, blocks);
goto add_block_to_new_bio;
}
}
if (bio) {
blocks_submitted = block;
submit_bio(bio);
}
bio = gfs2_log_alloc_bio(sdp, dblock, gfs2_end_log_read);
bio->bi_opf = REQ_OP_READ;
add_block_to_new_bio:
sz = bio_add_page(bio, page, bsize, off);
BUG_ON(sz != bsize);
block_added:
off += bsize;
if (off == PAGE_SIZE)
page = NULL;
if (blocks_submitted <= blocks_read + max_blocks) {
/* Keep at least one bio in flight */
continue;
}
gfs2_jhead_process_page(jd, blocks_read >> shift, head, &done);
blocks_read += PAGE_SIZE >> bsize_shift;
if (done)
goto out; /* found */
}
}
out:
if (bio)
submit_bio(bio);
while (blocks_read < block) {
gfs2_jhead_process_page(jd, blocks_read >> shift, head, &done);
blocks_read += PAGE_SIZE >> bsize_shift;
}
if (!ret)
ret = filemap_check_wb_err(mapping, since);
if (!keep_cache)
truncate_inode_pages(mapping, 0);
return ret;
}
static struct page *gfs2_get_log_desc(struct gfs2_sbd *sdp, u32 ld_type,
u32 ld_length, u32 ld_data1)
{
struct page *page = mempool_alloc(gfs2_page_pool, GFP_NOIO);
struct gfs2_log_descriptor *ld = page_address(page);
clear_page(ld);
ld->ld_header.mh_magic = cpu_to_be32(GFS2_MAGIC);
ld->ld_header.mh_type = cpu_to_be32(GFS2_METATYPE_LD);
ld->ld_header.mh_format = cpu_to_be32(GFS2_FORMAT_LD);
ld->ld_type = cpu_to_be32(ld_type);
ld->ld_length = cpu_to_be32(ld_length);
ld->ld_data1 = cpu_to_be32(ld_data1);
ld->ld_data2 = 0;
return page;
}
static void gfs2_check_magic(struct buffer_head *bh)
{
void *kaddr;
__be32 *ptr;
clear_buffer_escaped(bh);
kaddr = kmap_local_page(bh->b_page);
ptr = kaddr + bh_offset(bh);
if (*ptr == cpu_to_be32(GFS2_MAGIC))
set_buffer_escaped(bh);
kunmap_local(kaddr);
}
static int blocknr_cmp(void *priv, const struct list_head *a,
const struct list_head *b)
{
struct gfs2_bufdata *bda, *bdb;
bda = list_entry(a, struct gfs2_bufdata, bd_list);
bdb = list_entry(b, struct gfs2_bufdata, bd_list);
if (bda->bd_bh->b_blocknr < bdb->bd_bh->b_blocknr)
return -1;
if (bda->bd_bh->b_blocknr > bdb->bd_bh->b_blocknr)
return 1;
return 0;
}
static void gfs2_before_commit(struct gfs2_sbd *sdp, unsigned int limit,
unsigned int total, struct list_head *blist,
bool is_databuf)
{
struct gfs2_log_descriptor *ld;
struct gfs2_bufdata *bd1 = NULL, *bd2;
struct page *page;
unsigned int num;
unsigned n;
__be64 *ptr;
gfs2_log_lock(sdp);
list_sort(NULL, blist, blocknr_cmp);
bd1 = bd2 = list_prepare_entry(bd1, blist, bd_list);
while(total) {
num = total;
if (total > limit)
num = limit;
gfs2_log_unlock(sdp);
page = gfs2_get_log_desc(sdp,
is_databuf ? GFS2_LOG_DESC_JDATA :
GFS2_LOG_DESC_METADATA, num + 1, num);
ld = page_address(page);
gfs2_log_lock(sdp);
ptr = (__be64 *)(ld + 1);
n = 0;
list_for_each_entry_continue(bd1, blist, bd_list) {
*ptr++ = cpu_to_be64(bd1->bd_bh->b_blocknr);
if (is_databuf) {
gfs2_check_magic(bd1->bd_bh);
*ptr++ = cpu_to_be64(buffer_escaped(bd1->bd_bh) ? 1 : 0);
}
if (++n >= num)
break;
}
gfs2_log_unlock(sdp);
gfs2_log_write_page(sdp, page);
gfs2_log_lock(sdp);
n = 0;
list_for_each_entry_continue(bd2, blist, bd_list) {
get_bh(bd2->bd_bh);
gfs2_log_unlock(sdp);
lock_buffer(bd2->bd_bh);
if (buffer_escaped(bd2->bd_bh)) {
void *p;
page = mempool_alloc(gfs2_page_pool, GFP_NOIO);
p = page_address(page);
memcpy_from_page(p, page, bh_offset(bd2->bd_bh), bd2->bd_bh->b_size);
*(__be32 *)p = 0;
clear_buffer_escaped(bd2->bd_bh);
unlock_buffer(bd2->bd_bh);
brelse(bd2->bd_bh);
gfs2_log_write_page(sdp, page);
} else {
gfs2_log_write_bh(sdp, bd2->bd_bh);
}
gfs2_log_lock(sdp);
if (++n >= num)
break;
}
BUG_ON(total < num);
total -= num;
}
gfs2_log_unlock(sdp);
}
static void buf_lo_before_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
unsigned int limit = buf_limit(sdp); /* 503 for 4k blocks */
unsigned int nbuf;
if (tr == NULL)
return;
nbuf = tr->tr_num_buf_new - tr->tr_num_buf_rm;
gfs2_before_commit(sdp, limit, nbuf, &tr->tr_buf, 0);
}
static void buf_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
struct list_head *head;
struct gfs2_bufdata *bd;
if (tr == NULL)
return;
head = &tr->tr_buf;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
gfs2_unpin(sdp, bd->bd_bh, tr);
}
}
static void buf_lo_before_scan(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head, int pass)
{
if (pass != 0)
return;
jd->jd_found_blocks = 0;
jd->jd_replayed_blocks = 0;
}
#define obsolete_rgrp_replay \
"Replaying 0x%llx from jid=%d/0x%llx but we already have a bh!\n"
#define obsolete_rgrp_replay2 \
"busy:%d, pinned:%d rg_gen:0x%llx, j_gen:0x%llx\n"
static void obsolete_rgrp(struct gfs2_jdesc *jd, struct buffer_head *bh_log,
u64 blkno)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_rgrpd *rgd;
struct gfs2_rgrp *jrgd = (struct gfs2_rgrp *)bh_log->b_data;
rgd = gfs2_blk2rgrpd(sdp, blkno, false);
if (rgd && rgd->rd_addr == blkno &&
rgd->rd_bits && rgd->rd_bits->bi_bh) {
fs_info(sdp, obsolete_rgrp_replay, (unsigned long long)blkno,
jd->jd_jid, bh_log->b_blocknr);
fs_info(sdp, obsolete_rgrp_replay2,
buffer_busy(rgd->rd_bits->bi_bh) ? 1 : 0,
buffer_pinned(rgd->rd_bits->bi_bh),
rgd->rd_igeneration,
be64_to_cpu(jrgd->rg_igeneration));
gfs2_dump_glock(NULL, rgd->rd_gl, true);
}
}
static int buf_lo_scan_elements(struct gfs2_jdesc *jd, u32 start,
struct gfs2_log_descriptor *ld, __be64 *ptr,
int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_glock *gl = ip->i_gl;
unsigned int blks = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh_log, *bh_ip;
u64 blkno;
int error = 0;
if (pass != 1 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_METADATA)
return 0;
gfs2_replay_incr_blk(jd, &start);
for (; blks; gfs2_replay_incr_blk(jd, &start), blks--) {
blkno = be64_to_cpu(*ptr++);
jd->jd_found_blocks++;
if (gfs2_revoke_check(jd, blkno, start))
continue;
error = gfs2_replay_read_block(jd, start, &bh_log);
if (error)
return error;
bh_ip = gfs2_meta_new(gl, blkno);
memcpy(bh_ip->b_data, bh_log->b_data, bh_log->b_size);
if (gfs2_meta_check(sdp, bh_ip))
error = -EIO;
else {
struct gfs2_meta_header *mh =
(struct gfs2_meta_header *)bh_ip->b_data;
if (mh->mh_type == cpu_to_be32(GFS2_METATYPE_RG))
obsolete_rgrp(jd, bh_log, blkno);
mark_buffer_dirty(bh_ip);
}
brelse(bh_log);
brelse(bh_ip);
if (error)
break;
jd->jd_replayed_blocks++;
}
return error;
}
static void buf_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_inode_metasync(ip->i_gl);
return;
}
if (pass != 1)
return;
gfs2_inode_metasync(ip->i_gl);
fs_info(sdp, "jid=%u: Replayed %u of %u blocks\n",
jd->jd_jid, jd->jd_replayed_blocks, jd->jd_found_blocks);
}
static void revoke_lo_before_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
struct gfs2_meta_header *mh;
unsigned int offset;
struct list_head *head = &sdp->sd_log_revokes;
struct gfs2_bufdata *bd;
struct page *page;
unsigned int length;
gfs2_flush_revokes(sdp);
if (!sdp->sd_log_num_revoke)
return;
length = gfs2_struct2blk(sdp, sdp->sd_log_num_revoke);
page = gfs2_get_log_desc(sdp, GFS2_LOG_DESC_REVOKE, length, sdp->sd_log_num_revoke);
offset = sizeof(struct gfs2_log_descriptor);
list_for_each_entry(bd, head, bd_list) {
sdp->sd_log_num_revoke--;
if (offset + sizeof(u64) > sdp->sd_sb.sb_bsize) {
gfs2_log_write_page(sdp, page);
page = mempool_alloc(gfs2_page_pool, GFP_NOIO);
mh = page_address(page);
clear_page(mh);
mh->mh_magic = cpu_to_be32(GFS2_MAGIC);
mh->mh_type = cpu_to_be32(GFS2_METATYPE_LB);
mh->mh_format = cpu_to_be32(GFS2_FORMAT_LB);
offset = sizeof(struct gfs2_meta_header);
}
*(__be64 *)(page_address(page) + offset) = cpu_to_be64(bd->bd_blkno);
offset += sizeof(u64);
}
gfs2_assert_withdraw(sdp, !sdp->sd_log_num_revoke);
gfs2_log_write_page(sdp, page);
}
void gfs2_drain_revokes(struct gfs2_sbd *sdp)
{
struct list_head *head = &sdp->sd_log_revokes;
struct gfs2_bufdata *bd;
struct gfs2_glock *gl;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
gl = bd->bd_gl;
gfs2_glock_remove_revoke(gl);
kmem_cache_free(gfs2_bufdata_cachep, bd);
}
}
static void revoke_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
gfs2_drain_revokes(sdp);
}
static void revoke_lo_before_scan(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head, int pass)
{
if (pass != 0)
return;
jd->jd_found_revokes = 0;
jd->jd_replay_tail = head->lh_tail;
}
static int revoke_lo_scan_elements(struct gfs2_jdesc *jd, u32 start,
struct gfs2_log_descriptor *ld, __be64 *ptr,
int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
unsigned int blks = be32_to_cpu(ld->ld_length);
unsigned int revokes = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh;
unsigned int offset;
u64 blkno;
int first = 1;
int error;
if (pass != 0 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_REVOKE)
return 0;
offset = sizeof(struct gfs2_log_descriptor);
for (; blks; gfs2_replay_incr_blk(jd, &start), blks--) {
error = gfs2_replay_read_block(jd, start, &bh);
if (error)
return error;
if (!first)
gfs2_metatype_check(sdp, bh, GFS2_METATYPE_LB);
while (offset + sizeof(u64) <= sdp->sd_sb.sb_bsize) {
blkno = be64_to_cpu(*(__be64 *)(bh->b_data + offset));
error = gfs2_revoke_add(jd, blkno, start);
if (error < 0) {
brelse(bh);
return error;
}
else if (error)
jd->jd_found_revokes++;
if (!--revokes)
break;
offset += sizeof(u64);
}
brelse(bh);
offset = sizeof(struct gfs2_meta_header);
first = 0;
}
return 0;
}
static void revoke_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_revoke_clean(jd);
return;
}
if (pass != 1)
return;
fs_info(sdp, "jid=%u: Found %u revoke tags\n",
jd->jd_jid, jd->jd_found_revokes);
gfs2_revoke_clean(jd);
}
/**
* databuf_lo_before_commit - Scan the data buffers, writing as we go
* @sdp: The filesystem
* @tr: The system transaction being flushed
*/
static void databuf_lo_before_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
unsigned int limit = databuf_limit(sdp);
unsigned int nbuf;
if (tr == NULL)
return;
nbuf = tr->tr_num_databuf_new - tr->tr_num_databuf_rm;
gfs2_before_commit(sdp, limit, nbuf, &tr->tr_databuf, 1);
}
static int databuf_lo_scan_elements(struct gfs2_jdesc *jd, u32 start,
struct gfs2_log_descriptor *ld,
__be64 *ptr, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_glock *gl = ip->i_gl;
unsigned int blks = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh_log, *bh_ip;
u64 blkno;
u64 esc;
int error = 0;
if (pass != 1 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_JDATA)
return 0;
gfs2_replay_incr_blk(jd, &start);
for (; blks; gfs2_replay_incr_blk(jd, &start), blks--) {
blkno = be64_to_cpu(*ptr++);
esc = be64_to_cpu(*ptr++);
jd->jd_found_blocks++;
if (gfs2_revoke_check(jd, blkno, start))
continue;
error = gfs2_replay_read_block(jd, start, &bh_log);
if (error)
return error;
bh_ip = gfs2_meta_new(gl, blkno);
memcpy(bh_ip->b_data, bh_log->b_data, bh_log->b_size);
/* Unescape */
if (esc) {
__be32 *eptr = (__be32 *)bh_ip->b_data;
*eptr = cpu_to_be32(GFS2_MAGIC);
}
mark_buffer_dirty(bh_ip);
brelse(bh_log);
brelse(bh_ip);
jd->jd_replayed_blocks++;
}
return error;
}
/* FIXME: sort out accounting for log blocks etc. */
static void databuf_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_inode_metasync(ip->i_gl);
return;
}
if (pass != 1)
return;
/* data sync? */
gfs2_inode_metasync(ip->i_gl);
fs_info(sdp, "jid=%u: Replayed %u of %u data blocks\n",
jd->jd_jid, jd->jd_replayed_blocks, jd->jd_found_blocks);
}
static void databuf_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
struct list_head *head;
struct gfs2_bufdata *bd;
if (tr == NULL)
return;
head = &tr->tr_databuf;
while (!list_empty(head)) {
bd = list_first_entry(head, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
gfs2_unpin(sdp, bd->bd_bh, tr);
}
}
static const struct gfs2_log_operations gfs2_buf_lops = {
.lo_before_commit = buf_lo_before_commit,
.lo_after_commit = buf_lo_after_commit,
.lo_before_scan = buf_lo_before_scan,
.lo_scan_elements = buf_lo_scan_elements,
.lo_after_scan = buf_lo_after_scan,
.lo_name = "buf",
};
static const struct gfs2_log_operations gfs2_revoke_lops = {
.lo_before_commit = revoke_lo_before_commit,
.lo_after_commit = revoke_lo_after_commit,
.lo_before_scan = revoke_lo_before_scan,
.lo_scan_elements = revoke_lo_scan_elements,
.lo_after_scan = revoke_lo_after_scan,
.lo_name = "revoke",
};
static const struct gfs2_log_operations gfs2_databuf_lops = {
.lo_before_commit = databuf_lo_before_commit,
.lo_after_commit = databuf_lo_after_commit,
.lo_scan_elements = databuf_lo_scan_elements,
.lo_after_scan = databuf_lo_after_scan,
.lo_name = "databuf",
};
const struct gfs2_log_operations *gfs2_log_ops[] = {
&gfs2_databuf_lops,
&gfs2_buf_lops,
&gfs2_revoke_lops,
NULL,
};
| linux-master | fs/gfs2/lops.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2011 Red Hat, Inc. All rights reserved.
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/namei.h>
#include <linux/mm.h>
#include <linux/cred.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/iomap.h>
#include <linux/security.h>
#include <linux/fiemap.h>
#include <linux/uaccess.h>
#include "gfs2.h"
#include "incore.h"
#include "acl.h"
#include "bmap.h"
#include "dir.h"
#include "xattr.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
#include "super.h"
#include "glops.h"
static const struct inode_operations gfs2_file_iops;
static const struct inode_operations gfs2_dir_iops;
static const struct inode_operations gfs2_symlink_iops;
/**
* gfs2_set_iop - Sets inode operations
* @inode: The inode with correct i_mode filled in
*
* GFS2 lookup code fills in vfs inode contents based on info obtained
* from directory entry inside gfs2_inode_lookup().
*/
static void gfs2_set_iop(struct inode *inode)
{
struct gfs2_sbd *sdp = GFS2_SB(inode);
umode_t mode = inode->i_mode;
if (S_ISREG(mode)) {
inode->i_op = &gfs2_file_iops;
if (gfs2_localflocks(sdp))
inode->i_fop = &gfs2_file_fops_nolock;
else
inode->i_fop = &gfs2_file_fops;
} else if (S_ISDIR(mode)) {
inode->i_op = &gfs2_dir_iops;
if (gfs2_localflocks(sdp))
inode->i_fop = &gfs2_dir_fops_nolock;
else
inode->i_fop = &gfs2_dir_fops;
} else if (S_ISLNK(mode)) {
inode->i_op = &gfs2_symlink_iops;
} else {
inode->i_op = &gfs2_file_iops;
init_special_inode(inode, inode->i_mode, inode->i_rdev);
}
}
static int iget_test(struct inode *inode, void *opaque)
{
u64 no_addr = *(u64 *)opaque;
return GFS2_I(inode)->i_no_addr == no_addr;
}
static int iget_set(struct inode *inode, void *opaque)
{
u64 no_addr = *(u64 *)opaque;
GFS2_I(inode)->i_no_addr = no_addr;
inode->i_ino = no_addr;
return 0;
}
/**
* gfs2_inode_lookup - Lookup an inode
* @sb: The super block
* @type: The type of the inode
* @no_addr: The inode number
* @no_formal_ino: The inode generation number
* @blktype: Requested block type (GFS2_BLKST_DINODE or GFS2_BLKST_UNLINKED;
* GFS2_BLKST_FREE to indicate not to verify)
*
* If @type is DT_UNKNOWN, the inode type is fetched from disk.
*
* If @blktype is anything other than GFS2_BLKST_FREE (which is used as a
* placeholder because it doesn't otherwise make sense), the on-disk block type
* is verified to be @blktype.
*
* When @no_formal_ino is non-zero, this function will return ERR_PTR(-ESTALE)
* if it detects that @no_formal_ino doesn't match the actual inode generation
* number. However, it doesn't always know unless @type is DT_UNKNOWN.
*
* Returns: A VFS inode, or an error
*/
struct inode *gfs2_inode_lookup(struct super_block *sb, unsigned int type,
u64 no_addr, u64 no_formal_ino,
unsigned int blktype)
{
struct inode *inode;
struct gfs2_inode *ip;
struct gfs2_holder i_gh;
int error;
gfs2_holder_mark_uninitialized(&i_gh);
inode = iget5_locked(sb, no_addr, iget_test, iget_set, &no_addr);
if (!inode)
return ERR_PTR(-ENOMEM);
ip = GFS2_I(inode);
if (inode->i_state & I_NEW) {
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_glock *io_gl;
int extra_flags = 0;
error = gfs2_glock_get(sdp, no_addr, &gfs2_inode_glops, CREATE,
&ip->i_gl);
if (unlikely(error))
goto fail;
error = gfs2_glock_get(sdp, no_addr, &gfs2_iopen_glops, CREATE,
&io_gl);
if (unlikely(error))
goto fail;
/*
* The only caller that sets @blktype to GFS2_BLKST_UNLINKED is
* delete_work_func(). Make sure not to cancel the delete work
* from within itself here.
*/
if (blktype == GFS2_BLKST_UNLINKED)
extra_flags |= LM_FLAG_TRY;
else
gfs2_cancel_delete_work(io_gl);
error = gfs2_glock_nq_init(io_gl, LM_ST_SHARED,
GL_EXACT | GL_NOPID | extra_flags,
&ip->i_iopen_gh);
gfs2_glock_put(io_gl);
if (unlikely(error))
goto fail;
if (type == DT_UNKNOWN || blktype != GFS2_BLKST_FREE) {
/*
* The GL_SKIP flag indicates to skip reading the inode
* block. We read the inode when instantiating it
* after possibly checking the block type.
*/
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE,
GL_SKIP, &i_gh);
if (error)
goto fail;
error = -ESTALE;
if (no_formal_ino &&
gfs2_inode_already_deleted(ip->i_gl, no_formal_ino))
goto fail;
if (blktype != GFS2_BLKST_FREE) {
error = gfs2_check_blk_type(sdp, no_addr,
blktype);
if (error)
goto fail;
}
}
set_bit(GLF_INSTANTIATE_NEEDED, &ip->i_gl->gl_flags);
/* Lowest possible timestamp; will be overwritten in gfs2_dinode_in. */
inode->i_atime.tv_sec = 1LL << (8 * sizeof(inode->i_atime.tv_sec) - 1);
inode->i_atime.tv_nsec = 0;
glock_set_object(ip->i_gl, ip);
if (type == DT_UNKNOWN) {
/* Inode glock must be locked already */
error = gfs2_instantiate(&i_gh);
if (error) {
glock_clear_object(ip->i_gl, ip);
goto fail;
}
} else {
ip->i_no_formal_ino = no_formal_ino;
inode->i_mode = DT2IF(type);
}
if (gfs2_holder_initialized(&i_gh))
gfs2_glock_dq_uninit(&i_gh);
glock_set_object(ip->i_iopen_gh.gh_gl, ip);
gfs2_set_iop(inode);
unlock_new_inode(inode);
}
if (no_formal_ino && ip->i_no_formal_ino &&
no_formal_ino != ip->i_no_formal_ino) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
fail:
if (error == GLR_TRYFAILED)
error = -EAGAIN;
if (gfs2_holder_initialized(&ip->i_iopen_gh))
gfs2_glock_dq_uninit(&ip->i_iopen_gh);
if (gfs2_holder_initialized(&i_gh))
gfs2_glock_dq_uninit(&i_gh);
if (ip->i_gl) {
gfs2_glock_put(ip->i_gl);
ip->i_gl = NULL;
}
iget_failed(inode);
return ERR_PTR(error);
}
/**
* gfs2_lookup_by_inum - look up an inode by inode number
* @sdp: The super block
* @no_addr: The inode number
* @no_formal_ino: The inode generation number (0 for any)
* @blktype: Requested block type (see gfs2_inode_lookup)
*/
struct inode *gfs2_lookup_by_inum(struct gfs2_sbd *sdp, u64 no_addr,
u64 no_formal_ino, unsigned int blktype)
{
struct super_block *sb = sdp->sd_vfs;
struct inode *inode;
int error;
inode = gfs2_inode_lookup(sb, DT_UNKNOWN, no_addr, no_formal_ino,
blktype);
if (IS_ERR(inode))
return inode;
if (no_formal_ino) {
error = -EIO;
if (GFS2_I(inode)->i_diskflags & GFS2_DIF_SYSTEM)
goto fail_iput;
}
return inode;
fail_iput:
iput(inode);
return ERR_PTR(error);
}
struct inode *gfs2_lookup_simple(struct inode *dip, const char *name)
{
struct qstr qstr;
struct inode *inode;
gfs2_str2qstr(&qstr, name);
inode = gfs2_lookupi(dip, &qstr, 1);
/* gfs2_lookupi has inconsistent callers: vfs
* related routines expect NULL for no entry found,
* gfs2_lookup_simple callers expect ENOENT
* and do not check for NULL.
*/
if (IS_ERR_OR_NULL(inode))
return inode ? inode : ERR_PTR(-ENOENT);
/*
* Must not call back into the filesystem when allocating
* pages in the metadata inode's address space.
*/
mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
return inode;
}
/**
* gfs2_lookupi - Look up a filename in a directory and return its inode
* @dir: The inode of the directory containing the inode to look-up
* @name: The name of the inode to look for
* @is_root: If 1, ignore the caller's permissions
*
* This can be called via the VFS filldir function when NFS is doing
* a readdirplus and the inode which its intending to stat isn't
* already in cache. In this case we must not take the directory glock
* again, since the readdir call will have already taken that lock.
*
* Returns: errno
*/
struct inode *gfs2_lookupi(struct inode *dir, const struct qstr *name,
int is_root)
{
struct super_block *sb = dir->i_sb;
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_holder d_gh;
int error = 0;
struct inode *inode = NULL;
gfs2_holder_mark_uninitialized(&d_gh);
if (!name->len || name->len > GFS2_FNAMESIZE)
return ERR_PTR(-ENAMETOOLONG);
if ((name->len == 1 && memcmp(name->name, ".", 1) == 0) ||
(name->len == 2 && memcmp(name->name, "..", 2) == 0 &&
dir == d_inode(sb->s_root))) {
igrab(dir);
return dir;
}
if (gfs2_glock_is_locked_by_me(dip->i_gl) == NULL) {
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
if (error)
return ERR_PTR(error);
}
if (!is_root) {
error = gfs2_permission(&nop_mnt_idmap, dir, MAY_EXEC);
if (error)
goto out;
}
inode = gfs2_dir_search(dir, name, false);
if (IS_ERR(inode))
error = PTR_ERR(inode);
out:
if (gfs2_holder_initialized(&d_gh))
gfs2_glock_dq_uninit(&d_gh);
if (error == -ENOENT)
return NULL;
return inode ? inode : ERR_PTR(error);
}
/**
* create_ok - OK to create a new on-disk inode here?
* @dip: Directory in which dinode is to be created
* @name: Name of new dinode
* @mode:
*
* Returns: errno
*/
static int create_ok(struct gfs2_inode *dip, const struct qstr *name,
umode_t mode)
{
int error;
error = gfs2_permission(&nop_mnt_idmap, &dip->i_inode,
MAY_WRITE | MAY_EXEC);
if (error)
return error;
/* Don't create entries in an unlinked directory */
if (!dip->i_inode.i_nlink)
return -ENOENT;
if (dip->i_entries == (u32)-1)
return -EFBIG;
if (S_ISDIR(mode) && dip->i_inode.i_nlink == (u32)-1)
return -EMLINK;
return 0;
}
static void munge_mode_uid_gid(const struct gfs2_inode *dip,
struct inode *inode)
{
if (GFS2_SB(&dip->i_inode)->sd_args.ar_suiddir &&
(dip->i_inode.i_mode & S_ISUID) &&
!uid_eq(dip->i_inode.i_uid, GLOBAL_ROOT_UID)) {
if (S_ISDIR(inode->i_mode))
inode->i_mode |= S_ISUID;
else if (!uid_eq(dip->i_inode.i_uid, current_fsuid()))
inode->i_mode &= ~07111;
inode->i_uid = dip->i_inode.i_uid;
} else
inode->i_uid = current_fsuid();
if (dip->i_inode.i_mode & S_ISGID) {
if (S_ISDIR(inode->i_mode))
inode->i_mode |= S_ISGID;
inode->i_gid = dip->i_inode.i_gid;
} else
inode->i_gid = current_fsgid();
}
static int alloc_dinode(struct gfs2_inode *ip, u32 flags, unsigned *dblocks)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_alloc_parms ap = { .target = *dblocks, .aflags = flags, };
int error;
error = gfs2_quota_lock_check(ip, &ap);
if (error)
goto out;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto out_quota;
error = gfs2_trans_begin(sdp, (*dblocks * RES_RG_BIT) + RES_STATFS + RES_QUOTA, 0);
if (error)
goto out_ipreserv;
error = gfs2_alloc_blocks(ip, &ip->i_no_addr, dblocks, 1, &ip->i_generation);
if (error)
goto out_trans_end;
ip->i_no_formal_ino = ip->i_generation;
ip->i_inode.i_ino = ip->i_no_addr;
ip->i_goal = ip->i_no_addr;
if (*dblocks > 1)
ip->i_eattr = ip->i_no_addr + 1;
out_trans_end:
gfs2_trans_end(sdp);
out_ipreserv:
gfs2_inplace_release(ip);
out_quota:
gfs2_quota_unlock(ip);
out:
return error;
}
static void gfs2_init_dir(struct buffer_head *dibh,
const struct gfs2_inode *parent)
{
struct gfs2_dinode *di = (struct gfs2_dinode *)dibh->b_data;
struct gfs2_dirent *dent = (struct gfs2_dirent *)(di+1);
gfs2_qstr2dirent(&gfs2_qdot, GFS2_DIRENT_SIZE(gfs2_qdot.len), dent);
dent->de_inum = di->di_num; /* already GFS2 endian */
dent->de_type = cpu_to_be16(DT_DIR);
dent = (struct gfs2_dirent *)((char*)dent + GFS2_DIRENT_SIZE(1));
gfs2_qstr2dirent(&gfs2_qdotdot, dibh->b_size - GFS2_DIRENT_SIZE(1) - sizeof(struct gfs2_dinode), dent);
gfs2_inum_out(parent, dent);
dent->de_type = cpu_to_be16(DT_DIR);
}
/**
* gfs2_init_xattr - Initialise an xattr block for a new inode
* @ip: The inode in question
*
* This sets up an empty xattr block for a new inode, ready to
* take any ACLs, LSM xattrs, etc.
*/
static void gfs2_init_xattr(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *bh;
struct gfs2_ea_header *ea;
bh = gfs2_meta_new(ip->i_gl, ip->i_eattr);
gfs2_trans_add_meta(ip->i_gl, bh);
gfs2_metatype_set(bh, GFS2_METATYPE_EA, GFS2_FORMAT_EA);
gfs2_buffer_clear_tail(bh, sizeof(struct gfs2_meta_header));
ea = GFS2_EA_BH2FIRST(bh);
ea->ea_rec_len = cpu_to_be32(sdp->sd_jbsize);
ea->ea_type = GFS2_EATYPE_UNUSED;
ea->ea_flags = GFS2_EAFLAG_LAST;
brelse(bh);
}
/**
* init_dinode - Fill in a new dinode structure
* @dip: The directory this inode is being created in
* @ip: The inode
* @symname: The symlink destination (if a symlink)
*
*/
static void init_dinode(struct gfs2_inode *dip, struct gfs2_inode *ip,
const char *symname)
{
struct gfs2_dinode *di;
struct buffer_head *dibh;
dibh = gfs2_meta_new(ip->i_gl, ip->i_no_addr);
gfs2_trans_add_meta(ip->i_gl, dibh);
di = (struct gfs2_dinode *)dibh->b_data;
gfs2_dinode_out(ip, di);
di->di_major = cpu_to_be32(imajor(&ip->i_inode));
di->di_minor = cpu_to_be32(iminor(&ip->i_inode));
di->__pad1 = 0;
di->__pad2 = 0;
di->__pad3 = 0;
memset(&di->__pad4, 0, sizeof(di->__pad4));
memset(&di->di_reserved, 0, sizeof(di->di_reserved));
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
switch(ip->i_inode.i_mode & S_IFMT) {
case S_IFDIR:
gfs2_init_dir(dibh, dip);
break;
case S_IFLNK:
memcpy(dibh->b_data + sizeof(struct gfs2_dinode), symname, ip->i_inode.i_size);
break;
}
set_buffer_uptodate(dibh);
brelse(dibh);
}
/**
* gfs2_trans_da_blks - Calculate number of blocks to link inode
* @dip: The directory we are linking into
* @da: The dir add information
* @nr_inodes: The number of inodes involved
*
* This calculate the number of blocks we need to reserve in a
* transaction to link @nr_inodes into a directory. In most cases
* @nr_inodes will be 2 (the directory plus the inode being linked in)
* but in case of rename, 4 may be required.
*
* Returns: Number of blocks
*/
static unsigned gfs2_trans_da_blks(const struct gfs2_inode *dip,
const struct gfs2_diradd *da,
unsigned nr_inodes)
{
return da->nr_blocks + gfs2_rg_blocks(dip, da->nr_blocks) +
(nr_inodes * RES_DINODE) + RES_QUOTA + RES_STATFS;
}
static int link_dinode(struct gfs2_inode *dip, const struct qstr *name,
struct gfs2_inode *ip, struct gfs2_diradd *da)
{
struct gfs2_sbd *sdp = GFS2_SB(&dip->i_inode);
struct gfs2_alloc_parms ap = { .target = da->nr_blocks, };
int error;
if (da->nr_blocks) {
error = gfs2_quota_lock_check(dip, &ap);
if (error)
goto fail_quota_locks;
error = gfs2_inplace_reserve(dip, &ap);
if (error)
goto fail_quota_locks;
error = gfs2_trans_begin(sdp, gfs2_trans_da_blks(dip, da, 2), 0);
if (error)
goto fail_ipreserv;
} else {
error = gfs2_trans_begin(sdp, RES_LEAF + 2 * RES_DINODE, 0);
if (error)
goto fail_quota_locks;
}
error = gfs2_dir_add(&dip->i_inode, name, ip, da);
gfs2_trans_end(sdp);
fail_ipreserv:
gfs2_inplace_release(dip);
fail_quota_locks:
gfs2_quota_unlock(dip);
return error;
}
static int gfs2_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *fs_info)
{
const struct xattr *xattr;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
err = __gfs2_xattr_set(inode, xattr->name, xattr->value,
xattr->value_len, 0,
GFS2_EATYPE_SECURITY);
if (err < 0)
break;
}
return err;
}
/**
* gfs2_create_inode - Create a new inode
* @dir: The parent directory
* @dentry: The new dentry
* @file: If non-NULL, the file which is being opened
* @mode: The permissions on the new inode
* @dev: For device nodes, this is the device number
* @symname: For symlinks, this is the link destination
* @size: The initial size of the inode (ignored for directories)
* @excl: Force fail if inode exists
*
* FIXME: Change to allocate the disk blocks and write them out in the same
* transaction. That way, we can no longer end up in a situation in which an
* inode is allocated, the node crashes, and the block looks like a valid
* inode. (With atomic creates in place, we will also no longer need to zero
* the link count and dirty the inode here on failure.)
*
* Returns: 0 on success, or error code
*/
static int gfs2_create_inode(struct inode *dir, struct dentry *dentry,
struct file *file,
umode_t mode, dev_t dev, const char *symname,
unsigned int size, int excl)
{
const struct qstr *name = &dentry->d_name;
struct posix_acl *default_acl, *acl;
struct gfs2_holder d_gh, gh;
struct inode *inode = NULL;
struct gfs2_inode *dip = GFS2_I(dir), *ip;
struct gfs2_sbd *sdp = GFS2_SB(&dip->i_inode);
struct gfs2_glock *io_gl;
int error;
u32 aflags = 0;
unsigned blocks = 1;
struct gfs2_diradd da = { .bh = NULL, .save_loc = 1, };
if (!name->len || name->len > GFS2_FNAMESIZE)
return -ENAMETOOLONG;
error = gfs2_qa_get(dip);
if (error)
return error;
error = gfs2_rindex_update(sdp);
if (error)
goto fail;
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_EXCLUSIVE, 0, &d_gh);
if (error)
goto fail;
gfs2_holder_mark_uninitialized(&gh);
error = create_ok(dip, name, mode);
if (error)
goto fail_gunlock;
inode = gfs2_dir_search(dir, &dentry->d_name, !S_ISREG(mode) || excl);
error = PTR_ERR(inode);
if (!IS_ERR(inode)) {
if (S_ISDIR(inode->i_mode)) {
iput(inode);
inode = ERR_PTR(-EISDIR);
goto fail_gunlock;
}
d_instantiate(dentry, inode);
error = 0;
if (file) {
if (S_ISREG(inode->i_mode))
error = finish_open(file, dentry, gfs2_open_common);
else
error = finish_no_open(file, NULL);
}
gfs2_glock_dq_uninit(&d_gh);
goto fail;
} else if (error != -ENOENT) {
goto fail_gunlock;
}
error = gfs2_diradd_alloc_required(dir, name, &da);
if (error < 0)
goto fail_gunlock;
inode = new_inode(sdp->sd_vfs);
error = -ENOMEM;
if (!inode)
goto fail_gunlock;
ip = GFS2_I(inode);
error = posix_acl_create(dir, &mode, &default_acl, &acl);
if (error)
goto fail_gunlock;
error = gfs2_qa_get(ip);
if (error)
goto fail_free_acls;
inode->i_mode = mode;
set_nlink(inode, S_ISDIR(mode) ? 2 : 1);
inode->i_rdev = dev;
inode->i_size = size;
inode->i_atime = inode->i_mtime = inode_set_ctime_current(inode);
munge_mode_uid_gid(dip, inode);
check_and_update_goal(dip);
ip->i_goal = dip->i_goal;
ip->i_diskflags = 0;
ip->i_eattr = 0;
ip->i_height = 0;
ip->i_depth = 0;
ip->i_entries = 0;
ip->i_no_addr = 0; /* Temporarily zero until real addr is assigned */
switch(mode & S_IFMT) {
case S_IFREG:
if ((dip->i_diskflags & GFS2_DIF_INHERIT_JDATA) ||
gfs2_tune_get(sdp, gt_new_files_jdata))
ip->i_diskflags |= GFS2_DIF_JDATA;
gfs2_set_aops(inode);
break;
case S_IFDIR:
ip->i_diskflags |= (dip->i_diskflags & GFS2_DIF_INHERIT_JDATA);
ip->i_diskflags |= GFS2_DIF_JDATA;
ip->i_entries = 2;
break;
}
/* Force SYSTEM flag on all files and subdirs of a SYSTEM directory */
if (dip->i_diskflags & GFS2_DIF_SYSTEM)
ip->i_diskflags |= GFS2_DIF_SYSTEM;
gfs2_set_inode_flags(inode);
if ((GFS2_I(d_inode(sdp->sd_root_dir)) == dip) ||
(dip->i_diskflags & GFS2_DIF_TOPDIR))
aflags |= GFS2_AF_ORLOV;
if (default_acl || acl)
blocks++;
error = alloc_dinode(ip, aflags, &blocks);
if (error)
goto fail_free_inode;
gfs2_set_inode_blocks(inode, blocks);
error = gfs2_glock_get(sdp, ip->i_no_addr, &gfs2_inode_glops, CREATE, &ip->i_gl);
if (error)
goto fail_free_inode;
error = gfs2_glock_get(sdp, ip->i_no_addr, &gfs2_iopen_glops, CREATE, &io_gl);
if (error)
goto fail_free_inode;
gfs2_cancel_delete_work(io_gl);
retry:
error = insert_inode_locked4(inode, ip->i_no_addr, iget_test, &ip->i_no_addr);
if (error == -EBUSY)
goto retry;
if (error)
goto fail_gunlock2;
error = gfs2_glock_nq_init(io_gl, LM_ST_SHARED, GL_EXACT | GL_NOPID,
&ip->i_iopen_gh);
if (error)
goto fail_gunlock2;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, GL_SKIP, &gh);
if (error)
goto fail_gunlock3;
error = gfs2_trans_begin(sdp, blocks, 0);
if (error)
goto fail_gunlock3;
if (blocks > 1)
gfs2_init_xattr(ip);
init_dinode(dip, ip, symname);
gfs2_trans_end(sdp);
glock_set_object(ip->i_gl, ip);
glock_set_object(io_gl, ip);
gfs2_set_iop(inode);
if (default_acl) {
error = __gfs2_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
if (error)
goto fail_gunlock4;
posix_acl_release(default_acl);
default_acl = NULL;
}
if (acl) {
error = __gfs2_set_acl(inode, acl, ACL_TYPE_ACCESS);
if (error)
goto fail_gunlock4;
posix_acl_release(acl);
acl = NULL;
}
error = security_inode_init_security(&ip->i_inode, &dip->i_inode, name,
&gfs2_initxattrs, NULL);
if (error)
goto fail_gunlock4;
error = link_dinode(dip, name, ip, &da);
if (error)
goto fail_gunlock4;
mark_inode_dirty(inode);
d_instantiate(dentry, inode);
/* After instantiate, errors should result in evict which will destroy
* both inode and iopen glocks properly. */
if (file) {
file->f_mode |= FMODE_CREATED;
error = finish_open(file, dentry, gfs2_open_common);
}
gfs2_glock_dq_uninit(&d_gh);
gfs2_qa_put(ip);
gfs2_glock_dq_uninit(&gh);
gfs2_glock_put(io_gl);
gfs2_qa_put(dip);
unlock_new_inode(inode);
return error;
fail_gunlock4:
glock_clear_object(ip->i_gl, ip);
glock_clear_object(io_gl, ip);
fail_gunlock3:
gfs2_glock_dq_uninit(&ip->i_iopen_gh);
fail_gunlock2:
gfs2_glock_put(io_gl);
fail_free_inode:
if (ip->i_gl) {
gfs2_glock_put(ip->i_gl);
ip->i_gl = NULL;
}
gfs2_rs_deltree(&ip->i_res);
gfs2_qa_put(ip);
fail_free_acls:
posix_acl_release(default_acl);
posix_acl_release(acl);
fail_gunlock:
gfs2_dir_no_add(&da);
gfs2_glock_dq_uninit(&d_gh);
if (!IS_ERR_OR_NULL(inode)) {
set_bit(GIF_ALLOC_FAILED, &ip->i_flags);
clear_nlink(inode);
if (ip->i_no_addr)
mark_inode_dirty(inode);
if (inode->i_state & I_NEW)
iget_failed(inode);
else
iput(inode);
}
if (gfs2_holder_initialized(&gh))
gfs2_glock_dq_uninit(&gh);
fail:
gfs2_qa_put(dip);
return error;
}
/**
* gfs2_create - Create a file
* @idmap: idmap of the mount the inode was found from
* @dir: The directory in which to create the file
* @dentry: The dentry of the new file
* @mode: The mode of the new file
* @excl: Force fail if inode exists
*
* Returns: errno
*/
static int gfs2_create(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, bool excl)
{
return gfs2_create_inode(dir, dentry, NULL, S_IFREG | mode, 0, NULL, 0, excl);
}
/**
* __gfs2_lookup - Look up a filename in a directory and return its inode
* @dir: The directory inode
* @dentry: The dentry of the new inode
* @file: File to be opened
*
*
* Returns: errno
*/
static struct dentry *__gfs2_lookup(struct inode *dir, struct dentry *dentry,
struct file *file)
{
struct inode *inode;
struct dentry *d;
struct gfs2_holder gh;
struct gfs2_glock *gl;
int error;
inode = gfs2_lookupi(dir, &dentry->d_name, 0);
if (inode == NULL) {
d_add(dentry, NULL);
return NULL;
}
if (IS_ERR(inode))
return ERR_CAST(inode);
gl = GFS2_I(inode)->i_gl;
error = gfs2_glock_nq_init(gl, LM_ST_SHARED, LM_FLAG_ANY, &gh);
if (error) {
iput(inode);
return ERR_PTR(error);
}
d = d_splice_alias(inode, dentry);
if (IS_ERR(d)) {
gfs2_glock_dq_uninit(&gh);
return d;
}
if (file && S_ISREG(inode->i_mode))
error = finish_open(file, dentry, gfs2_open_common);
gfs2_glock_dq_uninit(&gh);
if (error) {
dput(d);
return ERR_PTR(error);
}
return d;
}
static struct dentry *gfs2_lookup(struct inode *dir, struct dentry *dentry,
unsigned flags)
{
return __gfs2_lookup(dir, dentry, NULL);
}
/**
* gfs2_link - Link to a file
* @old_dentry: The inode to link
* @dir: Add link to this directory
* @dentry: The name of the link
*
* Link the inode in "old_dentry" into the directory "dir" with the
* name in "dentry".
*
* Returns: errno
*/
static int gfs2_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_sbd *sdp = GFS2_SB(dir);
struct inode *inode = d_inode(old_dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder d_gh, gh;
struct buffer_head *dibh;
struct gfs2_diradd da = { .bh = NULL, .save_loc = 1, };
int error;
if (S_ISDIR(inode->i_mode))
return -EPERM;
error = gfs2_qa_get(dip);
if (error)
return error;
gfs2_holder_init(dip->i_gl, LM_ST_EXCLUSIVE, 0, &d_gh);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
error = gfs2_glock_nq(&d_gh);
if (error)
goto out_parent;
error = gfs2_glock_nq(&gh);
if (error)
goto out_child;
error = -ENOENT;
if (inode->i_nlink == 0)
goto out_gunlock;
error = gfs2_permission(&nop_mnt_idmap, dir, MAY_WRITE | MAY_EXEC);
if (error)
goto out_gunlock;
error = gfs2_dir_check(dir, &dentry->d_name, NULL);
switch (error) {
case -ENOENT:
break;
case 0:
error = -EEXIST;
goto out_gunlock;
default:
goto out_gunlock;
}
error = -EINVAL;
if (!dip->i_inode.i_nlink)
goto out_gunlock;
error = -EFBIG;
if (dip->i_entries == (u32)-1)
goto out_gunlock;
error = -EPERM;
if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
goto out_gunlock;
error = -EMLINK;
if (ip->i_inode.i_nlink == (u32)-1)
goto out_gunlock;
error = gfs2_diradd_alloc_required(dir, &dentry->d_name, &da);
if (error < 0)
goto out_gunlock;
if (da.nr_blocks) {
struct gfs2_alloc_parms ap = { .target = da.nr_blocks, };
error = gfs2_quota_lock_check(dip, &ap);
if (error)
goto out_gunlock;
error = gfs2_inplace_reserve(dip, &ap);
if (error)
goto out_gunlock_q;
error = gfs2_trans_begin(sdp, gfs2_trans_da_blks(dip, &da, 2), 0);
if (error)
goto out_ipres;
} else {
error = gfs2_trans_begin(sdp, 2 * RES_DINODE + RES_LEAF, 0);
if (error)
goto out_ipres;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out_end_trans;
error = gfs2_dir_add(dir, &dentry->d_name, ip, &da);
if (error)
goto out_brelse;
gfs2_trans_add_meta(ip->i_gl, dibh);
inc_nlink(&ip->i_inode);
inode_set_ctime_current(&ip->i_inode);
ihold(inode);
d_instantiate(dentry, inode);
mark_inode_dirty(inode);
out_brelse:
brelse(dibh);
out_end_trans:
gfs2_trans_end(sdp);
out_ipres:
if (da.nr_blocks)
gfs2_inplace_release(dip);
out_gunlock_q:
if (da.nr_blocks)
gfs2_quota_unlock(dip);
out_gunlock:
gfs2_dir_no_add(&da);
gfs2_glock_dq(&gh);
out_child:
gfs2_glock_dq(&d_gh);
out_parent:
gfs2_qa_put(dip);
gfs2_holder_uninit(&d_gh);
gfs2_holder_uninit(&gh);
return error;
}
/*
* gfs2_unlink_ok - check to see that a inode is still in a directory
* @dip: the directory
* @name: the name of the file
* @ip: the inode
*
* Assumes that the lock on (at least) @dip is held.
*
* Returns: 0 if the parent/child relationship is correct, errno if it isn't
*/
static int gfs2_unlink_ok(struct gfs2_inode *dip, const struct qstr *name,
const struct gfs2_inode *ip)
{
int error;
if (IS_IMMUTABLE(&ip->i_inode) || IS_APPEND(&ip->i_inode))
return -EPERM;
if ((dip->i_inode.i_mode & S_ISVTX) &&
!uid_eq(dip->i_inode.i_uid, current_fsuid()) &&
!uid_eq(ip->i_inode.i_uid, current_fsuid()) && !capable(CAP_FOWNER))
return -EPERM;
if (IS_APPEND(&dip->i_inode))
return -EPERM;
error = gfs2_permission(&nop_mnt_idmap, &dip->i_inode,
MAY_WRITE | MAY_EXEC);
if (error)
return error;
return gfs2_dir_check(&dip->i_inode, name, ip);
}
/**
* gfs2_unlink_inode - Removes an inode from its parent dir and unlinks it
* @dip: The parent directory
* @dentry: The dentry to unlink
*
* Called with all the locks and in a transaction. This will only be
* called for a directory after it has been checked to ensure it is empty.
*
* Returns: 0 on success, or an error
*/
static int gfs2_unlink_inode(struct gfs2_inode *dip,
const struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
struct gfs2_inode *ip = GFS2_I(inode);
int error;
error = gfs2_dir_del(dip, dentry);
if (error)
return error;
ip->i_entries = 0;
inode_set_ctime_current(inode);
if (S_ISDIR(inode->i_mode))
clear_nlink(inode);
else
drop_nlink(inode);
mark_inode_dirty(inode);
if (inode->i_nlink == 0)
gfs2_unlink_di(inode);
return 0;
}
/**
* gfs2_unlink - Unlink an inode (this does rmdir as well)
* @dir: The inode of the directory containing the inode to unlink
* @dentry: The file itself
*
* This routine uses the type of the inode as a flag to figure out
* whether this is an unlink or an rmdir.
*
* Returns: errno
*/
static int gfs2_unlink(struct inode *dir, struct dentry *dentry)
{
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_sbd *sdp = GFS2_SB(dir);
struct inode *inode = d_inode(dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder d_gh, r_gh, gh;
struct gfs2_rgrpd *rgd;
int error;
error = gfs2_rindex_update(sdp);
if (error)
return error;
error = -EROFS;
gfs2_holder_init(dip->i_gl, LM_ST_EXCLUSIVE, 0, &d_gh);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
rgd = gfs2_blk2rgrpd(sdp, ip->i_no_addr, 1);
if (!rgd)
goto out_inodes;
gfs2_holder_init(rgd->rd_gl, LM_ST_EXCLUSIVE, LM_FLAG_NODE_SCOPE, &r_gh);
error = gfs2_glock_nq(&d_gh);
if (error)
goto out_parent;
error = gfs2_glock_nq(&gh);
if (error)
goto out_child;
error = -ENOENT;
if (inode->i_nlink == 0)
goto out_rgrp;
if (S_ISDIR(inode->i_mode)) {
error = -ENOTEMPTY;
if (ip->i_entries > 2 || inode->i_nlink > 2)
goto out_rgrp;
}
error = gfs2_glock_nq(&r_gh); /* rgrp */
if (error)
goto out_rgrp;
error = gfs2_unlink_ok(dip, &dentry->d_name, ip);
if (error)
goto out_gunlock;
error = gfs2_trans_begin(sdp, 2*RES_DINODE + 3*RES_LEAF + RES_RG_BIT, 0);
if (error)
goto out_gunlock;
error = gfs2_unlink_inode(dip, dentry);
gfs2_trans_end(sdp);
out_gunlock:
gfs2_glock_dq(&r_gh);
out_rgrp:
gfs2_glock_dq(&gh);
out_child:
gfs2_glock_dq(&d_gh);
out_parent:
gfs2_holder_uninit(&r_gh);
out_inodes:
gfs2_holder_uninit(&gh);
gfs2_holder_uninit(&d_gh);
return error;
}
/**
* gfs2_symlink - Create a symlink
* @idmap: idmap of the mount the inode was found from
* @dir: The directory to create the symlink in
* @dentry: The dentry to put the symlink in
* @symname: The thing which the link points to
*
* Returns: errno
*/
static int gfs2_symlink(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, const char *symname)
{
unsigned int size;
size = strlen(symname);
if (size >= gfs2_max_stuffed_size(GFS2_I(dir)))
return -ENAMETOOLONG;
return gfs2_create_inode(dir, dentry, NULL, S_IFLNK | S_IRWXUGO, 0, symname, size, 0);
}
/**
* gfs2_mkdir - Make a directory
* @idmap: idmap of the mount the inode was found from
* @dir: The parent directory of the new one
* @dentry: The dentry of the new directory
* @mode: The mode of the new directory
*
* Returns: errno
*/
static int gfs2_mkdir(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode)
{
unsigned dsize = gfs2_max_stuffed_size(GFS2_I(dir));
return gfs2_create_inode(dir, dentry, NULL, S_IFDIR | mode, 0, NULL, dsize, 0);
}
/**
* gfs2_mknod - Make a special file
* @idmap: idmap of the mount the inode was found from
* @dir: The directory in which the special file will reside
* @dentry: The dentry of the special file
* @mode: The mode of the special file
* @dev: The device specification of the special file
*
*/
static int gfs2_mknod(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, dev_t dev)
{
return gfs2_create_inode(dir, dentry, NULL, mode, dev, NULL, 0, 0);
}
/**
* gfs2_atomic_open - Atomically open a file
* @dir: The directory
* @dentry: The proposed new entry
* @file: The proposed new struct file
* @flags: open flags
* @mode: File mode
*
* Returns: error code or 0 for success
*/
static int gfs2_atomic_open(struct inode *dir, struct dentry *dentry,
struct file *file, unsigned flags,
umode_t mode)
{
struct dentry *d;
bool excl = !!(flags & O_EXCL);
if (!d_in_lookup(dentry))
goto skip_lookup;
d = __gfs2_lookup(dir, dentry, file);
if (IS_ERR(d))
return PTR_ERR(d);
if (d != NULL)
dentry = d;
if (d_really_is_positive(dentry)) {
if (!(file->f_mode & FMODE_OPENED))
return finish_no_open(file, d);
dput(d);
return excl && (flags & O_CREAT) ? -EEXIST : 0;
}
BUG_ON(d != NULL);
skip_lookup:
if (!(flags & O_CREAT))
return -ENOENT;
return gfs2_create_inode(dir, dentry, file, S_IFREG | mode, 0, NULL, 0, excl);
}
/*
* gfs2_ok_to_move - check if it's ok to move a directory to another directory
* @this: move this
* @to: to here
*
* Follow @to back to the root and make sure we don't encounter @this
* Assumes we already hold the rename lock.
*
* Returns: errno
*/
static int gfs2_ok_to_move(struct gfs2_inode *this, struct gfs2_inode *to)
{
struct inode *dir = &to->i_inode;
struct super_block *sb = dir->i_sb;
struct inode *tmp;
int error = 0;
igrab(dir);
for (;;) {
if (dir == &this->i_inode) {
error = -EINVAL;
break;
}
if (dir == d_inode(sb->s_root)) {
error = 0;
break;
}
tmp = gfs2_lookupi(dir, &gfs2_qdotdot, 1);
if (!tmp) {
error = -ENOENT;
break;
}
if (IS_ERR(tmp)) {
error = PTR_ERR(tmp);
break;
}
iput(dir);
dir = tmp;
}
iput(dir);
return error;
}
/**
* update_moved_ino - Update an inode that's being moved
* @ip: The inode being moved
* @ndip: The parent directory of the new filename
* @dir_rename: True of ip is a directory
*
* Returns: errno
*/
static int update_moved_ino(struct gfs2_inode *ip, struct gfs2_inode *ndip,
int dir_rename)
{
if (dir_rename)
return gfs2_dir_mvino(ip, &gfs2_qdotdot, ndip, DT_DIR);
inode_set_ctime_current(&ip->i_inode);
mark_inode_dirty_sync(&ip->i_inode);
return 0;
}
/**
* gfs2_rename - Rename a file
* @odir: Parent directory of old file name
* @odentry: The old dentry of the file
* @ndir: Parent directory of new file name
* @ndentry: The new dentry of the file
*
* Returns: errno
*/
static int gfs2_rename(struct inode *odir, struct dentry *odentry,
struct inode *ndir, struct dentry *ndentry)
{
struct gfs2_inode *odip = GFS2_I(odir);
struct gfs2_inode *ndip = GFS2_I(ndir);
struct gfs2_inode *ip = GFS2_I(d_inode(odentry));
struct gfs2_inode *nip = NULL;
struct gfs2_sbd *sdp = GFS2_SB(odir);
struct gfs2_holder ghs[4], r_gh, rd_gh;
struct gfs2_rgrpd *nrgd;
unsigned int num_gh;
int dir_rename = 0;
struct gfs2_diradd da = { .nr_blocks = 0, .save_loc = 0, };
unsigned int x;
int error;
gfs2_holder_mark_uninitialized(&r_gh);
gfs2_holder_mark_uninitialized(&rd_gh);
if (d_really_is_positive(ndentry)) {
nip = GFS2_I(d_inode(ndentry));
if (ip == nip)
return 0;
}
error = gfs2_rindex_update(sdp);
if (error)
return error;
error = gfs2_qa_get(ndip);
if (error)
return error;
if (odip != ndip) {
error = gfs2_glock_nq_init(sdp->sd_rename_gl, LM_ST_EXCLUSIVE,
0, &r_gh);
if (error)
goto out;
if (S_ISDIR(ip->i_inode.i_mode)) {
dir_rename = 1;
/* don't move a directory into its subdir */
error = gfs2_ok_to_move(ip, ndip);
if (error)
goto out_gunlock_r;
}
}
num_gh = 1;
gfs2_holder_init(odip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC, ghs);
if (odip != ndip) {
gfs2_holder_init(ndip->i_gl, LM_ST_EXCLUSIVE,GL_ASYNC,
ghs + num_gh);
num_gh++;
}
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC, ghs + num_gh);
num_gh++;
if (nip) {
gfs2_holder_init(nip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC,
ghs + num_gh);
num_gh++;
}
for (x = 0; x < num_gh; x++) {
error = gfs2_glock_nq(ghs + x);
if (error)
goto out_gunlock;
}
error = gfs2_glock_async_wait(num_gh, ghs);
if (error)
goto out_gunlock;
if (nip) {
/* Grab the resource group glock for unlink flag twiddling.
* This is the case where the target dinode already exists
* so we unlink before doing the rename.
*/
nrgd = gfs2_blk2rgrpd(sdp, nip->i_no_addr, 1);
if (!nrgd) {
error = -ENOENT;
goto out_gunlock;
}
error = gfs2_glock_nq_init(nrgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, &rd_gh);
if (error)
goto out_gunlock;
}
error = -ENOENT;
if (ip->i_inode.i_nlink == 0)
goto out_gunlock;
/* Check out the old directory */
error = gfs2_unlink_ok(odip, &odentry->d_name, ip);
if (error)
goto out_gunlock;
/* Check out the new directory */
if (nip) {
error = gfs2_unlink_ok(ndip, &ndentry->d_name, nip);
if (error)
goto out_gunlock;
if (nip->i_inode.i_nlink == 0) {
error = -EAGAIN;
goto out_gunlock;
}
if (S_ISDIR(nip->i_inode.i_mode)) {
if (nip->i_entries < 2) {
gfs2_consist_inode(nip);
error = -EIO;
goto out_gunlock;
}
if (nip->i_entries > 2) {
error = -ENOTEMPTY;
goto out_gunlock;
}
}
} else {
error = gfs2_permission(&nop_mnt_idmap, ndir,
MAY_WRITE | MAY_EXEC);
if (error)
goto out_gunlock;
error = gfs2_dir_check(ndir, &ndentry->d_name, NULL);
switch (error) {
case -ENOENT:
error = 0;
break;
case 0:
error = -EEXIST;
goto out_gunlock;
default:
goto out_gunlock;
}
if (odip != ndip) {
if (!ndip->i_inode.i_nlink) {
error = -ENOENT;
goto out_gunlock;
}
if (ndip->i_entries == (u32)-1) {
error = -EFBIG;
goto out_gunlock;
}
if (S_ISDIR(ip->i_inode.i_mode) &&
ndip->i_inode.i_nlink == (u32)-1) {
error = -EMLINK;
goto out_gunlock;
}
}
}
/* Check out the dir to be renamed */
if (dir_rename) {
error = gfs2_permission(&nop_mnt_idmap, d_inode(odentry),
MAY_WRITE);
if (error)
goto out_gunlock;
}
if (nip == NULL) {
error = gfs2_diradd_alloc_required(ndir, &ndentry->d_name, &da);
if (error)
goto out_gunlock;
}
if (da.nr_blocks) {
struct gfs2_alloc_parms ap = { .target = da.nr_blocks, };
error = gfs2_quota_lock_check(ndip, &ap);
if (error)
goto out_gunlock;
error = gfs2_inplace_reserve(ndip, &ap);
if (error)
goto out_gunlock_q;
error = gfs2_trans_begin(sdp, gfs2_trans_da_blks(ndip, &da, 4) +
4 * RES_LEAF + 4, 0);
if (error)
goto out_ipreserv;
} else {
error = gfs2_trans_begin(sdp, 4 * RES_DINODE +
5 * RES_LEAF + 4, 0);
if (error)
goto out_gunlock;
}
/* Remove the target file, if it exists */
if (nip)
error = gfs2_unlink_inode(ndip, ndentry);
error = update_moved_ino(ip, ndip, dir_rename);
if (error)
goto out_end_trans;
error = gfs2_dir_del(odip, odentry);
if (error)
goto out_end_trans;
error = gfs2_dir_add(ndir, &ndentry->d_name, ip, &da);
if (error)
goto out_end_trans;
out_end_trans:
gfs2_trans_end(sdp);
out_ipreserv:
if (da.nr_blocks)
gfs2_inplace_release(ndip);
out_gunlock_q:
if (da.nr_blocks)
gfs2_quota_unlock(ndip);
out_gunlock:
gfs2_dir_no_add(&da);
if (gfs2_holder_initialized(&rd_gh))
gfs2_glock_dq_uninit(&rd_gh);
while (x--) {
if (gfs2_holder_queued(ghs + x))
gfs2_glock_dq(ghs + x);
gfs2_holder_uninit(ghs + x);
}
out_gunlock_r:
if (gfs2_holder_initialized(&r_gh))
gfs2_glock_dq_uninit(&r_gh);
out:
gfs2_qa_put(ndip);
return error;
}
/**
* gfs2_exchange - exchange two files
* @odir: Parent directory of old file name
* @odentry: The old dentry of the file
* @ndir: Parent directory of new file name
* @ndentry: The new dentry of the file
* @flags: The rename flags
*
* Returns: errno
*/
static int gfs2_exchange(struct inode *odir, struct dentry *odentry,
struct inode *ndir, struct dentry *ndentry,
unsigned int flags)
{
struct gfs2_inode *odip = GFS2_I(odir);
struct gfs2_inode *ndip = GFS2_I(ndir);
struct gfs2_inode *oip = GFS2_I(odentry->d_inode);
struct gfs2_inode *nip = GFS2_I(ndentry->d_inode);
struct gfs2_sbd *sdp = GFS2_SB(odir);
struct gfs2_holder ghs[4], r_gh;
unsigned int num_gh;
unsigned int x;
umode_t old_mode = oip->i_inode.i_mode;
umode_t new_mode = nip->i_inode.i_mode;
int error;
gfs2_holder_mark_uninitialized(&r_gh);
error = gfs2_rindex_update(sdp);
if (error)
return error;
if (odip != ndip) {
error = gfs2_glock_nq_init(sdp->sd_rename_gl, LM_ST_EXCLUSIVE,
0, &r_gh);
if (error)
goto out;
if (S_ISDIR(old_mode)) {
/* don't move a directory into its subdir */
error = gfs2_ok_to_move(oip, ndip);
if (error)
goto out_gunlock_r;
}
if (S_ISDIR(new_mode)) {
/* don't move a directory into its subdir */
error = gfs2_ok_to_move(nip, odip);
if (error)
goto out_gunlock_r;
}
}
num_gh = 1;
gfs2_holder_init(odip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC, ghs);
if (odip != ndip) {
gfs2_holder_init(ndip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC,
ghs + num_gh);
num_gh++;
}
gfs2_holder_init(oip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC, ghs + num_gh);
num_gh++;
gfs2_holder_init(nip->i_gl, LM_ST_EXCLUSIVE, GL_ASYNC, ghs + num_gh);
num_gh++;
for (x = 0; x < num_gh; x++) {
error = gfs2_glock_nq(ghs + x);
if (error)
goto out_gunlock;
}
error = gfs2_glock_async_wait(num_gh, ghs);
if (error)
goto out_gunlock;
error = -ENOENT;
if (oip->i_inode.i_nlink == 0 || nip->i_inode.i_nlink == 0)
goto out_gunlock;
error = gfs2_unlink_ok(odip, &odentry->d_name, oip);
if (error)
goto out_gunlock;
error = gfs2_unlink_ok(ndip, &ndentry->d_name, nip);
if (error)
goto out_gunlock;
if (S_ISDIR(old_mode)) {
error = gfs2_permission(&nop_mnt_idmap, odentry->d_inode,
MAY_WRITE);
if (error)
goto out_gunlock;
}
if (S_ISDIR(new_mode)) {
error = gfs2_permission(&nop_mnt_idmap, ndentry->d_inode,
MAY_WRITE);
if (error)
goto out_gunlock;
}
error = gfs2_trans_begin(sdp, 4 * RES_DINODE + 4 * RES_LEAF, 0);
if (error)
goto out_gunlock;
error = update_moved_ino(oip, ndip, S_ISDIR(old_mode));
if (error)
goto out_end_trans;
error = update_moved_ino(nip, odip, S_ISDIR(new_mode));
if (error)
goto out_end_trans;
error = gfs2_dir_mvino(ndip, &ndentry->d_name, oip,
IF2DT(old_mode));
if (error)
goto out_end_trans;
error = gfs2_dir_mvino(odip, &odentry->d_name, nip,
IF2DT(new_mode));
if (error)
goto out_end_trans;
if (odip != ndip) {
if (S_ISDIR(new_mode) && !S_ISDIR(old_mode)) {
inc_nlink(&odip->i_inode);
drop_nlink(&ndip->i_inode);
} else if (S_ISDIR(old_mode) && !S_ISDIR(new_mode)) {
inc_nlink(&ndip->i_inode);
drop_nlink(&odip->i_inode);
}
}
mark_inode_dirty(&ndip->i_inode);
if (odip != ndip)
mark_inode_dirty(&odip->i_inode);
out_end_trans:
gfs2_trans_end(sdp);
out_gunlock:
while (x--) {
if (gfs2_holder_queued(ghs + x))
gfs2_glock_dq(ghs + x);
gfs2_holder_uninit(ghs + x);
}
out_gunlock_r:
if (gfs2_holder_initialized(&r_gh))
gfs2_glock_dq_uninit(&r_gh);
out:
return error;
}
static int gfs2_rename2(struct mnt_idmap *idmap, struct inode *odir,
struct dentry *odentry, struct inode *ndir,
struct dentry *ndentry, unsigned int flags)
{
flags &= ~RENAME_NOREPLACE;
if (flags & ~RENAME_EXCHANGE)
return -EINVAL;
if (flags & RENAME_EXCHANGE)
return gfs2_exchange(odir, odentry, ndir, ndentry, flags);
return gfs2_rename(odir, odentry, ndir, ndentry);
}
/**
* gfs2_get_link - Follow a symbolic link
* @dentry: The dentry of the link
* @inode: The inode of the link
* @done: destructor for return value
*
* This can handle symlinks of any size.
*
* Returns: 0 on success or error code
*/
static const char *gfs2_get_link(struct dentry *dentry,
struct inode *inode,
struct delayed_call *done)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
struct buffer_head *dibh;
unsigned int size;
char *buf;
int error;
if (!dentry)
return ERR_PTR(-ECHILD);
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &i_gh);
error = gfs2_glock_nq(&i_gh);
if (error) {
gfs2_holder_uninit(&i_gh);
return ERR_PTR(error);
}
size = (unsigned int)i_size_read(&ip->i_inode);
if (size == 0) {
gfs2_consist_inode(ip);
buf = ERR_PTR(-EIO);
goto out;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error) {
buf = ERR_PTR(error);
goto out;
}
buf = kzalloc(size + 1, GFP_NOFS);
if (!buf)
buf = ERR_PTR(-ENOMEM);
else
memcpy(buf, dibh->b_data + sizeof(struct gfs2_dinode), size);
brelse(dibh);
out:
gfs2_glock_dq_uninit(&i_gh);
if (!IS_ERR(buf))
set_delayed_call(done, kfree_link, buf);
return buf;
}
/**
* gfs2_permission
* @idmap: idmap of the mount the inode was found from
* @inode: The inode
* @mask: The mask to be tested
*
* This may be called from the VFS directly, or from within GFS2 with the
* inode locked, so we look to see if the glock is already locked and only
* lock the glock if its not already been done.
*
* Returns: errno
*/
int gfs2_permission(struct mnt_idmap *idmap, struct inode *inode,
int mask)
{
struct gfs2_inode *ip;
struct gfs2_holder i_gh;
int error;
gfs2_holder_mark_uninitialized(&i_gh);
ip = GFS2_I(inode);
if (gfs2_glock_is_locked_by_me(ip->i_gl) == NULL) {
if (mask & MAY_NOT_BLOCK)
return -ECHILD;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh);
if (error)
return error;
}
if ((mask & MAY_WRITE) && IS_IMMUTABLE(inode))
error = -EPERM;
else
error = generic_permission(&nop_mnt_idmap, inode, mask);
if (gfs2_holder_initialized(&i_gh))
gfs2_glock_dq_uninit(&i_gh);
return error;
}
static int __gfs2_setattr_simple(struct inode *inode, struct iattr *attr)
{
setattr_copy(&nop_mnt_idmap, inode, attr);
mark_inode_dirty(inode);
return 0;
}
static int gfs2_setattr_simple(struct inode *inode, struct iattr *attr)
{
int error;
if (current->journal_info)
return __gfs2_setattr_simple(inode, attr);
error = gfs2_trans_begin(GFS2_SB(inode), RES_DINODE, 0);
if (error)
return error;
error = __gfs2_setattr_simple(inode, attr);
gfs2_trans_end(GFS2_SB(inode));
return error;
}
static int setattr_chown(struct inode *inode, struct iattr *attr)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
kuid_t ouid, nuid;
kgid_t ogid, ngid;
int error;
struct gfs2_alloc_parms ap;
ouid = inode->i_uid;
ogid = inode->i_gid;
nuid = attr->ia_uid;
ngid = attr->ia_gid;
if (!(attr->ia_valid & ATTR_UID) || uid_eq(ouid, nuid))
ouid = nuid = NO_UID_QUOTA_CHANGE;
if (!(attr->ia_valid & ATTR_GID) || gid_eq(ogid, ngid))
ogid = ngid = NO_GID_QUOTA_CHANGE;
error = gfs2_qa_get(ip);
if (error)
return error;
error = gfs2_rindex_update(sdp);
if (error)
goto out;
error = gfs2_quota_lock(ip, nuid, ngid);
if (error)
goto out;
ap.target = gfs2_get_inode_blocks(&ip->i_inode);
if (!uid_eq(ouid, NO_UID_QUOTA_CHANGE) ||
!gid_eq(ogid, NO_GID_QUOTA_CHANGE)) {
error = gfs2_quota_check(ip, nuid, ngid, &ap);
if (error)
goto out_gunlock_q;
}
error = gfs2_trans_begin(sdp, RES_DINODE + 2 * RES_QUOTA, 0);
if (error)
goto out_gunlock_q;
error = gfs2_setattr_simple(inode, attr);
if (error)
goto out_end_trans;
if (!uid_eq(ouid, NO_UID_QUOTA_CHANGE) ||
!gid_eq(ogid, NO_GID_QUOTA_CHANGE)) {
gfs2_quota_change(ip, -(s64)ap.target, ouid, ogid);
gfs2_quota_change(ip, ap.target, nuid, ngid);
}
out_end_trans:
gfs2_trans_end(sdp);
out_gunlock_q:
gfs2_quota_unlock(ip);
out:
gfs2_qa_put(ip);
return error;
}
/**
* gfs2_setattr - Change attributes on an inode
* @idmap: idmap of the mount the inode was found from
* @dentry: The dentry which is changing
* @attr: The structure describing the change
*
* The VFS layer wants to change one or more of an inodes attributes. Write
* that change out to disk.
*
* Returns: errno
*/
static int gfs2_setattr(struct mnt_idmap *idmap,
struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = d_inode(dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
int error;
error = gfs2_qa_get(ip);
if (error)
return error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh);
if (error)
goto out;
error = may_setattr(&nop_mnt_idmap, inode, attr->ia_valid);
if (error)
goto error;
error = setattr_prepare(&nop_mnt_idmap, dentry, attr);
if (error)
goto error;
if (attr->ia_valid & ATTR_SIZE)
error = gfs2_setattr_size(inode, attr->ia_size);
else if (attr->ia_valid & (ATTR_UID | ATTR_GID))
error = setattr_chown(inode, attr);
else {
error = gfs2_setattr_simple(inode, attr);
if (!error && attr->ia_valid & ATTR_MODE)
error = posix_acl_chmod(&nop_mnt_idmap, dentry,
inode->i_mode);
}
error:
if (!error)
mark_inode_dirty(inode);
gfs2_glock_dq_uninit(&i_gh);
out:
gfs2_qa_put(ip);
return error;
}
/**
* gfs2_getattr - Read out an inode's attributes
* @idmap: idmap of the mount the inode was found from
* @path: Object to query
* @stat: The inode's stats
* @request_mask: Mask of STATX_xxx flags indicating the caller's interests
* @flags: AT_STATX_xxx setting
*
* This may be called from the VFS directly, or from within GFS2 with the
* inode locked, so we look to see if the glock is already locked and only
* lock the glock if its not already been done. Note that its the NFS
* readdirplus operation which causes this to be called (from filldir)
* with the glock already held.
*
* Returns: errno
*/
static int gfs2_getattr(struct mnt_idmap *idmap,
const struct path *path, struct kstat *stat,
u32 request_mask, unsigned int flags)
{
struct inode *inode = d_inode(path->dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
u32 gfsflags;
int error;
gfs2_holder_mark_uninitialized(&gh);
if (gfs2_glock_is_locked_by_me(ip->i_gl) == NULL) {
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &gh);
if (error)
return error;
}
gfsflags = ip->i_diskflags;
if (gfsflags & GFS2_DIF_APPENDONLY)
stat->attributes |= STATX_ATTR_APPEND;
if (gfsflags & GFS2_DIF_IMMUTABLE)
stat->attributes |= STATX_ATTR_IMMUTABLE;
stat->attributes_mask |= (STATX_ATTR_APPEND |
STATX_ATTR_COMPRESSED |
STATX_ATTR_ENCRYPTED |
STATX_ATTR_IMMUTABLE |
STATX_ATTR_NODUMP);
generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
if (gfs2_holder_initialized(&gh))
gfs2_glock_dq_uninit(&gh);
return 0;
}
static int gfs2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int ret;
inode_lock_shared(inode);
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (ret)
goto out;
ret = iomap_fiemap(inode, fieinfo, start, len, &gfs2_iomap_ops);
gfs2_glock_dq_uninit(&gh);
out:
inode_unlock_shared(inode);
return ret;
}
loff_t gfs2_seek_data(struct file *file, loff_t offset)
{
struct inode *inode = file->f_mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
loff_t ret;
inode_lock_shared(inode);
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (!ret)
ret = iomap_seek_data(inode, offset, &gfs2_iomap_ops);
gfs2_glock_dq_uninit(&gh);
inode_unlock_shared(inode);
if (ret < 0)
return ret;
return vfs_setpos(file, ret, inode->i_sb->s_maxbytes);
}
loff_t gfs2_seek_hole(struct file *file, loff_t offset)
{
struct inode *inode = file->f_mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
loff_t ret;
inode_lock_shared(inode);
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (!ret)
ret = iomap_seek_hole(inode, offset, &gfs2_iomap_ops);
gfs2_glock_dq_uninit(&gh);
inode_unlock_shared(inode);
if (ret < 0)
return ret;
return vfs_setpos(file, ret, inode->i_sb->s_maxbytes);
}
static int gfs2_update_time(struct inode *inode, int flags)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_glock *gl = ip->i_gl;
struct gfs2_holder *gh;
int error;
gh = gfs2_glock_is_locked_by_me(gl);
if (gh && !gfs2_glock_is_held_excl(gl)) {
gfs2_glock_dq(gh);
gfs2_holder_reinit(LM_ST_EXCLUSIVE, 0, gh);
error = gfs2_glock_nq(gh);
if (error)
return error;
}
generic_update_time(inode, flags);
return 0;
}
static const struct inode_operations gfs2_file_iops = {
.permission = gfs2_permission,
.setattr = gfs2_setattr,
.getattr = gfs2_getattr,
.listxattr = gfs2_listxattr,
.fiemap = gfs2_fiemap,
.get_inode_acl = gfs2_get_acl,
.set_acl = gfs2_set_acl,
.update_time = gfs2_update_time,
.fileattr_get = gfs2_fileattr_get,
.fileattr_set = gfs2_fileattr_set,
};
static const struct inode_operations gfs2_dir_iops = {
.create = gfs2_create,
.lookup = gfs2_lookup,
.link = gfs2_link,
.unlink = gfs2_unlink,
.symlink = gfs2_symlink,
.mkdir = gfs2_mkdir,
.rmdir = gfs2_unlink,
.mknod = gfs2_mknod,
.rename = gfs2_rename2,
.permission = gfs2_permission,
.setattr = gfs2_setattr,
.getattr = gfs2_getattr,
.listxattr = gfs2_listxattr,
.fiemap = gfs2_fiemap,
.get_inode_acl = gfs2_get_acl,
.set_acl = gfs2_set_acl,
.update_time = gfs2_update_time,
.atomic_open = gfs2_atomic_open,
.fileattr_get = gfs2_fileattr_get,
.fileattr_set = gfs2_fileattr_set,
};
static const struct inode_operations gfs2_symlink_iops = {
.get_link = gfs2_get_link,
.permission = gfs2_permission,
.setattr = gfs2_setattr,
.getattr = gfs2_getattr,
.listxattr = gfs2_listxattr,
.fiemap = gfs2_fiemap,
};
| linux-master | fs/gfs2/inode.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/kallsyms.h>
#include <linux/gfs2_ondisk.h>
#include "gfs2.h"
#include "incore.h"
#include "glock.h"
#include "inode.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "trans.h"
#include "util.h"
#include "trace_gfs2.h"
static void gfs2_print_trans(struct gfs2_sbd *sdp, const struct gfs2_trans *tr)
{
fs_warn(sdp, "Transaction created at: %pSR\n", (void *)tr->tr_ip);
fs_warn(sdp, "blocks=%u revokes=%u reserved=%u touched=%u\n",
tr->tr_blocks, tr->tr_revokes, tr->tr_reserved,
test_bit(TR_TOUCHED, &tr->tr_flags));
fs_warn(sdp, "Buf %u/%u Databuf %u/%u Revoke %u\n",
tr->tr_num_buf_new, tr->tr_num_buf_rm,
tr->tr_num_databuf_new, tr->tr_num_databuf_rm,
tr->tr_num_revoke);
}
int __gfs2_trans_begin(struct gfs2_trans *tr, struct gfs2_sbd *sdp,
unsigned int blocks, unsigned int revokes,
unsigned long ip)
{
unsigned int extra_revokes;
if (current->journal_info) {
gfs2_print_trans(sdp, current->journal_info);
BUG();
}
BUG_ON(blocks == 0 && revokes == 0);
if (!test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))
return -EROFS;
tr->tr_ip = ip;
tr->tr_blocks = blocks;
tr->tr_revokes = revokes;
tr->tr_reserved = GFS2_LOG_FLUSH_MIN_BLOCKS;
if (blocks) {
/*
* The reserved blocks are either used for data or metadata.
* We can have mixed data and metadata, each with its own log
* descriptor block; see calc_reserved().
*/
tr->tr_reserved += blocks + 1 + DIV_ROUND_UP(blocks - 1, databuf_limit(sdp));
}
INIT_LIST_HEAD(&tr->tr_databuf);
INIT_LIST_HEAD(&tr->tr_buf);
INIT_LIST_HEAD(&tr->tr_list);
INIT_LIST_HEAD(&tr->tr_ail1_list);
INIT_LIST_HEAD(&tr->tr_ail2_list);
if (gfs2_assert_warn(sdp, tr->tr_reserved <= sdp->sd_jdesc->jd_blocks))
return -EINVAL;
sb_start_intwrite(sdp->sd_vfs);
/*
* Try the reservations under sd_log_flush_lock to prevent log flushes
* from creating inconsistencies between the number of allocated and
* reserved revokes. If that fails, do a full-block allocation outside
* of the lock to avoid stalling log flushes. Then, allot the
* appropriate number of blocks to revokes, use as many revokes locally
* as needed, and "release" the surplus into the revokes pool.
*/
down_read(&sdp->sd_log_flush_lock);
if (gfs2_log_try_reserve(sdp, tr, &extra_revokes))
goto reserved;
up_read(&sdp->sd_log_flush_lock);
gfs2_log_reserve(sdp, tr, &extra_revokes);
down_read(&sdp->sd_log_flush_lock);
reserved:
gfs2_log_release_revokes(sdp, extra_revokes);
if (unlikely(!test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))) {
gfs2_log_release_revokes(sdp, tr->tr_revokes);
up_read(&sdp->sd_log_flush_lock);
gfs2_log_release(sdp, tr->tr_reserved);
sb_end_intwrite(sdp->sd_vfs);
return -EROFS;
}
current->journal_info = tr;
return 0;
}
int gfs2_trans_begin(struct gfs2_sbd *sdp, unsigned int blocks,
unsigned int revokes)
{
struct gfs2_trans *tr;
int error;
tr = kmem_cache_zalloc(gfs2_trans_cachep, GFP_NOFS);
if (!tr)
return -ENOMEM;
error = __gfs2_trans_begin(tr, sdp, blocks, revokes, _RET_IP_);
if (error)
kmem_cache_free(gfs2_trans_cachep, tr);
return error;
}
void gfs2_trans_end(struct gfs2_sbd *sdp)
{
struct gfs2_trans *tr = current->journal_info;
s64 nbuf;
current->journal_info = NULL;
if (!test_bit(TR_TOUCHED, &tr->tr_flags)) {
gfs2_log_release_revokes(sdp, tr->tr_revokes);
up_read(&sdp->sd_log_flush_lock);
gfs2_log_release(sdp, tr->tr_reserved);
if (!test_bit(TR_ONSTACK, &tr->tr_flags))
gfs2_trans_free(sdp, tr);
sb_end_intwrite(sdp->sd_vfs);
return;
}
gfs2_log_release_revokes(sdp, tr->tr_revokes - tr->tr_num_revoke);
nbuf = tr->tr_num_buf_new + tr->tr_num_databuf_new;
nbuf -= tr->tr_num_buf_rm;
nbuf -= tr->tr_num_databuf_rm;
if (gfs2_assert_withdraw(sdp, nbuf <= tr->tr_blocks) ||
gfs2_assert_withdraw(sdp, tr->tr_num_revoke <= tr->tr_revokes))
gfs2_print_trans(sdp, tr);
gfs2_log_commit(sdp, tr);
if (!test_bit(TR_ONSTACK, &tr->tr_flags) &&
!test_bit(TR_ATTACHED, &tr->tr_flags))
gfs2_trans_free(sdp, tr);
up_read(&sdp->sd_log_flush_lock);
if (sdp->sd_vfs->s_flags & SB_SYNCHRONOUS)
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_TRANS_END);
sb_end_intwrite(sdp->sd_vfs);
}
static struct gfs2_bufdata *gfs2_alloc_bufdata(struct gfs2_glock *gl,
struct buffer_head *bh)
{
struct gfs2_bufdata *bd;
bd = kmem_cache_zalloc(gfs2_bufdata_cachep, GFP_NOFS | __GFP_NOFAIL);
bd->bd_bh = bh;
bd->bd_gl = gl;
INIT_LIST_HEAD(&bd->bd_list);
INIT_LIST_HEAD(&bd->bd_ail_st_list);
INIT_LIST_HEAD(&bd->bd_ail_gl_list);
bh->b_private = bd;
return bd;
}
/**
* gfs2_trans_add_data - Add a databuf to the transaction.
* @gl: The inode glock associated with the buffer
* @bh: The buffer to add
*
* This is used in journaled data mode.
* We need to journal the data block in the same way as metadata in
* the functions above. The difference is that here we have a tag
* which is two __be64's being the block number (as per meta data)
* and a flag which says whether the data block needs escaping or
* not. This means we need a new log entry for each 251 or so data
* blocks, which isn't an enormous overhead but twice as much as
* for normal metadata blocks.
*/
void gfs2_trans_add_data(struct gfs2_glock *gl, struct buffer_head *bh)
{
struct gfs2_trans *tr = current->journal_info;
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_bufdata *bd;
lock_buffer(bh);
if (buffer_pinned(bh)) {
set_bit(TR_TOUCHED, &tr->tr_flags);
goto out;
}
gfs2_log_lock(sdp);
bd = bh->b_private;
if (bd == NULL) {
gfs2_log_unlock(sdp);
unlock_buffer(bh);
if (bh->b_private == NULL)
bd = gfs2_alloc_bufdata(gl, bh);
else
bd = bh->b_private;
lock_buffer(bh);
gfs2_log_lock(sdp);
}
gfs2_assert(sdp, bd->bd_gl == gl);
set_bit(TR_TOUCHED, &tr->tr_flags);
if (list_empty(&bd->bd_list)) {
set_bit(GLF_LFLUSH, &bd->bd_gl->gl_flags);
set_bit(GLF_DIRTY, &bd->bd_gl->gl_flags);
gfs2_pin(sdp, bd->bd_bh);
tr->tr_num_databuf_new++;
list_add_tail(&bd->bd_list, &tr->tr_databuf);
}
gfs2_log_unlock(sdp);
out:
unlock_buffer(bh);
}
void gfs2_trans_add_meta(struct gfs2_glock *gl, struct buffer_head *bh)
{
struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct super_block *sb = sdp->sd_vfs;
struct gfs2_bufdata *bd;
struct gfs2_meta_header *mh;
struct gfs2_trans *tr = current->journal_info;
bool withdraw = false;
lock_buffer(bh);
if (buffer_pinned(bh)) {
set_bit(TR_TOUCHED, &tr->tr_flags);
goto out;
}
gfs2_log_lock(sdp);
bd = bh->b_private;
if (bd == NULL) {
gfs2_log_unlock(sdp);
unlock_buffer(bh);
lock_page(bh->b_page);
if (bh->b_private == NULL)
bd = gfs2_alloc_bufdata(gl, bh);
else
bd = bh->b_private;
unlock_page(bh->b_page);
lock_buffer(bh);
gfs2_log_lock(sdp);
}
gfs2_assert(sdp, bd->bd_gl == gl);
set_bit(TR_TOUCHED, &tr->tr_flags);
if (!list_empty(&bd->bd_list))
goto out_unlock;
set_bit(GLF_LFLUSH, &bd->bd_gl->gl_flags);
set_bit(GLF_DIRTY, &bd->bd_gl->gl_flags);
mh = (struct gfs2_meta_header *)bd->bd_bh->b_data;
if (unlikely(mh->mh_magic != cpu_to_be32(GFS2_MAGIC))) {
fs_err(sdp, "Attempting to add uninitialised block to "
"journal (inplace block=%lld)\n",
(unsigned long long)bd->bd_bh->b_blocknr);
BUG();
}
if (unlikely(gfs2_withdrawn(sdp))) {
fs_info(sdp, "GFS2:adding buf while withdrawn! 0x%llx\n",
(unsigned long long)bd->bd_bh->b_blocknr);
goto out_unlock;
}
if (unlikely(sb->s_writers.frozen == SB_FREEZE_COMPLETE)) {
fs_info(sdp, "GFS2:adding buf while frozen\n");
withdraw = true;
goto out_unlock;
}
gfs2_pin(sdp, bd->bd_bh);
mh->__pad0 = cpu_to_be64(0);
mh->mh_jid = cpu_to_be32(sdp->sd_jdesc->jd_jid);
list_add(&bd->bd_list, &tr->tr_buf);
tr->tr_num_buf_new++;
out_unlock:
gfs2_log_unlock(sdp);
if (withdraw)
gfs2_assert_withdraw(sdp, 0);
out:
unlock_buffer(bh);
}
void gfs2_trans_add_revoke(struct gfs2_sbd *sdp, struct gfs2_bufdata *bd)
{
struct gfs2_trans *tr = current->journal_info;
BUG_ON(!list_empty(&bd->bd_list));
gfs2_add_revoke(sdp, bd);
set_bit(TR_TOUCHED, &tr->tr_flags);
tr->tr_num_revoke++;
}
void gfs2_trans_remove_revoke(struct gfs2_sbd *sdp, u64 blkno, unsigned int len)
{
struct gfs2_bufdata *bd, *tmp;
unsigned int n = len;
gfs2_log_lock(sdp);
list_for_each_entry_safe(bd, tmp, &sdp->sd_log_revokes, bd_list) {
if ((bd->bd_blkno >= blkno) && (bd->bd_blkno < (blkno + len))) {
list_del_init(&bd->bd_list);
gfs2_assert_withdraw(sdp, sdp->sd_log_num_revoke);
sdp->sd_log_num_revoke--;
if (bd->bd_gl)
gfs2_glock_remove_revoke(bd->bd_gl);
kmem_cache_free(gfs2_bufdata_cachep, bd);
gfs2_log_release_revokes(sdp, 1);
if (--n == 0)
break;
}
}
gfs2_log_unlock(sdp);
}
void gfs2_trans_free(struct gfs2_sbd *sdp, struct gfs2_trans *tr)
{
if (tr == NULL)
return;
gfs2_assert_warn(sdp, list_empty(&tr->tr_ail1_list));
gfs2_assert_warn(sdp, list_empty(&tr->tr_ail2_list));
gfs2_assert_warn(sdp, list_empty(&tr->tr_databuf));
gfs2_assert_warn(sdp, list_empty(&tr->tr_buf));
kmem_cache_free(gfs2_trans_cachep, tr);
}
| linux-master | fs/gfs2/trans.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
*/
/*
* Quota change tags are associated with each transaction that allocates or
* deallocates space. Those changes are accumulated locally to each node (in a
* per-node file) and then are periodically synced to the quota file. This
* avoids the bottleneck of constantly touching the quota file, but introduces
* fuzziness in the current usage value of IDs that are being used on different
* nodes in the cluster simultaneously. So, it is possible for a user on
* multiple nodes to overrun their quota, but that overrun is controlable.
* Since quota tags are part of transactions, there is no need for a quota check
* program to be run on node crashes or anything like that.
*
* There are couple of knobs that let the administrator manage the quota
* fuzziness. "quota_quantum" sets the maximum time a quota change can be
* sitting on one node before being synced to the quota file. (The default is
* 60 seconds.) Another knob, "quota_scale" controls how quickly the frequency
* of quota file syncs increases as the user moves closer to their limit. The
* more frequent the syncs, the more accurate the quota enforcement, but that
* means that there is more contention between the nodes for the quota file.
* The default value is one. This sets the maximum theoretical quota overrun
* (with infinite node with infinite bandwidth) to twice the user's limit. (In
* practice, the maximum overrun you see should be much less.) A "quota_scale"
* number greater than one makes quota syncs more frequent and reduces the
* maximum overrun. Numbers less than one (but greater than zero) make quota
* syncs less frequent.
*
* GFS quotas also use per-ID Lock Value Blocks (LVBs) to cache the contents of
* the quota file, so it is not being constantly read.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/sort.h>
#include <linux/fs.h>
#include <linux/bio.h>
#include <linux/gfs2_ondisk.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/quota.h>
#include <linux/dqblk_xfs.h>
#include <linux/lockref.h>
#include <linux/list_lru.h>
#include <linux/rcupdate.h>
#include <linux/rculist_bl.h>
#include <linux/bit_spinlock.h>
#include <linux/jhash.h>
#include <linux/vmalloc.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "glops.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "inode.h"
#include "util.h"
#define GFS2_QD_HASH_SHIFT 12
#define GFS2_QD_HASH_SIZE BIT(GFS2_QD_HASH_SHIFT)
#define GFS2_QD_HASH_MASK (GFS2_QD_HASH_SIZE - 1)
#define QC_CHANGE 0
#define QC_SYNC 1
/* Lock order: qd_lock -> bucket lock -> qd->lockref.lock -> lru lock */
/* -> sd_bitmap_lock */
static DEFINE_SPINLOCK(qd_lock);
struct list_lru gfs2_qd_lru;
static struct hlist_bl_head qd_hash_table[GFS2_QD_HASH_SIZE];
static unsigned int gfs2_qd_hash(const struct gfs2_sbd *sdp,
const struct kqid qid)
{
unsigned int h;
h = jhash(&sdp, sizeof(struct gfs2_sbd *), 0);
h = jhash(&qid, sizeof(struct kqid), h);
return h & GFS2_QD_HASH_MASK;
}
static inline void spin_lock_bucket(unsigned int hash)
{
hlist_bl_lock(&qd_hash_table[hash]);
}
static inline void spin_unlock_bucket(unsigned int hash)
{
hlist_bl_unlock(&qd_hash_table[hash]);
}
static void gfs2_qd_dealloc(struct rcu_head *rcu)
{
struct gfs2_quota_data *qd = container_of(rcu, struct gfs2_quota_data, qd_rcu);
struct gfs2_sbd *sdp = qd->qd_sbd;
kmem_cache_free(gfs2_quotad_cachep, qd);
if (atomic_dec_and_test(&sdp->sd_quota_count))
wake_up(&sdp->sd_kill_wait);
}
static void gfs2_qd_dispose(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
spin_lock(&qd_lock);
list_del(&qd->qd_list);
spin_unlock(&qd_lock);
spin_lock_bucket(qd->qd_hash);
hlist_bl_del_rcu(&qd->qd_hlist);
spin_unlock_bucket(qd->qd_hash);
if (!gfs2_withdrawn(sdp)) {
gfs2_assert_warn(sdp, !qd->qd_change);
gfs2_assert_warn(sdp, !qd->qd_slot_ref);
gfs2_assert_warn(sdp, !qd->qd_bh_count);
}
gfs2_glock_put(qd->qd_gl);
call_rcu(&qd->qd_rcu, gfs2_qd_dealloc);
}
static void gfs2_qd_list_dispose(struct list_head *list)
{
struct gfs2_quota_data *qd;
while (!list_empty(list)) {
qd = list_first_entry(list, struct gfs2_quota_data, qd_lru);
list_del(&qd->qd_lru);
gfs2_qd_dispose(qd);
}
}
static enum lru_status gfs2_qd_isolate(struct list_head *item,
struct list_lru_one *lru, spinlock_t *lru_lock, void *arg)
{
struct list_head *dispose = arg;
struct gfs2_quota_data *qd =
list_entry(item, struct gfs2_quota_data, qd_lru);
enum lru_status status;
if (!spin_trylock(&qd->qd_lockref.lock))
return LRU_SKIP;
status = LRU_SKIP;
if (qd->qd_lockref.count == 0) {
lockref_mark_dead(&qd->qd_lockref);
list_lru_isolate_move(lru, &qd->qd_lru, dispose);
status = LRU_REMOVED;
}
spin_unlock(&qd->qd_lockref.lock);
return status;
}
static unsigned long gfs2_qd_shrink_scan(struct shrinker *shrink,
struct shrink_control *sc)
{
LIST_HEAD(dispose);
unsigned long freed;
if (!(sc->gfp_mask & __GFP_FS))
return SHRINK_STOP;
freed = list_lru_shrink_walk(&gfs2_qd_lru, sc,
gfs2_qd_isolate, &dispose);
gfs2_qd_list_dispose(&dispose);
return freed;
}
static unsigned long gfs2_qd_shrink_count(struct shrinker *shrink,
struct shrink_control *sc)
{
return vfs_pressure_ratio(list_lru_shrink_count(&gfs2_qd_lru, sc));
}
struct shrinker gfs2_qd_shrinker = {
.count_objects = gfs2_qd_shrink_count,
.scan_objects = gfs2_qd_shrink_scan,
.seeks = DEFAULT_SEEKS,
.flags = SHRINKER_NUMA_AWARE,
};
static u64 qd2index(struct gfs2_quota_data *qd)
{
struct kqid qid = qd->qd_id;
return (2 * (u64)from_kqid(&init_user_ns, qid)) +
((qid.type == USRQUOTA) ? 0 : 1);
}
static u64 qd2offset(struct gfs2_quota_data *qd)
{
return qd2index(qd) * sizeof(struct gfs2_quota);
}
static struct gfs2_quota_data *qd_alloc(unsigned hash, struct gfs2_sbd *sdp, struct kqid qid)
{
struct gfs2_quota_data *qd;
int error;
qd = kmem_cache_zalloc(gfs2_quotad_cachep, GFP_NOFS);
if (!qd)
return NULL;
qd->qd_sbd = sdp;
qd->qd_lockref.count = 0;
spin_lock_init(&qd->qd_lockref.lock);
qd->qd_id = qid;
qd->qd_slot = -1;
INIT_LIST_HEAD(&qd->qd_lru);
qd->qd_hash = hash;
error = gfs2_glock_get(sdp, qd2index(qd),
&gfs2_quota_glops, CREATE, &qd->qd_gl);
if (error)
goto fail;
return qd;
fail:
kmem_cache_free(gfs2_quotad_cachep, qd);
return NULL;
}
static struct gfs2_quota_data *gfs2_qd_search_bucket(unsigned int hash,
const struct gfs2_sbd *sdp,
struct kqid qid)
{
struct gfs2_quota_data *qd;
struct hlist_bl_node *h;
hlist_bl_for_each_entry_rcu(qd, h, &qd_hash_table[hash], qd_hlist) {
if (!qid_eq(qd->qd_id, qid))
continue;
if (qd->qd_sbd != sdp)
continue;
if (lockref_get_not_dead(&qd->qd_lockref)) {
list_lru_del(&gfs2_qd_lru, &qd->qd_lru);
return qd;
}
}
return NULL;
}
static int qd_get(struct gfs2_sbd *sdp, struct kqid qid,
struct gfs2_quota_data **qdp)
{
struct gfs2_quota_data *qd, *new_qd;
unsigned int hash = gfs2_qd_hash(sdp, qid);
rcu_read_lock();
*qdp = qd = gfs2_qd_search_bucket(hash, sdp, qid);
rcu_read_unlock();
if (qd)
return 0;
new_qd = qd_alloc(hash, sdp, qid);
if (!new_qd)
return -ENOMEM;
spin_lock(&qd_lock);
spin_lock_bucket(hash);
*qdp = qd = gfs2_qd_search_bucket(hash, sdp, qid);
if (qd == NULL) {
new_qd->qd_lockref.count++;
*qdp = new_qd;
list_add(&new_qd->qd_list, &sdp->sd_quota_list);
hlist_bl_add_head_rcu(&new_qd->qd_hlist, &qd_hash_table[hash]);
atomic_inc(&sdp->sd_quota_count);
}
spin_unlock_bucket(hash);
spin_unlock(&qd_lock);
if (qd) {
gfs2_glock_put(new_qd->qd_gl);
kmem_cache_free(gfs2_quotad_cachep, new_qd);
}
return 0;
}
static void qd_hold(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
gfs2_assert(sdp, !__lockref_is_dead(&qd->qd_lockref));
lockref_get(&qd->qd_lockref);
}
static void qd_put(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp;
if (lockref_put_or_lock(&qd->qd_lockref))
return;
BUG_ON(__lockref_is_dead(&qd->qd_lockref));
sdp = qd->qd_sbd;
if (unlikely(!test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))) {
lockref_mark_dead(&qd->qd_lockref);
spin_unlock(&qd->qd_lockref.lock);
gfs2_qd_dispose(qd);
return;
}
qd->qd_lockref.count = 0;
list_lru_add(&gfs2_qd_lru, &qd->qd_lru);
spin_unlock(&qd->qd_lockref.lock);
}
static int slot_get(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
unsigned int bit;
int error = 0;
spin_lock(&sdp->sd_bitmap_lock);
if (qd->qd_slot_ref == 0) {
bit = find_first_zero_bit(sdp->sd_quota_bitmap,
sdp->sd_quota_slots);
if (bit >= sdp->sd_quota_slots) {
error = -ENOSPC;
goto out;
}
set_bit(bit, sdp->sd_quota_bitmap);
qd->qd_slot = bit;
}
qd->qd_slot_ref++;
out:
spin_unlock(&sdp->sd_bitmap_lock);
return error;
}
static void slot_hold(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
spin_lock(&sdp->sd_bitmap_lock);
gfs2_assert(sdp, qd->qd_slot_ref);
qd->qd_slot_ref++;
spin_unlock(&sdp->sd_bitmap_lock);
}
static void slot_put(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
spin_lock(&sdp->sd_bitmap_lock);
gfs2_assert(sdp, qd->qd_slot_ref);
if (!--qd->qd_slot_ref) {
BUG_ON(!test_and_clear_bit(qd->qd_slot, sdp->sd_quota_bitmap));
qd->qd_slot = -1;
}
spin_unlock(&sdp->sd_bitmap_lock);
}
static int bh_get(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
struct inode *inode = sdp->sd_qc_inode;
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int block, offset;
struct buffer_head *bh;
struct iomap iomap = { };
int error;
mutex_lock(&sdp->sd_quota_mutex);
if (qd->qd_bh_count++) {
mutex_unlock(&sdp->sd_quota_mutex);
return 0;
}
block = qd->qd_slot / sdp->sd_qc_per_block;
offset = qd->qd_slot % sdp->sd_qc_per_block;
error = gfs2_iomap_get(inode,
(loff_t)block << inode->i_blkbits,
i_blocksize(inode), &iomap);
if (error)
goto fail;
error = -ENOENT;
if (iomap.type != IOMAP_MAPPED)
goto fail;
error = gfs2_meta_read(ip->i_gl, iomap.addr >> inode->i_blkbits,
DIO_WAIT, 0, &bh);
if (error)
goto fail;
error = -EIO;
if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC))
goto fail_brelse;
qd->qd_bh = bh;
qd->qd_bh_qc = (struct gfs2_quota_change *)
(bh->b_data + sizeof(struct gfs2_meta_header) +
offset * sizeof(struct gfs2_quota_change));
mutex_unlock(&sdp->sd_quota_mutex);
return 0;
fail_brelse:
brelse(bh);
fail:
qd->qd_bh_count--;
mutex_unlock(&sdp->sd_quota_mutex);
return error;
}
static void bh_put(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
mutex_lock(&sdp->sd_quota_mutex);
gfs2_assert(sdp, qd->qd_bh_count);
if (!--qd->qd_bh_count) {
brelse(qd->qd_bh);
qd->qd_bh = NULL;
qd->qd_bh_qc = NULL;
}
mutex_unlock(&sdp->sd_quota_mutex);
}
static int qd_check_sync(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd,
u64 *sync_gen)
{
if (test_bit(QDF_LOCKED, &qd->qd_flags) ||
!test_bit(QDF_CHANGE, &qd->qd_flags) ||
(sync_gen && (qd->qd_sync_gen >= *sync_gen)))
return 0;
if (!lockref_get_not_dead(&qd->qd_lockref))
return 0;
list_move_tail(&qd->qd_list, &sdp->sd_quota_list);
set_bit(QDF_LOCKED, &qd->qd_flags);
qd->qd_change_sync = qd->qd_change;
slot_hold(qd);
return 1;
}
static int qd_bh_get_or_undo(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd)
{
int error;
error = bh_get(qd);
if (!error)
return 0;
clear_bit(QDF_LOCKED, &qd->qd_flags);
slot_put(qd);
qd_put(qd);
return error;
}
static int qd_fish(struct gfs2_sbd *sdp, struct gfs2_quota_data **qdp)
{
struct gfs2_quota_data *qd = NULL, *iter;
int error;
*qdp = NULL;
if (sb_rdonly(sdp->sd_vfs))
return 0;
spin_lock(&qd_lock);
list_for_each_entry(iter, &sdp->sd_quota_list, qd_list) {
if (qd_check_sync(sdp, iter, &sdp->sd_quota_sync_gen)) {
qd = iter;
break;
}
}
spin_unlock(&qd_lock);
if (qd) {
error = qd_bh_get_or_undo(sdp, qd);
if (error)
return error;
*qdp = qd;
}
return 0;
}
static void qdsb_put(struct gfs2_quota_data *qd)
{
bh_put(qd);
slot_put(qd);
qd_put(qd);
}
static void qd_unlock(struct gfs2_quota_data *qd)
{
gfs2_assert_warn(qd->qd_sbd, test_bit(QDF_LOCKED, &qd->qd_flags));
clear_bit(QDF_LOCKED, &qd->qd_flags);
qdsb_put(qd);
}
static int qdsb_get(struct gfs2_sbd *sdp, struct kqid qid,
struct gfs2_quota_data **qdp)
{
int error;
error = qd_get(sdp, qid, qdp);
if (error)
return error;
error = slot_get(*qdp);
if (error)
goto fail;
error = bh_get(*qdp);
if (error)
goto fail_slot;
return 0;
fail_slot:
slot_put(*qdp);
fail:
qd_put(*qdp);
return error;
}
/**
* gfs2_qa_get - make sure we have a quota allocations data structure,
* if necessary
* @ip: the inode for this reservation
*/
int gfs2_qa_get(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct inode *inode = &ip->i_inode;
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return 0;
spin_lock(&inode->i_lock);
if (ip->i_qadata == NULL) {
struct gfs2_qadata *tmp;
spin_unlock(&inode->i_lock);
tmp = kmem_cache_zalloc(gfs2_qadata_cachep, GFP_NOFS);
if (!tmp)
return -ENOMEM;
spin_lock(&inode->i_lock);
if (ip->i_qadata == NULL)
ip->i_qadata = tmp;
else
kmem_cache_free(gfs2_qadata_cachep, tmp);
}
ip->i_qadata->qa_ref++;
spin_unlock(&inode->i_lock);
return 0;
}
void gfs2_qa_put(struct gfs2_inode *ip)
{
struct inode *inode = &ip->i_inode;
spin_lock(&inode->i_lock);
if (ip->i_qadata && --ip->i_qadata->qa_ref == 0) {
kmem_cache_free(gfs2_qadata_cachep, ip->i_qadata);
ip->i_qadata = NULL;
}
spin_unlock(&inode->i_lock);
}
int gfs2_quota_hold(struct gfs2_inode *ip, kuid_t uid, kgid_t gid)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_quota_data **qd;
int error;
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return 0;
error = gfs2_qa_get(ip);
if (error)
return error;
qd = ip->i_qadata->qa_qd;
if (gfs2_assert_warn(sdp, !ip->i_qadata->qa_qd_num) ||
gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags))) {
error = -EIO;
gfs2_qa_put(ip);
goto out;
}
error = qdsb_get(sdp, make_kqid_uid(ip->i_inode.i_uid), qd);
if (error)
goto out_unhold;
ip->i_qadata->qa_qd_num++;
qd++;
error = qdsb_get(sdp, make_kqid_gid(ip->i_inode.i_gid), qd);
if (error)
goto out_unhold;
ip->i_qadata->qa_qd_num++;
qd++;
if (!uid_eq(uid, NO_UID_QUOTA_CHANGE) &&
!uid_eq(uid, ip->i_inode.i_uid)) {
error = qdsb_get(sdp, make_kqid_uid(uid), qd);
if (error)
goto out_unhold;
ip->i_qadata->qa_qd_num++;
qd++;
}
if (!gid_eq(gid, NO_GID_QUOTA_CHANGE) &&
!gid_eq(gid, ip->i_inode.i_gid)) {
error = qdsb_get(sdp, make_kqid_gid(gid), qd);
if (error)
goto out_unhold;
ip->i_qadata->qa_qd_num++;
qd++;
}
out_unhold:
if (error)
gfs2_quota_unhold(ip);
out:
return error;
}
void gfs2_quota_unhold(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
u32 x;
if (ip->i_qadata == NULL)
return;
gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags));
for (x = 0; x < ip->i_qadata->qa_qd_num; x++) {
qdsb_put(ip->i_qadata->qa_qd[x]);
ip->i_qadata->qa_qd[x] = NULL;
}
ip->i_qadata->qa_qd_num = 0;
gfs2_qa_put(ip);
}
static int sort_qd(const void *a, const void *b)
{
const struct gfs2_quota_data *qd_a = *(const struct gfs2_quota_data **)a;
const struct gfs2_quota_data *qd_b = *(const struct gfs2_quota_data **)b;
if (qid_lt(qd_a->qd_id, qd_b->qd_id))
return -1;
if (qid_lt(qd_b->qd_id, qd_a->qd_id))
return 1;
return 0;
}
static void do_qc(struct gfs2_quota_data *qd, s64 change, int qc_type)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode);
struct gfs2_quota_change *qc = qd->qd_bh_qc;
s64 x;
mutex_lock(&sdp->sd_quota_mutex);
gfs2_trans_add_meta(ip->i_gl, qd->qd_bh);
if (!test_bit(QDF_CHANGE, &qd->qd_flags)) {
qc->qc_change = 0;
qc->qc_flags = 0;
if (qd->qd_id.type == USRQUOTA)
qc->qc_flags = cpu_to_be32(GFS2_QCF_USER);
qc->qc_id = cpu_to_be32(from_kqid(&init_user_ns, qd->qd_id));
}
x = be64_to_cpu(qc->qc_change) + change;
qc->qc_change = cpu_to_be64(x);
spin_lock(&qd_lock);
qd->qd_change = x;
spin_unlock(&qd_lock);
if (qc_type == QC_CHANGE) {
if (!test_and_set_bit(QDF_CHANGE, &qd->qd_flags)) {
qd_hold(qd);
slot_hold(qd);
}
} else {
gfs2_assert_warn(sdp, test_bit(QDF_CHANGE, &qd->qd_flags));
clear_bit(QDF_CHANGE, &qd->qd_flags);
qc->qc_flags = 0;
qc->qc_id = 0;
slot_put(qd);
qd_put(qd);
}
if (change < 0) /* Reset quiet flag if we freed some blocks */
clear_bit(QDF_QMSG_QUIET, &qd->qd_flags);
mutex_unlock(&sdp->sd_quota_mutex);
}
static int gfs2_write_buf_to_page(struct gfs2_sbd *sdp, unsigned long index,
unsigned off, void *buf, unsigned bytes)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct inode *inode = &ip->i_inode;
struct address_space *mapping = inode->i_mapping;
struct page *page;
struct buffer_head *bh;
u64 blk;
unsigned bsize = sdp->sd_sb.sb_bsize, bnum = 0, boff = 0;
unsigned to_write = bytes, pg_off = off;
blk = index << (PAGE_SHIFT - sdp->sd_sb.sb_bsize_shift);
boff = off % bsize;
page = grab_cache_page(mapping, index);
if (!page)
return -ENOMEM;
if (!page_has_buffers(page))
create_empty_buffers(page, bsize, 0);
bh = page_buffers(page);
for(;;) {
/* Find the beginning block within the page */
if (pg_off >= ((bnum * bsize) + bsize)) {
bh = bh->b_this_page;
bnum++;
blk++;
continue;
}
if (!buffer_mapped(bh)) {
gfs2_block_map(inode, blk, bh, 1);
if (!buffer_mapped(bh))
goto unlock_out;
/* If it's a newly allocated disk block, zero it */
if (buffer_new(bh))
zero_user(page, bnum * bsize, bh->b_size);
}
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (bh_read(bh, REQ_META | REQ_PRIO) < 0)
goto unlock_out;
gfs2_trans_add_data(ip->i_gl, bh);
/* If we need to write to the next block as well */
if (to_write > (bsize - boff)) {
pg_off += (bsize - boff);
to_write -= (bsize - boff);
boff = pg_off % bsize;
continue;
}
break;
}
/* Write to the page, now that we have setup the buffer(s) */
memcpy_to_page(page, off, buf, bytes);
flush_dcache_page(page);
unlock_page(page);
put_page(page);
return 0;
unlock_out:
unlock_page(page);
put_page(page);
return -EIO;
}
static int gfs2_write_disk_quota(struct gfs2_sbd *sdp, struct gfs2_quota *qp,
loff_t loc)
{
unsigned long pg_beg;
unsigned pg_off, nbytes, overflow = 0;
int error;
void *ptr;
nbytes = sizeof(struct gfs2_quota);
pg_beg = loc >> PAGE_SHIFT;
pg_off = offset_in_page(loc);
/* If the quota straddles a page boundary, split the write in two */
if ((pg_off + nbytes) > PAGE_SIZE)
overflow = (pg_off + nbytes) - PAGE_SIZE;
ptr = qp;
error = gfs2_write_buf_to_page(sdp, pg_beg, pg_off, ptr,
nbytes - overflow);
/* If there's an overflow, write the remaining bytes to the next page */
if (!error && overflow)
error = gfs2_write_buf_to_page(sdp, pg_beg + 1, 0,
ptr + nbytes - overflow,
overflow);
return error;
}
/**
* gfs2_adjust_quota - adjust record of current block usage
* @sdp: The superblock
* @loc: Offset of the entry in the quota file
* @change: The amount of usage change to record
* @qd: The quota data
* @fdq: The updated limits to record
*
* This function was mostly borrowed from gfs2_block_truncate_page which was
* in turn mostly borrowed from ext3
*
* Returns: 0 or -ve on error
*/
static int gfs2_adjust_quota(struct gfs2_sbd *sdp, loff_t loc,
s64 change, struct gfs2_quota_data *qd,
struct qc_dqblk *fdq)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct inode *inode = &ip->i_inode;
struct gfs2_quota q;
int err;
u64 size;
if (gfs2_is_stuffed(ip)) {
err = gfs2_unstuff_dinode(ip);
if (err)
return err;
}
memset(&q, 0, sizeof(struct gfs2_quota));
err = gfs2_internal_read(ip, (char *)&q, &loc, sizeof(q));
if (err < 0)
return err;
loc -= sizeof(q); /* gfs2_internal_read would've advanced the loc ptr */
be64_add_cpu(&q.qu_value, change);
if (((s64)be64_to_cpu(q.qu_value)) < 0)
q.qu_value = 0; /* Never go negative on quota usage */
qd->qd_qb.qb_value = q.qu_value;
if (fdq) {
if (fdq->d_fieldmask & QC_SPC_SOFT) {
q.qu_warn = cpu_to_be64(fdq->d_spc_softlimit >> sdp->sd_sb.sb_bsize_shift);
qd->qd_qb.qb_warn = q.qu_warn;
}
if (fdq->d_fieldmask & QC_SPC_HARD) {
q.qu_limit = cpu_to_be64(fdq->d_spc_hardlimit >> sdp->sd_sb.sb_bsize_shift);
qd->qd_qb.qb_limit = q.qu_limit;
}
if (fdq->d_fieldmask & QC_SPACE) {
q.qu_value = cpu_to_be64(fdq->d_space >> sdp->sd_sb.sb_bsize_shift);
qd->qd_qb.qb_value = q.qu_value;
}
}
err = gfs2_write_disk_quota(sdp, &q, loc);
if (!err) {
size = loc + sizeof(struct gfs2_quota);
if (size > inode->i_size)
i_size_write(inode, size);
inode->i_mtime = inode_set_ctime_current(inode);
mark_inode_dirty(inode);
set_bit(QDF_REFRESH, &qd->qd_flags);
}
return err;
}
static int do_sync(unsigned int num_qd, struct gfs2_quota_data **qda)
{
struct gfs2_sbd *sdp = (*qda)->qd_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_alloc_parms ap = { .aflags = 0, };
unsigned int data_blocks, ind_blocks;
struct gfs2_holder *ghs, i_gh;
unsigned int qx, x;
struct gfs2_quota_data *qd;
unsigned reserved;
loff_t offset;
unsigned int nalloc = 0, blocks;
int error;
gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota),
&data_blocks, &ind_blocks);
ghs = kmalloc_array(num_qd, sizeof(struct gfs2_holder), GFP_NOFS);
if (!ghs)
return -ENOMEM;
sort(qda, num_qd, sizeof(struct gfs2_quota_data *), sort_qd, NULL);
inode_lock(&ip->i_inode);
for (qx = 0; qx < num_qd; qx++) {
error = gfs2_glock_nq_init(qda[qx]->qd_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, &ghs[qx]);
if (error)
goto out_dq;
}
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh);
if (error)
goto out_dq;
for (x = 0; x < num_qd; x++) {
offset = qd2offset(qda[x]);
if (gfs2_write_alloc_required(ip, offset,
sizeof(struct gfs2_quota)))
nalloc++;
}
/*
* 1 blk for unstuffing inode if stuffed. We add this extra
* block to the reservation unconditionally. If the inode
* doesn't need unstuffing, the block will be released to the
* rgrp since it won't be allocated during the transaction
*/
/* +3 in the end for unstuffing block, inode size update block
* and another block in case quota straddles page boundary and
* two blocks need to be updated instead of 1 */
blocks = num_qd * data_blocks + RES_DINODE + num_qd + 3;
reserved = 1 + (nalloc * (data_blocks + ind_blocks));
ap.target = reserved;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto out_alloc;
if (nalloc)
blocks += gfs2_rg_blocks(ip, reserved) + nalloc * ind_blocks + RES_STATFS;
error = gfs2_trans_begin(sdp, blocks, 0);
if (error)
goto out_ipres;
for (x = 0; x < num_qd; x++) {
qd = qda[x];
offset = qd2offset(qd);
error = gfs2_adjust_quota(sdp, offset, qd->qd_change_sync, qd,
NULL);
if (error)
goto out_end_trans;
do_qc(qd, -qd->qd_change_sync, QC_SYNC);
set_bit(QDF_REFRESH, &qd->qd_flags);
}
out_end_trans:
gfs2_trans_end(sdp);
out_ipres:
gfs2_inplace_release(ip);
out_alloc:
gfs2_glock_dq_uninit(&i_gh);
out_dq:
while (qx--)
gfs2_glock_dq_uninit(&ghs[qx]);
inode_unlock(&ip->i_inode);
kfree(ghs);
gfs2_log_flush(ip->i_gl->gl_name.ln_sbd, ip->i_gl,
GFS2_LOG_HEAD_FLUSH_NORMAL | GFS2_LFC_DO_SYNC);
if (!error) {
for (x = 0; x < num_qd; x++)
qda[x]->qd_sync_gen = sdp->sd_quota_sync_gen;
}
return error;
}
static int update_qd(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_quota q;
struct gfs2_quota_lvb *qlvb;
loff_t pos;
int error;
memset(&q, 0, sizeof(struct gfs2_quota));
pos = qd2offset(qd);
error = gfs2_internal_read(ip, (char *)&q, &pos, sizeof(q));
if (error < 0)
return error;
qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr;
qlvb->qb_magic = cpu_to_be32(GFS2_MAGIC);
qlvb->__pad = 0;
qlvb->qb_limit = q.qu_limit;
qlvb->qb_warn = q.qu_warn;
qlvb->qb_value = q.qu_value;
qd->qd_qb = *qlvb;
return 0;
}
static int do_glock(struct gfs2_quota_data *qd, int force_refresh,
struct gfs2_holder *q_gh)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_holder i_gh;
int error;
gfs2_assert_warn(sdp, sdp == qd->qd_gl->gl_name.ln_sbd);
restart:
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_SHARED, 0, q_gh);
if (error)
return error;
if (test_and_clear_bit(QDF_REFRESH, &qd->qd_flags))
force_refresh = FORCE;
qd->qd_qb = *(struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr;
if (force_refresh || qd->qd_qb.qb_magic != cpu_to_be32(GFS2_MAGIC)) {
gfs2_glock_dq_uninit(q_gh);
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, q_gh);
if (error)
return error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &i_gh);
if (error)
goto fail;
error = update_qd(sdp, qd);
if (error)
goto fail_gunlock;
gfs2_glock_dq_uninit(&i_gh);
gfs2_glock_dq_uninit(q_gh);
force_refresh = 0;
goto restart;
}
return 0;
fail_gunlock:
gfs2_glock_dq_uninit(&i_gh);
fail:
gfs2_glock_dq_uninit(q_gh);
return error;
}
int gfs2_quota_lock(struct gfs2_inode *ip, kuid_t uid, kgid_t gid)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_quota_data *qd;
u32 x;
int error;
if (sdp->sd_args.ar_quota != GFS2_QUOTA_ON &&
sdp->sd_args.ar_quota != GFS2_QUOTA_QUIET)
return 0;
error = gfs2_quota_hold(ip, uid, gid);
if (error)
return error;
sort(ip->i_qadata->qa_qd, ip->i_qadata->qa_qd_num,
sizeof(struct gfs2_quota_data *), sort_qd, NULL);
for (x = 0; x < ip->i_qadata->qa_qd_num; x++) {
qd = ip->i_qadata->qa_qd[x];
error = do_glock(qd, NO_FORCE, &ip->i_qadata->qa_qd_ghs[x]);
if (error)
break;
}
if (!error)
set_bit(GIF_QD_LOCKED, &ip->i_flags);
else {
while (x--)
gfs2_glock_dq_uninit(&ip->i_qadata->qa_qd_ghs[x]);
gfs2_quota_unhold(ip);
}
return error;
}
static bool need_sync(struct gfs2_quota_data *qd)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
struct gfs2_tune *gt = &sdp->sd_tune;
s64 value;
unsigned int num, den;
if (!qd->qd_qb.qb_limit)
return false;
spin_lock(&qd_lock);
value = qd->qd_change;
spin_unlock(&qd_lock);
spin_lock(>->gt_spin);
num = gt->gt_quota_scale_num;
den = gt->gt_quota_scale_den;
spin_unlock(>->gt_spin);
if (value <= 0)
return false;
else if ((s64)be64_to_cpu(qd->qd_qb.qb_value) >=
(s64)be64_to_cpu(qd->qd_qb.qb_limit))
return false;
else {
value *= gfs2_jindex_size(sdp) * num;
value = div_s64(value, den);
value += (s64)be64_to_cpu(qd->qd_qb.qb_value);
if (value < (s64)be64_to_cpu(qd->qd_qb.qb_limit))
return false;
}
return true;
}
void gfs2_quota_unlock(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_quota_data *qda[2 * GFS2_MAXQUOTAS];
unsigned int count = 0;
u32 x;
int found;
if (!test_and_clear_bit(GIF_QD_LOCKED, &ip->i_flags))
return;
for (x = 0; x < ip->i_qadata->qa_qd_num; x++) {
struct gfs2_quota_data *qd;
bool sync;
qd = ip->i_qadata->qa_qd[x];
sync = need_sync(qd);
gfs2_glock_dq_uninit(&ip->i_qadata->qa_qd_ghs[x]);
if (!sync)
continue;
spin_lock(&qd_lock);
found = qd_check_sync(sdp, qd, NULL);
spin_unlock(&qd_lock);
if (!found)
continue;
if (!qd_bh_get_or_undo(sdp, qd))
qda[count++] = qd;
}
if (count) {
do_sync(count, qda);
for (x = 0; x < count; x++)
qd_unlock(qda[x]);
}
gfs2_quota_unhold(ip);
}
#define MAX_LINE 256
static int print_message(struct gfs2_quota_data *qd, char *type)
{
struct gfs2_sbd *sdp = qd->qd_sbd;
if (sdp->sd_args.ar_quota != GFS2_QUOTA_QUIET)
fs_info(sdp, "quota %s for %s %u\n",
type,
(qd->qd_id.type == USRQUOTA) ? "user" : "group",
from_kqid(&init_user_ns, qd->qd_id));
return 0;
}
/**
* gfs2_quota_check - check if allocating new blocks will exceed quota
* @ip: The inode for which this check is being performed
* @uid: The uid to check against
* @gid: The gid to check against
* @ap: The allocation parameters. ap->target contains the requested
* blocks. ap->min_target, if set, contains the minimum blks
* requested.
*
* Returns: 0 on success.
* min_req = ap->min_target ? ap->min_target : ap->target;
* quota must allow at least min_req blks for success and
* ap->allowed is set to the number of blocks allowed
*
* -EDQUOT otherwise, quota violation. ap->allowed is set to number
* of blocks available.
*/
int gfs2_quota_check(struct gfs2_inode *ip, kuid_t uid, kgid_t gid,
struct gfs2_alloc_parms *ap)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_quota_data *qd;
s64 value, warn, limit;
u32 x;
int error = 0;
ap->allowed = UINT_MAX; /* Assume we are permitted a whole lot */
if (!test_bit(GIF_QD_LOCKED, &ip->i_flags))
return 0;
for (x = 0; x < ip->i_qadata->qa_qd_num; x++) {
qd = ip->i_qadata->qa_qd[x];
if (!(qid_eq(qd->qd_id, make_kqid_uid(uid)) ||
qid_eq(qd->qd_id, make_kqid_gid(gid))))
continue;
warn = (s64)be64_to_cpu(qd->qd_qb.qb_warn);
limit = (s64)be64_to_cpu(qd->qd_qb.qb_limit);
value = (s64)be64_to_cpu(qd->qd_qb.qb_value);
spin_lock(&qd_lock);
value += qd->qd_change;
spin_unlock(&qd_lock);
if (limit > 0 && (limit - value) < ap->allowed)
ap->allowed = limit - value;
/* If we can't meet the target */
if (limit && limit < (value + (s64)ap->target)) {
/* If no min_target specified or we don't meet
* min_target, return -EDQUOT */
if (!ap->min_target || ap->min_target > ap->allowed) {
if (!test_and_set_bit(QDF_QMSG_QUIET,
&qd->qd_flags)) {
print_message(qd, "exceeded");
quota_send_warning(qd->qd_id,
sdp->sd_vfs->s_dev,
QUOTA_NL_BHARDWARN);
}
error = -EDQUOT;
break;
}
} else if (warn && warn < value &&
time_after_eq(jiffies, qd->qd_last_warn +
gfs2_tune_get(sdp, gt_quota_warn_period)
* HZ)) {
quota_send_warning(qd->qd_id,
sdp->sd_vfs->s_dev, QUOTA_NL_BSOFTWARN);
error = print_message(qd, "warning");
qd->qd_last_warn = jiffies;
}
}
return error;
}
void gfs2_quota_change(struct gfs2_inode *ip, s64 change,
kuid_t uid, kgid_t gid)
{
struct gfs2_quota_data *qd;
u32 x;
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
if ((sdp->sd_args.ar_quota != GFS2_QUOTA_ON &&
sdp->sd_args.ar_quota != GFS2_QUOTA_QUIET) ||
gfs2_assert_warn(sdp, change))
return;
if (ip->i_diskflags & GFS2_DIF_SYSTEM)
return;
if (gfs2_assert_withdraw(sdp, ip->i_qadata &&
ip->i_qadata->qa_ref > 0))
return;
for (x = 0; x < ip->i_qadata->qa_qd_num; x++) {
qd = ip->i_qadata->qa_qd[x];
if (qid_eq(qd->qd_id, make_kqid_uid(uid)) ||
qid_eq(qd->qd_id, make_kqid_gid(gid))) {
do_qc(qd, change, QC_CHANGE);
}
}
}
static bool qd_changed(struct gfs2_sbd *sdp)
{
struct gfs2_quota_data *qd;
bool changed = false;
spin_lock(&qd_lock);
list_for_each_entry(qd, &sdp->sd_quota_list, qd_list) {
if (test_bit(QDF_LOCKED, &qd->qd_flags) ||
!test_bit(QDF_CHANGE, &qd->qd_flags))
continue;
changed = true;
break;
}
spin_unlock(&qd_lock);
return changed;
}
int gfs2_quota_sync(struct super_block *sb, int type)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_quota_data **qda;
unsigned int max_qd = PAGE_SIZE / sizeof(struct gfs2_holder);
unsigned int num_qd;
unsigned int x;
int error = 0;
if (!qd_changed(sdp))
return 0;
qda = kcalloc(max_qd, sizeof(struct gfs2_quota_data *), GFP_KERNEL);
if (!qda)
return -ENOMEM;
mutex_lock(&sdp->sd_quota_sync_mutex);
sdp->sd_quota_sync_gen++;
do {
num_qd = 0;
for (;;) {
error = qd_fish(sdp, qda + num_qd);
if (error || !qda[num_qd])
break;
if (++num_qd == max_qd)
break;
}
if (num_qd) {
if (!error)
error = do_sync(num_qd, qda);
for (x = 0; x < num_qd; x++)
qd_unlock(qda[x]);
}
} while (!error && num_qd == max_qd);
mutex_unlock(&sdp->sd_quota_sync_mutex);
kfree(qda);
return error;
}
int gfs2_quota_refresh(struct gfs2_sbd *sdp, struct kqid qid)
{
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh;
int error;
error = qd_get(sdp, qid, &qd);
if (error)
return error;
error = do_glock(qd, FORCE, &q_gh);
if (!error)
gfs2_glock_dq_uninit(&q_gh);
qd_put(qd);
return error;
}
int gfs2_quota_init(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode);
u64 size = i_size_read(sdp->sd_qc_inode);
unsigned int blocks = size >> sdp->sd_sb.sb_bsize_shift;
unsigned int x, slot = 0;
unsigned int found = 0;
unsigned int hash;
unsigned int bm_size;
u64 dblock;
u32 extlen = 0;
int error;
if (gfs2_check_internal_file_size(sdp->sd_qc_inode, 1, 64 << 20))
return -EIO;
sdp->sd_quota_slots = blocks * sdp->sd_qc_per_block;
bm_size = DIV_ROUND_UP(sdp->sd_quota_slots, 8 * sizeof(unsigned long));
bm_size *= sizeof(unsigned long);
error = -ENOMEM;
sdp->sd_quota_bitmap = kzalloc(bm_size, GFP_NOFS | __GFP_NOWARN);
if (sdp->sd_quota_bitmap == NULL)
sdp->sd_quota_bitmap = __vmalloc(bm_size, GFP_NOFS |
__GFP_ZERO);
if (!sdp->sd_quota_bitmap)
return error;
for (x = 0; x < blocks; x++) {
struct buffer_head *bh;
const struct gfs2_quota_change *qc;
unsigned int y;
if (!extlen) {
extlen = 32;
error = gfs2_get_extent(&ip->i_inode, x, &dblock, &extlen);
if (error)
goto fail;
}
error = -EIO;
bh = gfs2_meta_ra(ip->i_gl, dblock, extlen);
if (!bh)
goto fail;
if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC)) {
brelse(bh);
goto fail;
}
qc = (const struct gfs2_quota_change *)(bh->b_data + sizeof(struct gfs2_meta_header));
for (y = 0; y < sdp->sd_qc_per_block && slot < sdp->sd_quota_slots;
y++, slot++) {
struct gfs2_quota_data *qd;
s64 qc_change = be64_to_cpu(qc->qc_change);
u32 qc_flags = be32_to_cpu(qc->qc_flags);
enum quota_type qtype = (qc_flags & GFS2_QCF_USER) ?
USRQUOTA : GRPQUOTA;
struct kqid qc_id = make_kqid(&init_user_ns, qtype,
be32_to_cpu(qc->qc_id));
qc++;
if (!qc_change)
continue;
hash = gfs2_qd_hash(sdp, qc_id);
qd = qd_alloc(hash, sdp, qc_id);
if (qd == NULL) {
brelse(bh);
goto fail;
}
set_bit(QDF_CHANGE, &qd->qd_flags);
qd->qd_change = qc_change;
qd->qd_slot = slot;
qd->qd_slot_ref = 1;
spin_lock(&qd_lock);
BUG_ON(test_and_set_bit(slot, sdp->sd_quota_bitmap));
list_add(&qd->qd_list, &sdp->sd_quota_list);
atomic_inc(&sdp->sd_quota_count);
spin_unlock(&qd_lock);
spin_lock_bucket(hash);
hlist_bl_add_head_rcu(&qd->qd_hlist, &qd_hash_table[hash]);
spin_unlock_bucket(hash);
found++;
}
brelse(bh);
dblock++;
extlen--;
}
if (found)
fs_info(sdp, "found %u quota changes\n", found);
return 0;
fail:
gfs2_quota_cleanup(sdp);
return error;
}
void gfs2_quota_cleanup(struct gfs2_sbd *sdp)
{
struct gfs2_quota_data *qd;
LIST_HEAD(dispose);
int count;
BUG_ON(test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags));
spin_lock(&qd_lock);
list_for_each_entry(qd, &sdp->sd_quota_list, qd_list) {
spin_lock(&qd->qd_lockref.lock);
if (qd->qd_lockref.count != 0) {
spin_unlock(&qd->qd_lockref.lock);
continue;
}
lockref_mark_dead(&qd->qd_lockref);
spin_unlock(&qd->qd_lockref.lock);
list_lru_del(&gfs2_qd_lru, &qd->qd_lru);
list_add(&qd->qd_lru, &dispose);
}
spin_unlock(&qd_lock);
gfs2_qd_list_dispose(&dispose);
wait_event_timeout(sdp->sd_kill_wait,
(count = atomic_read(&sdp->sd_quota_count)) == 0,
HZ * 60);
if (count != 0)
fs_err(sdp, "%d left-over quota data objects\n", count);
kvfree(sdp->sd_quota_bitmap);
sdp->sd_quota_bitmap = NULL;
}
static void quotad_error(struct gfs2_sbd *sdp, const char *msg, int error)
{
if (error == 0 || error == -EROFS)
return;
if (!gfs2_withdrawn(sdp)) {
if (!cmpxchg(&sdp->sd_log_error, 0, error))
fs_err(sdp, "gfs2_quotad: %s error %d\n", msg, error);
wake_up(&sdp->sd_logd_waitq);
}
}
static void quotad_check_timeo(struct gfs2_sbd *sdp, const char *msg,
int (*fxn)(struct super_block *sb, int type),
unsigned long t, unsigned long *timeo,
unsigned int *new_timeo)
{
if (t >= *timeo) {
int error = fxn(sdp->sd_vfs, 0);
quotad_error(sdp, msg, error);
*timeo = gfs2_tune_get_i(&sdp->sd_tune, new_timeo) * HZ;
} else {
*timeo -= t;
}
}
void gfs2_wake_up_statfs(struct gfs2_sbd *sdp) {
if (!sdp->sd_statfs_force_sync) {
sdp->sd_statfs_force_sync = 1;
wake_up(&sdp->sd_quota_wait);
}
}
/**
* gfs2_quotad - Write cached quota changes into the quota file
* @data: Pointer to GFS2 superblock
*
*/
int gfs2_quotad(void *data)
{
struct gfs2_sbd *sdp = data;
struct gfs2_tune *tune = &sdp->sd_tune;
unsigned long statfs_timeo = 0;
unsigned long quotad_timeo = 0;
unsigned long t = 0;
while (!kthread_should_stop()) {
if (gfs2_withdrawn(sdp))
break;
/* Update the master statfs file */
if (sdp->sd_statfs_force_sync) {
int error = gfs2_statfs_sync(sdp->sd_vfs, 0);
quotad_error(sdp, "statfs", error);
statfs_timeo = gfs2_tune_get(sdp, gt_statfs_quantum) * HZ;
}
else
quotad_check_timeo(sdp, "statfs", gfs2_statfs_sync, t,
&statfs_timeo,
&tune->gt_statfs_quantum);
/* Update quota file */
quotad_check_timeo(sdp, "sync", gfs2_quota_sync, t,
"ad_timeo, &tune->gt_quota_quantum);
try_to_freeze();
t = min(quotad_timeo, statfs_timeo);
t = wait_event_interruptible_timeout(sdp->sd_quota_wait,
sdp->sd_statfs_force_sync ||
gfs2_withdrawn(sdp) ||
kthread_should_stop(),
t);
if (sdp->sd_statfs_force_sync)
t = 0;
}
return 0;
}
static int gfs2_quota_get_state(struct super_block *sb, struct qc_state *state)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
memset(state, 0, sizeof(*state));
switch (sdp->sd_args.ar_quota) {
case GFS2_QUOTA_QUIET:
fallthrough;
case GFS2_QUOTA_ON:
state->s_state[USRQUOTA].flags |= QCI_LIMITS_ENFORCED;
state->s_state[GRPQUOTA].flags |= QCI_LIMITS_ENFORCED;
fallthrough;
case GFS2_QUOTA_ACCOUNT:
state->s_state[USRQUOTA].flags |= QCI_ACCT_ENABLED |
QCI_SYSFILE;
state->s_state[GRPQUOTA].flags |= QCI_ACCT_ENABLED |
QCI_SYSFILE;
break;
case GFS2_QUOTA_OFF:
break;
}
if (sdp->sd_quota_inode) {
state->s_state[USRQUOTA].ino =
GFS2_I(sdp->sd_quota_inode)->i_no_addr;
state->s_state[USRQUOTA].blocks = sdp->sd_quota_inode->i_blocks;
}
state->s_state[USRQUOTA].nextents = 1; /* unsupported */
state->s_state[GRPQUOTA] = state->s_state[USRQUOTA];
state->s_incoredqs = list_lru_count(&gfs2_qd_lru);
return 0;
}
static int gfs2_get_dqblk(struct super_block *sb, struct kqid qid,
struct qc_dqblk *fdq)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_quota_lvb *qlvb;
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh;
int error;
memset(fdq, 0, sizeof(*fdq));
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return -ESRCH; /* Crazy XFS error code */
if ((qid.type != USRQUOTA) &&
(qid.type != GRPQUOTA))
return -EINVAL;
error = qd_get(sdp, qid, &qd);
if (error)
return error;
error = do_glock(qd, FORCE, &q_gh);
if (error)
goto out;
qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr;
fdq->d_spc_hardlimit = be64_to_cpu(qlvb->qb_limit) << sdp->sd_sb.sb_bsize_shift;
fdq->d_spc_softlimit = be64_to_cpu(qlvb->qb_warn) << sdp->sd_sb.sb_bsize_shift;
fdq->d_space = be64_to_cpu(qlvb->qb_value) << sdp->sd_sb.sb_bsize_shift;
gfs2_glock_dq_uninit(&q_gh);
out:
qd_put(qd);
return error;
}
/* GFS2 only supports a subset of the XFS fields */
#define GFS2_FIELDMASK (QC_SPC_SOFT|QC_SPC_HARD|QC_SPACE)
static int gfs2_set_dqblk(struct super_block *sb, struct kqid qid,
struct qc_dqblk *fdq)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode);
struct gfs2_quota_data *qd;
struct gfs2_holder q_gh, i_gh;
unsigned int data_blocks, ind_blocks;
unsigned int blocks = 0;
int alloc_required;
loff_t offset;
int error;
if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF)
return -ESRCH; /* Crazy XFS error code */
if ((qid.type != USRQUOTA) &&
(qid.type != GRPQUOTA))
return -EINVAL;
if (fdq->d_fieldmask & ~GFS2_FIELDMASK)
return -EINVAL;
error = qd_get(sdp, qid, &qd);
if (error)
return error;
error = gfs2_qa_get(ip);
if (error)
goto out_put;
inode_lock(&ip->i_inode);
error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE, 0, &q_gh);
if (error)
goto out_unlockput;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh);
if (error)
goto out_q;
/* Check for existing entry, if none then alloc new blocks */
error = update_qd(sdp, qd);
if (error)
goto out_i;
/* If nothing has changed, this is a no-op */
if ((fdq->d_fieldmask & QC_SPC_SOFT) &&
((fdq->d_spc_softlimit >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_warn)))
fdq->d_fieldmask ^= QC_SPC_SOFT;
if ((fdq->d_fieldmask & QC_SPC_HARD) &&
((fdq->d_spc_hardlimit >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_limit)))
fdq->d_fieldmask ^= QC_SPC_HARD;
if ((fdq->d_fieldmask & QC_SPACE) &&
((fdq->d_space >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_value)))
fdq->d_fieldmask ^= QC_SPACE;
if (fdq->d_fieldmask == 0)
goto out_i;
offset = qd2offset(qd);
alloc_required = gfs2_write_alloc_required(ip, offset, sizeof(struct gfs2_quota));
if (gfs2_is_stuffed(ip))
alloc_required = 1;
if (alloc_required) {
struct gfs2_alloc_parms ap = { .aflags = 0, };
gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota),
&data_blocks, &ind_blocks);
blocks = 1 + data_blocks + ind_blocks;
ap.target = blocks;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto out_i;
blocks += gfs2_rg_blocks(ip, blocks);
}
/* Some quotas span block boundaries and can update two blocks,
adding an extra block to the transaction to handle such quotas */
error = gfs2_trans_begin(sdp, blocks + RES_DINODE + 2, 0);
if (error)
goto out_release;
/* Apply changes */
error = gfs2_adjust_quota(sdp, offset, 0, qd, fdq);
if (!error)
clear_bit(QDF_QMSG_QUIET, &qd->qd_flags);
gfs2_trans_end(sdp);
out_release:
if (alloc_required)
gfs2_inplace_release(ip);
out_i:
gfs2_glock_dq_uninit(&i_gh);
out_q:
gfs2_glock_dq_uninit(&q_gh);
out_unlockput:
gfs2_qa_put(ip);
inode_unlock(&ip->i_inode);
out_put:
qd_put(qd);
return error;
}
const struct quotactl_ops gfs2_quotactl_ops = {
.quota_sync = gfs2_quota_sync,
.get_state = gfs2_quota_get_state,
.get_dqblk = gfs2_get_dqblk,
.set_dqblk = gfs2_set_dqblk,
};
void __init gfs2_quota_hash_init(void)
{
unsigned i;
for(i = 0; i < GFS2_QD_HASH_SIZE; i++)
INIT_HLIST_BL_HEAD(&qd_hash_table[i]);
}
| linux-master | fs/gfs2/quota.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gfs2_ondisk.h>
#include <linux/rcupdate.h>
#include <linux/rculist_bl.h>
#include <linux/atomic.h>
#include <linux/mempool.h>
#include "gfs2.h"
#include "incore.h"
#include "super.h"
#include "sys.h"
#include "util.h"
#include "glock.h"
#include "quota.h"
#include "recovery.h"
#include "dir.h"
#include "glops.h"
struct workqueue_struct *gfs2_control_wq;
static void gfs2_init_inode_once(void *foo)
{
struct gfs2_inode *ip = foo;
inode_init_once(&ip->i_inode);
atomic_set(&ip->i_sizehint, 0);
init_rwsem(&ip->i_rw_mutex);
INIT_LIST_HEAD(&ip->i_ordered);
ip->i_qadata = NULL;
gfs2_holder_mark_uninitialized(&ip->i_rgd_gh);
memset(&ip->i_res, 0, sizeof(ip->i_res));
RB_CLEAR_NODE(&ip->i_res.rs_node);
ip->i_hash_cache = NULL;
gfs2_holder_mark_uninitialized(&ip->i_iopen_gh);
}
static void gfs2_init_glock_once(void *foo)
{
struct gfs2_glock *gl = foo;
spin_lock_init(&gl->gl_lockref.lock);
INIT_LIST_HEAD(&gl->gl_holders);
INIT_LIST_HEAD(&gl->gl_lru);
INIT_LIST_HEAD(&gl->gl_ail_list);
atomic_set(&gl->gl_ail_count, 0);
atomic_set(&gl->gl_revokes, 0);
}
static void gfs2_init_gl_aspace_once(void *foo)
{
struct gfs2_glock_aspace *gla = foo;
gfs2_init_glock_once(&gla->glock);
address_space_init_once(&gla->mapping);
}
/**
* init_gfs2_fs - Register GFS2 as a filesystem
*
* Returns: 0 on success, error code on failure
*/
static int __init init_gfs2_fs(void)
{
int error;
gfs2_str2qstr(&gfs2_qdot, ".");
gfs2_str2qstr(&gfs2_qdotdot, "..");
gfs2_quota_hash_init();
error = gfs2_sys_init();
if (error)
return error;
error = list_lru_init(&gfs2_qd_lru);
if (error)
goto fail_lru;
error = gfs2_glock_init();
if (error)
goto fail_glock;
error = -ENOMEM;
gfs2_glock_cachep = kmem_cache_create("gfs2_glock",
sizeof(struct gfs2_glock),
0, SLAB_RECLAIM_ACCOUNT,
gfs2_init_glock_once);
if (!gfs2_glock_cachep)
goto fail_cachep1;
gfs2_glock_aspace_cachep = kmem_cache_create("gfs2_glock(aspace)",
sizeof(struct gfs2_glock_aspace),
0, 0, gfs2_init_gl_aspace_once);
if (!gfs2_glock_aspace_cachep)
goto fail_cachep2;
gfs2_inode_cachep = kmem_cache_create("gfs2_inode",
sizeof(struct gfs2_inode),
0, SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|
SLAB_ACCOUNT,
gfs2_init_inode_once);
if (!gfs2_inode_cachep)
goto fail_cachep3;
gfs2_bufdata_cachep = kmem_cache_create("gfs2_bufdata",
sizeof(struct gfs2_bufdata),
0, 0, NULL);
if (!gfs2_bufdata_cachep)
goto fail_cachep4;
gfs2_rgrpd_cachep = kmem_cache_create("gfs2_rgrpd",
sizeof(struct gfs2_rgrpd),
0, 0, NULL);
if (!gfs2_rgrpd_cachep)
goto fail_cachep5;
gfs2_quotad_cachep = kmem_cache_create("gfs2_quotad",
sizeof(struct gfs2_quota_data),
0, SLAB_RECLAIM_ACCOUNT, NULL);
if (!gfs2_quotad_cachep)
goto fail_cachep6;
gfs2_qadata_cachep = kmem_cache_create("gfs2_qadata",
sizeof(struct gfs2_qadata),
0, 0, NULL);
if (!gfs2_qadata_cachep)
goto fail_cachep7;
gfs2_trans_cachep = kmem_cache_create("gfs2_trans",
sizeof(struct gfs2_trans),
0, 0, NULL);
if (!gfs2_trans_cachep)
goto fail_cachep8;
error = register_shrinker(&gfs2_qd_shrinker, "gfs2-qd");
if (error)
goto fail_shrinker;
error = -ENOMEM;
gfs2_recovery_wq = alloc_workqueue("gfs2_recovery",
WQ_MEM_RECLAIM | WQ_FREEZABLE, 0);
if (!gfs2_recovery_wq)
goto fail_wq1;
gfs2_control_wq = alloc_workqueue("gfs2_control",
WQ_UNBOUND | WQ_FREEZABLE, 0);
if (!gfs2_control_wq)
goto fail_wq2;
gfs2_freeze_wq = alloc_workqueue("gfs2_freeze", 0, 0);
if (!gfs2_freeze_wq)
goto fail_wq3;
gfs2_page_pool = mempool_create_page_pool(64, 0);
if (!gfs2_page_pool)
goto fail_mempool;
gfs2_register_debugfs();
error = register_filesystem(&gfs2_fs_type);
if (error)
goto fail_fs1;
error = register_filesystem(&gfs2meta_fs_type);
if (error)
goto fail_fs2;
pr_info("GFS2 installed\n");
return 0;
fail_fs2:
unregister_filesystem(&gfs2_fs_type);
fail_fs1:
mempool_destroy(gfs2_page_pool);
fail_mempool:
destroy_workqueue(gfs2_freeze_wq);
fail_wq3:
destroy_workqueue(gfs2_control_wq);
fail_wq2:
destroy_workqueue(gfs2_recovery_wq);
fail_wq1:
unregister_shrinker(&gfs2_qd_shrinker);
fail_shrinker:
kmem_cache_destroy(gfs2_trans_cachep);
fail_cachep8:
kmem_cache_destroy(gfs2_qadata_cachep);
fail_cachep7:
kmem_cache_destroy(gfs2_quotad_cachep);
fail_cachep6:
kmem_cache_destroy(gfs2_rgrpd_cachep);
fail_cachep5:
kmem_cache_destroy(gfs2_bufdata_cachep);
fail_cachep4:
kmem_cache_destroy(gfs2_inode_cachep);
fail_cachep3:
kmem_cache_destroy(gfs2_glock_aspace_cachep);
fail_cachep2:
kmem_cache_destroy(gfs2_glock_cachep);
fail_cachep1:
gfs2_glock_exit();
fail_glock:
list_lru_destroy(&gfs2_qd_lru);
fail_lru:
gfs2_sys_uninit();
return error;
}
/**
* exit_gfs2_fs - Unregister the file system
*
*/
static void __exit exit_gfs2_fs(void)
{
unregister_shrinker(&gfs2_qd_shrinker);
gfs2_glock_exit();
gfs2_unregister_debugfs();
unregister_filesystem(&gfs2_fs_type);
unregister_filesystem(&gfs2meta_fs_type);
destroy_workqueue(gfs2_recovery_wq);
destroy_workqueue(gfs2_control_wq);
destroy_workqueue(gfs2_freeze_wq);
list_lru_destroy(&gfs2_qd_lru);
rcu_barrier();
mempool_destroy(gfs2_page_pool);
kmem_cache_destroy(gfs2_trans_cachep);
kmem_cache_destroy(gfs2_qadata_cachep);
kmem_cache_destroy(gfs2_quotad_cachep);
kmem_cache_destroy(gfs2_rgrpd_cachep);
kmem_cache_destroy(gfs2_bufdata_cachep);
kmem_cache_destroy(gfs2_inode_cachep);
kmem_cache_destroy(gfs2_glock_aspace_cachep);
kmem_cache_destroy(gfs2_glock_cachep);
gfs2_sys_uninit();
}
MODULE_DESCRIPTION("Global File System");
MODULE_AUTHOR("Red Hat, Inc.");
MODULE_LICENSE("GPL");
module_init(init_gfs2_fs);
module_exit(exit_gfs2_fs);
| linux-master | fs/gfs2/main.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include <linux/iomap.h>
#include <linux/ktime.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "log.h"
#include "super.h"
#include "trans.h"
#include "dir.h"
#include "util.h"
#include "aops.h"
#include "trace_gfs2.h"
/* This doesn't need to be that large as max 64 bit pointers in a 4k
* block is 512, so __u16 is fine for that. It saves stack space to
* keep it small.
*/
struct metapath {
struct buffer_head *mp_bh[GFS2_MAX_META_HEIGHT];
__u16 mp_list[GFS2_MAX_META_HEIGHT];
int mp_fheight; /* find_metapath height */
int mp_aheight; /* actual height (lookup height) */
};
static int punch_hole(struct gfs2_inode *ip, u64 offset, u64 length);
/**
* gfs2_unstuffer_page - unstuff a stuffed inode into a block cached by a page
* @ip: the inode
* @dibh: the dinode buffer
* @block: the block number that was allocated
* @page: The (optional) page. This is looked up if @page is NULL
*
* Returns: errno
*/
static int gfs2_unstuffer_page(struct gfs2_inode *ip, struct buffer_head *dibh,
u64 block, struct page *page)
{
struct inode *inode = &ip->i_inode;
if (!PageUptodate(page)) {
void *kaddr = kmap(page);
u64 dsize = i_size_read(inode);
memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode), dsize);
memset(kaddr + dsize, 0, PAGE_SIZE - dsize);
kunmap(page);
SetPageUptodate(page);
}
if (gfs2_is_jdata(ip)) {
struct buffer_head *bh;
if (!page_has_buffers(page))
create_empty_buffers(page, BIT(inode->i_blkbits),
BIT(BH_Uptodate));
bh = page_buffers(page);
if (!buffer_mapped(bh))
map_bh(bh, inode->i_sb, block);
set_buffer_uptodate(bh);
gfs2_trans_add_data(ip->i_gl, bh);
} else {
set_page_dirty(page);
gfs2_ordered_add_inode(ip);
}
return 0;
}
static int __gfs2_unstuff_inode(struct gfs2_inode *ip, struct page *page)
{
struct buffer_head *bh, *dibh;
struct gfs2_dinode *di;
u64 block = 0;
int isdir = gfs2_is_dir(ip);
int error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
if (i_size_read(&ip->i_inode)) {
/* Get a free block, fill it with the stuffed data,
and write it out to disk */
unsigned int n = 1;
error = gfs2_alloc_blocks(ip, &block, &n, 0, NULL);
if (error)
goto out_brelse;
if (isdir) {
gfs2_trans_remove_revoke(GFS2_SB(&ip->i_inode), block, 1);
error = gfs2_dir_get_new_buffer(ip, block, &bh);
if (error)
goto out_brelse;
gfs2_buffer_copy_tail(bh, sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
brelse(bh);
} else {
error = gfs2_unstuffer_page(ip, dibh, block, page);
if (error)
goto out_brelse;
}
}
/* Set up the pointer to the new block */
gfs2_trans_add_meta(ip->i_gl, dibh);
di = (struct gfs2_dinode *)dibh->b_data;
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
if (i_size_read(&ip->i_inode)) {
*(__be64 *)(di + 1) = cpu_to_be64(block);
gfs2_add_inode_blocks(&ip->i_inode, 1);
di->di_blocks = cpu_to_be64(gfs2_get_inode_blocks(&ip->i_inode));
}
ip->i_height = 1;
di->di_height = cpu_to_be16(1);
out_brelse:
brelse(dibh);
return error;
}
/**
* gfs2_unstuff_dinode - Unstuff a dinode when the data has grown too big
* @ip: The GFS2 inode to unstuff
*
* This routine unstuffs a dinode and returns it to a "normal" state such
* that the height can be grown in the traditional way.
*
* Returns: errno
*/
int gfs2_unstuff_dinode(struct gfs2_inode *ip)
{
struct inode *inode = &ip->i_inode;
struct page *page;
int error;
down_write(&ip->i_rw_mutex);
page = grab_cache_page(inode->i_mapping, 0);
error = -ENOMEM;
if (!page)
goto out;
error = __gfs2_unstuff_inode(ip, page);
unlock_page(page);
put_page(page);
out:
up_write(&ip->i_rw_mutex);
return error;
}
/**
* find_metapath - Find path through the metadata tree
* @sdp: The superblock
* @block: The disk block to look up
* @mp: The metapath to return the result in
* @height: The pre-calculated height of the metadata tree
*
* This routine returns a struct metapath structure that defines a path
* through the metadata of inode "ip" to get to block "block".
*
* Example:
* Given: "ip" is a height 3 file, "offset" is 101342453, and this is a
* filesystem with a blocksize of 4096.
*
* find_metapath() would return a struct metapath structure set to:
* mp_fheight = 3, mp_list[0] = 0, mp_list[1] = 48, and mp_list[2] = 165.
*
* That means that in order to get to the block containing the byte at
* offset 101342453, we would load the indirect block pointed to by pointer
* 0 in the dinode. We would then load the indirect block pointed to by
* pointer 48 in that indirect block. We would then load the data block
* pointed to by pointer 165 in that indirect block.
*
* ----------------------------------------
* | Dinode | |
* | | 4|
* | |0 1 2 3 4 5 9|
* | | 6|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Indirect Block |
* | 5|
* | 4 4 4 4 4 5 5 1|
* |0 5 6 7 8 9 0 1 2|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Indirect Block |
* | 1 1 1 1 1 5|
* | 6 6 6 6 6 1|
* |0 3 4 5 6 7 2|
* ----------------------------------------
* |
* |
* V
* ----------------------------------------
* | Data block containing offset |
* | 101342453 |
* | |
* | |
* ----------------------------------------
*
*/
static void find_metapath(const struct gfs2_sbd *sdp, u64 block,
struct metapath *mp, unsigned int height)
{
unsigned int i;
mp->mp_fheight = height;
for (i = height; i--;)
mp->mp_list[i] = do_div(block, sdp->sd_inptrs);
}
static inline unsigned int metapath_branch_start(const struct metapath *mp)
{
if (mp->mp_list[0] == 0)
return 2;
return 1;
}
/**
* metaptr1 - Return the first possible metadata pointer in a metapath buffer
* @height: The metadata height (0 = dinode)
* @mp: The metapath
*/
static inline __be64 *metaptr1(unsigned int height, const struct metapath *mp)
{
struct buffer_head *bh = mp->mp_bh[height];
if (height == 0)
return ((__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)));
return ((__be64 *)(bh->b_data + sizeof(struct gfs2_meta_header)));
}
/**
* metapointer - Return pointer to start of metadata in a buffer
* @height: The metadata height (0 = dinode)
* @mp: The metapath
*
* Return a pointer to the block number of the next height of the metadata
* tree given a buffer containing the pointer to the current height of the
* metadata tree.
*/
static inline __be64 *metapointer(unsigned int height, const struct metapath *mp)
{
__be64 *p = metaptr1(height, mp);
return p + mp->mp_list[height];
}
static inline const __be64 *metaend(unsigned int height, const struct metapath *mp)
{
const struct buffer_head *bh = mp->mp_bh[height];
return (const __be64 *)(bh->b_data + bh->b_size);
}
static void clone_metapath(struct metapath *clone, struct metapath *mp)
{
unsigned int hgt;
*clone = *mp;
for (hgt = 0; hgt < mp->mp_aheight; hgt++)
get_bh(clone->mp_bh[hgt]);
}
static void gfs2_metapath_ra(struct gfs2_glock *gl, __be64 *start, __be64 *end)
{
const __be64 *t;
for (t = start; t < end; t++) {
struct buffer_head *rabh;
if (!*t)
continue;
rabh = gfs2_getbuf(gl, be64_to_cpu(*t), CREATE);
if (trylock_buffer(rabh)) {
if (!buffer_uptodate(rabh)) {
rabh->b_end_io = end_buffer_read_sync;
submit_bh(REQ_OP_READ | REQ_RAHEAD | REQ_META |
REQ_PRIO, rabh);
continue;
}
unlock_buffer(rabh);
}
brelse(rabh);
}
}
static int __fillup_metapath(struct gfs2_inode *ip, struct metapath *mp,
unsigned int x, unsigned int h)
{
for (; x < h; x++) {
__be64 *ptr = metapointer(x, mp);
u64 dblock = be64_to_cpu(*ptr);
int ret;
if (!dblock)
break;
ret = gfs2_meta_buffer(ip, GFS2_METATYPE_IN, dblock, &mp->mp_bh[x + 1]);
if (ret)
return ret;
}
mp->mp_aheight = x + 1;
return 0;
}
/**
* lookup_metapath - Walk the metadata tree to a specific point
* @ip: The inode
* @mp: The metapath
*
* Assumes that the inode's buffer has already been looked up and
* hooked onto mp->mp_bh[0] and that the metapath has been initialised
* by find_metapath().
*
* If this function encounters part of the tree which has not been
* allocated, it returns the current height of the tree at the point
* at which it found the unallocated block. Blocks which are found are
* added to the mp->mp_bh[] list.
*
* Returns: error
*/
static int lookup_metapath(struct gfs2_inode *ip, struct metapath *mp)
{
return __fillup_metapath(ip, mp, 0, ip->i_height - 1);
}
/**
* fillup_metapath - fill up buffers for the metadata path to a specific height
* @ip: The inode
* @mp: The metapath
* @h: The height to which it should be mapped
*
* Similar to lookup_metapath, but does lookups for a range of heights
*
* Returns: error or the number of buffers filled
*/
static int fillup_metapath(struct gfs2_inode *ip, struct metapath *mp, int h)
{
unsigned int x = 0;
int ret;
if (h) {
/* find the first buffer we need to look up. */
for (x = h - 1; x > 0; x--) {
if (mp->mp_bh[x])
break;
}
}
ret = __fillup_metapath(ip, mp, x, h);
if (ret)
return ret;
return mp->mp_aheight - x - 1;
}
static sector_t metapath_to_block(struct gfs2_sbd *sdp, struct metapath *mp)
{
sector_t factor = 1, block = 0;
int hgt;
for (hgt = mp->mp_fheight - 1; hgt >= 0; hgt--) {
if (hgt < mp->mp_aheight)
block += mp->mp_list[hgt] * factor;
factor *= sdp->sd_inptrs;
}
return block;
}
static void release_metapath(struct metapath *mp)
{
int i;
for (i = 0; i < GFS2_MAX_META_HEIGHT; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
}
/**
* gfs2_extent_length - Returns length of an extent of blocks
* @bh: The metadata block
* @ptr: Current position in @bh
* @limit: Max extent length to return
* @eob: Set to 1 if we hit "end of block"
*
* Returns: The length of the extent (minimum of one block)
*/
static inline unsigned int gfs2_extent_length(struct buffer_head *bh, __be64 *ptr, size_t limit, int *eob)
{
const __be64 *end = (__be64 *)(bh->b_data + bh->b_size);
const __be64 *first = ptr;
u64 d = be64_to_cpu(*ptr);
*eob = 0;
do {
ptr++;
if (ptr >= end)
break;
d++;
} while(be64_to_cpu(*ptr) == d);
if (ptr >= end)
*eob = 1;
return ptr - first;
}
enum walker_status { WALK_STOP, WALK_FOLLOW, WALK_CONTINUE };
/*
* gfs2_metadata_walker - walk an indirect block
* @mp: Metapath to indirect block
* @ptrs: Number of pointers to look at
*
* When returning WALK_FOLLOW, the walker must update @mp to point at the right
* indirect block to follow.
*/
typedef enum walker_status (*gfs2_metadata_walker)(struct metapath *mp,
unsigned int ptrs);
/*
* gfs2_walk_metadata - walk a tree of indirect blocks
* @inode: The inode
* @mp: Starting point of walk
* @max_len: Maximum number of blocks to walk
* @walker: Called during the walk
*
* Returns 1 if the walk was stopped by @walker, 0 if we went past @max_len or
* past the end of metadata, and a negative error code otherwise.
*/
static int gfs2_walk_metadata(struct inode *inode, struct metapath *mp,
u64 max_len, gfs2_metadata_walker walker)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
u64 factor = 1;
unsigned int hgt;
int ret;
/*
* The walk starts in the lowest allocated indirect block, which may be
* before the position indicated by @mp. Adjust @max_len accordingly
* to avoid a short walk.
*/
for (hgt = mp->mp_fheight - 1; hgt >= mp->mp_aheight; hgt--) {
max_len += mp->mp_list[hgt] * factor;
mp->mp_list[hgt] = 0;
factor *= sdp->sd_inptrs;
}
for (;;) {
u16 start = mp->mp_list[hgt];
enum walker_status status;
unsigned int ptrs;
u64 len;
/* Walk indirect block. */
ptrs = (hgt >= 1 ? sdp->sd_inptrs : sdp->sd_diptrs) - start;
len = ptrs * factor;
if (len > max_len)
ptrs = DIV_ROUND_UP_ULL(max_len, factor);
status = walker(mp, ptrs);
switch (status) {
case WALK_STOP:
return 1;
case WALK_FOLLOW:
BUG_ON(mp->mp_aheight == mp->mp_fheight);
ptrs = mp->mp_list[hgt] - start;
len = ptrs * factor;
break;
case WALK_CONTINUE:
break;
}
if (len >= max_len)
break;
max_len -= len;
if (status == WALK_FOLLOW)
goto fill_up_metapath;
lower_metapath:
/* Decrease height of metapath. */
brelse(mp->mp_bh[hgt]);
mp->mp_bh[hgt] = NULL;
mp->mp_list[hgt] = 0;
if (!hgt)
break;
hgt--;
factor *= sdp->sd_inptrs;
/* Advance in metadata tree. */
(mp->mp_list[hgt])++;
if (hgt) {
if (mp->mp_list[hgt] >= sdp->sd_inptrs)
goto lower_metapath;
} else {
if (mp->mp_list[hgt] >= sdp->sd_diptrs)
break;
}
fill_up_metapath:
/* Increase height of metapath. */
ret = fillup_metapath(ip, mp, ip->i_height - 1);
if (ret < 0)
return ret;
hgt += ret;
for (; ret; ret--)
do_div(factor, sdp->sd_inptrs);
mp->mp_aheight = hgt + 1;
}
return 0;
}
static enum walker_status gfs2_hole_walker(struct metapath *mp,
unsigned int ptrs)
{
const __be64 *start, *ptr, *end;
unsigned int hgt;
hgt = mp->mp_aheight - 1;
start = metapointer(hgt, mp);
end = start + ptrs;
for (ptr = start; ptr < end; ptr++) {
if (*ptr) {
mp->mp_list[hgt] += ptr - start;
if (mp->mp_aheight == mp->mp_fheight)
return WALK_STOP;
return WALK_FOLLOW;
}
}
return WALK_CONTINUE;
}
/**
* gfs2_hole_size - figure out the size of a hole
* @inode: The inode
* @lblock: The logical starting block number
* @len: How far to look (in blocks)
* @mp: The metapath at lblock
* @iomap: The iomap to store the hole size in
*
* This function modifies @mp.
*
* Returns: errno on error
*/
static int gfs2_hole_size(struct inode *inode, sector_t lblock, u64 len,
struct metapath *mp, struct iomap *iomap)
{
struct metapath clone;
u64 hole_size;
int ret;
clone_metapath(&clone, mp);
ret = gfs2_walk_metadata(inode, &clone, len, gfs2_hole_walker);
if (ret < 0)
goto out;
if (ret == 1)
hole_size = metapath_to_block(GFS2_SB(inode), &clone) - lblock;
else
hole_size = len;
iomap->length = hole_size << inode->i_blkbits;
ret = 0;
out:
release_metapath(&clone);
return ret;
}
static inline void gfs2_indirect_init(struct metapath *mp,
struct gfs2_glock *gl, unsigned int i,
unsigned offset, u64 bn)
{
__be64 *ptr = (__be64 *)(mp->mp_bh[i - 1]->b_data +
((i > 1) ? sizeof(struct gfs2_meta_header) :
sizeof(struct gfs2_dinode)));
BUG_ON(i < 1);
BUG_ON(mp->mp_bh[i] != NULL);
mp->mp_bh[i] = gfs2_meta_new(gl, bn);
gfs2_trans_add_meta(gl, mp->mp_bh[i]);
gfs2_metatype_set(mp->mp_bh[i], GFS2_METATYPE_IN, GFS2_FORMAT_IN);
gfs2_buffer_clear_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header));
ptr += offset;
*ptr = cpu_to_be64(bn);
}
enum alloc_state {
ALLOC_DATA = 0,
ALLOC_GROW_DEPTH = 1,
ALLOC_GROW_HEIGHT = 2,
/* ALLOC_UNSTUFF = 3, TBD and rather complicated */
};
/**
* __gfs2_iomap_alloc - Build a metadata tree of the requested height
* @inode: The GFS2 inode
* @iomap: The iomap structure
* @mp: The metapath, with proper height information calculated
*
* In this routine we may have to alloc:
* i) Indirect blocks to grow the metadata tree height
* ii) Indirect blocks to fill in lower part of the metadata tree
* iii) Data blocks
*
* This function is called after __gfs2_iomap_get, which works out the
* total number of blocks which we need via gfs2_alloc_size.
*
* We then do the actual allocation asking for an extent at a time (if
* enough contiguous free blocks are available, there will only be one
* allocation request per call) and uses the state machine to initialise
* the blocks in order.
*
* Right now, this function will allocate at most one indirect block
* worth of data -- with a default block size of 4K, that's slightly
* less than 2M. If this limitation is ever removed to allow huge
* allocations, we would probably still want to limit the iomap size we
* return to avoid stalling other tasks during huge writes; the next
* iomap iteration would then find the blocks already allocated.
*
* Returns: errno on error
*/
static int __gfs2_iomap_alloc(struct inode *inode, struct iomap *iomap,
struct metapath *mp)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
size_t dblks = iomap->length >> inode->i_blkbits;
const unsigned end_of_metadata = mp->mp_fheight - 1;
int ret;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(mp->mp_aheight < 1);
BUG_ON(dibh == NULL);
BUG_ON(dblks < 1);
gfs2_trans_add_meta(ip->i_gl, dibh);
down_write(&ip->i_rw_mutex);
if (mp->mp_fheight == mp->mp_aheight) {
/* Bottom indirect block exists */
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
if (mp->mp_fheight == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = mp->mp_fheight - mp->mp_aheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = mp->mp_fheight - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (mp->mp_fheight - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = mp->mp_aheight;
do {
n = blks - alloced;
ret = gfs2_alloc_blocks(ip, &bn, &n, 0, NULL);
if (ret)
goto out;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_remove_revoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < mp->mp_fheight - ip->i_height && n > 0;
i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == mp->mp_fheight - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < mp->mp_fheight; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
fallthrough; /* To branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < mp->mp_fheight)
gfs2_trans_add_meta(ip->i_gl, mp->mp_bh[i-1]);
for (; i < mp->mp_fheight && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == mp->mp_fheight)
state = ALLOC_DATA;
if (n == 0)
break;
fallthrough; /* To tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_meta(ip->i_gl, mp->mp_bh[end_of_metadata]);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
iomap->addr = bn << inode->i_blkbits;
iomap->flags |= IOMAP_F_MERGED | IOMAP_F_NEW;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
break;
}
} while (iomap->addr == IOMAP_NULL_ADDR);
iomap->type = IOMAP_MAPPED;
iomap->length = (u64)dblks << inode->i_blkbits;
ip->i_height = mp->mp_fheight;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, dibh->b_data);
out:
up_write(&ip->i_rw_mutex);
return ret;
}
#define IOMAP_F_GFS2_BOUNDARY IOMAP_F_PRIVATE
/**
* gfs2_alloc_size - Compute the maximum allocation size
* @inode: The inode
* @mp: The metapath
* @size: Requested size in blocks
*
* Compute the maximum size of the next allocation at @mp.
*
* Returns: size in blocks
*/
static u64 gfs2_alloc_size(struct inode *inode, struct metapath *mp, u64 size)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
const __be64 *first, *ptr, *end;
/*
* For writes to stuffed files, this function is called twice via
* __gfs2_iomap_get, before and after unstuffing. The size we return the
* first time needs to be large enough to get the reservation and
* allocation sizes right. The size we return the second time must
* be exact or else __gfs2_iomap_alloc won't do the right thing.
*/
if (gfs2_is_stuffed(ip) || mp->mp_fheight != mp->mp_aheight) {
unsigned int maxsize = mp->mp_fheight > 1 ?
sdp->sd_inptrs : sdp->sd_diptrs;
maxsize -= mp->mp_list[mp->mp_fheight - 1];
if (size > maxsize)
size = maxsize;
return size;
}
first = metapointer(ip->i_height - 1, mp);
end = metaend(ip->i_height - 1, mp);
if (end - first > size)
end = first + size;
for (ptr = first; ptr < end; ptr++) {
if (*ptr)
break;
}
return ptr - first;
}
/**
* __gfs2_iomap_get - Map blocks from an inode to disk blocks
* @inode: The inode
* @pos: Starting position in bytes
* @length: Length to map, in bytes
* @flags: iomap flags
* @iomap: The iomap structure
* @mp: The metapath
*
* Returns: errno
*/
static int __gfs2_iomap_get(struct inode *inode, loff_t pos, loff_t length,
unsigned flags, struct iomap *iomap,
struct metapath *mp)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
loff_t size = i_size_read(inode);
__be64 *ptr;
sector_t lblock;
sector_t lblock_stop;
int ret;
int eob;
u64 len;
struct buffer_head *dibh = NULL, *bh;
u8 height;
if (!length)
return -EINVAL;
down_read(&ip->i_rw_mutex);
ret = gfs2_meta_inode_buffer(ip, &dibh);
if (ret)
goto unlock;
mp->mp_bh[0] = dibh;
if (gfs2_is_stuffed(ip)) {
if (flags & IOMAP_WRITE) {
loff_t max_size = gfs2_max_stuffed_size(ip);
if (pos + length > max_size)
goto unstuff;
iomap->length = max_size;
} else {
if (pos >= size) {
if (flags & IOMAP_REPORT) {
ret = -ENOENT;
goto unlock;
} else {
iomap->offset = pos;
iomap->length = length;
goto hole_found;
}
}
iomap->length = size;
}
iomap->addr = (ip->i_no_addr << inode->i_blkbits) +
sizeof(struct gfs2_dinode);
iomap->type = IOMAP_INLINE;
iomap->inline_data = dibh->b_data + sizeof(struct gfs2_dinode);
goto out;
}
unstuff:
lblock = pos >> inode->i_blkbits;
iomap->offset = lblock << inode->i_blkbits;
lblock_stop = (pos + length - 1) >> inode->i_blkbits;
len = lblock_stop - lblock + 1;
iomap->length = len << inode->i_blkbits;
height = ip->i_height;
while ((lblock + 1) * sdp->sd_sb.sb_bsize > sdp->sd_heightsize[height])
height++;
find_metapath(sdp, lblock, mp, height);
if (height > ip->i_height || gfs2_is_stuffed(ip))
goto do_alloc;
ret = lookup_metapath(ip, mp);
if (ret)
goto unlock;
if (mp->mp_aheight != ip->i_height)
goto do_alloc;
ptr = metapointer(ip->i_height - 1, mp);
if (*ptr == 0)
goto do_alloc;
bh = mp->mp_bh[ip->i_height - 1];
len = gfs2_extent_length(bh, ptr, len, &eob);
iomap->addr = be64_to_cpu(*ptr) << inode->i_blkbits;
iomap->length = len << inode->i_blkbits;
iomap->type = IOMAP_MAPPED;
iomap->flags |= IOMAP_F_MERGED;
if (eob)
iomap->flags |= IOMAP_F_GFS2_BOUNDARY;
out:
iomap->bdev = inode->i_sb->s_bdev;
unlock:
up_read(&ip->i_rw_mutex);
return ret;
do_alloc:
if (flags & IOMAP_REPORT) {
if (pos >= size)
ret = -ENOENT;
else if (height == ip->i_height)
ret = gfs2_hole_size(inode, lblock, len, mp, iomap);
else
iomap->length = size - iomap->offset;
} else if (flags & IOMAP_WRITE) {
u64 alloc_size;
if (flags & IOMAP_DIRECT)
goto out; /* (see gfs2_file_direct_write) */
len = gfs2_alloc_size(inode, mp, len);
alloc_size = len << inode->i_blkbits;
if (alloc_size < iomap->length)
iomap->length = alloc_size;
} else {
if (pos < size && height == ip->i_height)
ret = gfs2_hole_size(inode, lblock, len, mp, iomap);
}
hole_found:
iomap->addr = IOMAP_NULL_ADDR;
iomap->type = IOMAP_HOLE;
goto out;
}
static struct folio *
gfs2_iomap_get_folio(struct iomap_iter *iter, loff_t pos, unsigned len)
{
struct inode *inode = iter->inode;
unsigned int blockmask = i_blocksize(inode) - 1;
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned int blocks;
struct folio *folio;
int status;
blocks = ((pos & blockmask) + len + blockmask) >> inode->i_blkbits;
status = gfs2_trans_begin(sdp, RES_DINODE + blocks, 0);
if (status)
return ERR_PTR(status);
folio = iomap_get_folio(iter, pos, len);
if (IS_ERR(folio))
gfs2_trans_end(sdp);
return folio;
}
static void gfs2_iomap_put_folio(struct inode *inode, loff_t pos,
unsigned copied, struct folio *folio)
{
struct gfs2_trans *tr = current->journal_info;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
if (!gfs2_is_stuffed(ip))
gfs2_trans_add_databufs(ip, folio, offset_in_folio(folio, pos),
copied);
folio_unlock(folio);
folio_put(folio);
if (tr->tr_num_buf_new)
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
gfs2_trans_end(sdp);
}
static const struct iomap_folio_ops gfs2_iomap_folio_ops = {
.get_folio = gfs2_iomap_get_folio,
.put_folio = gfs2_iomap_put_folio,
};
static int gfs2_iomap_begin_write(struct inode *inode, loff_t pos,
loff_t length, unsigned flags,
struct iomap *iomap,
struct metapath *mp)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
bool unstuff;
int ret;
unstuff = gfs2_is_stuffed(ip) &&
pos + length > gfs2_max_stuffed_size(ip);
if (unstuff || iomap->type == IOMAP_HOLE) {
unsigned int data_blocks, ind_blocks;
struct gfs2_alloc_parms ap = {};
unsigned int rblocks;
struct gfs2_trans *tr;
gfs2_write_calc_reserv(ip, iomap->length, &data_blocks,
&ind_blocks);
ap.target = data_blocks + ind_blocks;
ret = gfs2_quota_lock_check(ip, &ap);
if (ret)
return ret;
ret = gfs2_inplace_reserve(ip, &ap);
if (ret)
goto out_qunlock;
rblocks = RES_DINODE + ind_blocks;
if (gfs2_is_jdata(ip))
rblocks += data_blocks;
if (ind_blocks || data_blocks)
rblocks += RES_STATFS + RES_QUOTA;
if (inode == sdp->sd_rindex)
rblocks += 2 * RES_STATFS;
rblocks += gfs2_rg_blocks(ip, data_blocks + ind_blocks);
ret = gfs2_trans_begin(sdp, rblocks,
iomap->length >> inode->i_blkbits);
if (ret)
goto out_trans_fail;
if (unstuff) {
ret = gfs2_unstuff_dinode(ip);
if (ret)
goto out_trans_end;
release_metapath(mp);
ret = __gfs2_iomap_get(inode, iomap->offset,
iomap->length, flags, iomap, mp);
if (ret)
goto out_trans_end;
}
if (iomap->type == IOMAP_HOLE) {
ret = __gfs2_iomap_alloc(inode, iomap, mp);
if (ret) {
gfs2_trans_end(sdp);
gfs2_inplace_release(ip);
punch_hole(ip, iomap->offset, iomap->length);
goto out_qunlock;
}
}
tr = current->journal_info;
if (tr->tr_num_buf_new)
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
gfs2_trans_end(sdp);
}
if (gfs2_is_stuffed(ip) || gfs2_is_jdata(ip))
iomap->folio_ops = &gfs2_iomap_folio_ops;
return 0;
out_trans_end:
gfs2_trans_end(sdp);
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
return ret;
}
static int gfs2_iomap_begin(struct inode *inode, loff_t pos, loff_t length,
unsigned flags, struct iomap *iomap,
struct iomap *srcmap)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct metapath mp = { .mp_aheight = 1, };
int ret;
if (gfs2_is_jdata(ip))
iomap->flags |= IOMAP_F_BUFFER_HEAD;
trace_gfs2_iomap_start(ip, pos, length, flags);
ret = __gfs2_iomap_get(inode, pos, length, flags, iomap, &mp);
if (ret)
goto out_unlock;
switch(flags & (IOMAP_WRITE | IOMAP_ZERO)) {
case IOMAP_WRITE:
if (flags & IOMAP_DIRECT) {
/*
* Silently fall back to buffered I/O for stuffed files
* or if we've got a hole (see gfs2_file_direct_write).
*/
if (iomap->type != IOMAP_MAPPED)
ret = -ENOTBLK;
goto out_unlock;
}
break;
case IOMAP_ZERO:
if (iomap->type == IOMAP_HOLE)
goto out_unlock;
break;
default:
goto out_unlock;
}
ret = gfs2_iomap_begin_write(inode, pos, length, flags, iomap, &mp);
out_unlock:
release_metapath(&mp);
trace_gfs2_iomap_end(ip, iomap, ret);
return ret;
}
static int gfs2_iomap_end(struct inode *inode, loff_t pos, loff_t length,
ssize_t written, unsigned flags, struct iomap *iomap)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
switch (flags & (IOMAP_WRITE | IOMAP_ZERO)) {
case IOMAP_WRITE:
if (flags & IOMAP_DIRECT)
return 0;
break;
case IOMAP_ZERO:
if (iomap->type == IOMAP_HOLE)
return 0;
break;
default:
return 0;
}
if (!gfs2_is_stuffed(ip))
gfs2_ordered_add_inode(ip);
if (inode == sdp->sd_rindex)
adjust_fs_space(inode);
gfs2_inplace_release(ip);
if (ip->i_qadata && ip->i_qadata->qa_qd_num)
gfs2_quota_unlock(ip);
if (length != written && (iomap->flags & IOMAP_F_NEW)) {
/* Deallocate blocks that were just allocated. */
loff_t hstart = round_up(pos + written, i_blocksize(inode));
loff_t hend = iomap->offset + iomap->length;
if (hstart < hend) {
truncate_pagecache_range(inode, hstart, hend - 1);
punch_hole(ip, hstart, hend - hstart);
}
}
if (unlikely(!written))
return 0;
if (iomap->flags & IOMAP_F_SIZE_CHANGED)
mark_inode_dirty(inode);
set_bit(GLF_DIRTY, &ip->i_gl->gl_flags);
return 0;
}
const struct iomap_ops gfs2_iomap_ops = {
.iomap_begin = gfs2_iomap_begin,
.iomap_end = gfs2_iomap_end,
};
/**
* gfs2_block_map - Map one or more blocks of an inode to a disk block
* @inode: The inode
* @lblock: The logical block number
* @bh_map: The bh to be mapped
* @create: True if its ok to alloc blocks to satify the request
*
* The size of the requested mapping is defined in bh_map->b_size.
*
* Clears buffer_mapped(bh_map) and leaves bh_map->b_size unchanged
* when @lblock is not mapped. Sets buffer_mapped(bh_map) and
* bh_map->b_size to indicate the size of the mapping when @lblock and
* successive blocks are mapped, up to the requested size.
*
* Sets buffer_boundary() if a read of metadata will be required
* before the next block can be mapped. Sets buffer_new() if new
* blocks were allocated.
*
* Returns: errno
*/
int gfs2_block_map(struct inode *inode, sector_t lblock,
struct buffer_head *bh_map, int create)
{
struct gfs2_inode *ip = GFS2_I(inode);
loff_t pos = (loff_t)lblock << inode->i_blkbits;
loff_t length = bh_map->b_size;
struct iomap iomap = { };
int ret;
clear_buffer_mapped(bh_map);
clear_buffer_new(bh_map);
clear_buffer_boundary(bh_map);
trace_gfs2_bmap(ip, bh_map, lblock, create, 1);
if (!create)
ret = gfs2_iomap_get(inode, pos, length, &iomap);
else
ret = gfs2_iomap_alloc(inode, pos, length, &iomap);
if (ret)
goto out;
if (iomap.length > bh_map->b_size) {
iomap.length = bh_map->b_size;
iomap.flags &= ~IOMAP_F_GFS2_BOUNDARY;
}
if (iomap.addr != IOMAP_NULL_ADDR)
map_bh(bh_map, inode->i_sb, iomap.addr >> inode->i_blkbits);
bh_map->b_size = iomap.length;
if (iomap.flags & IOMAP_F_GFS2_BOUNDARY)
set_buffer_boundary(bh_map);
if (iomap.flags & IOMAP_F_NEW)
set_buffer_new(bh_map);
out:
trace_gfs2_bmap(ip, bh_map, lblock, create, ret);
return ret;
}
int gfs2_get_extent(struct inode *inode, u64 lblock, u64 *dblock,
unsigned int *extlen)
{
unsigned int blkbits = inode->i_blkbits;
struct iomap iomap = { };
unsigned int len;
int ret;
ret = gfs2_iomap_get(inode, lblock << blkbits, *extlen << blkbits,
&iomap);
if (ret)
return ret;
if (iomap.type != IOMAP_MAPPED)
return -EIO;
*dblock = iomap.addr >> blkbits;
len = iomap.length >> blkbits;
if (len < *extlen)
*extlen = len;
return 0;
}
int gfs2_alloc_extent(struct inode *inode, u64 lblock, u64 *dblock,
unsigned int *extlen, bool *new)
{
unsigned int blkbits = inode->i_blkbits;
struct iomap iomap = { };
unsigned int len;
int ret;
ret = gfs2_iomap_alloc(inode, lblock << blkbits, *extlen << blkbits,
&iomap);
if (ret)
return ret;
if (iomap.type != IOMAP_MAPPED)
return -EIO;
*dblock = iomap.addr >> blkbits;
len = iomap.length >> blkbits;
if (len < *extlen)
*extlen = len;
*new = iomap.flags & IOMAP_F_NEW;
return 0;
}
/*
* NOTE: Never call gfs2_block_zero_range with an open transaction because it
* uses iomap write to perform its actions, which begin their own transactions
* (iomap_begin, get_folio, etc.)
*/
static int gfs2_block_zero_range(struct inode *inode, loff_t from,
unsigned int length)
{
BUG_ON(current->journal_info);
return iomap_zero_range(inode, from, length, NULL, &gfs2_iomap_ops);
}
#define GFS2_JTRUNC_REVOKES 8192
/**
* gfs2_journaled_truncate - Wrapper for truncate_pagecache for jdata files
* @inode: The inode being truncated
* @oldsize: The original (larger) size
* @newsize: The new smaller size
*
* With jdata files, we have to journal a revoke for each block which is
* truncated. As a result, we need to split this into separate transactions
* if the number of pages being truncated gets too large.
*/
static int gfs2_journaled_truncate(struct inode *inode, u64 oldsize, u64 newsize)
{
struct gfs2_sbd *sdp = GFS2_SB(inode);
u64 max_chunk = GFS2_JTRUNC_REVOKES * sdp->sd_vfs->s_blocksize;
u64 chunk;
int error;
while (oldsize != newsize) {
struct gfs2_trans *tr;
unsigned int offs;
chunk = oldsize - newsize;
if (chunk > max_chunk)
chunk = max_chunk;
offs = oldsize & ~PAGE_MASK;
if (offs && chunk > PAGE_SIZE)
chunk = offs + ((chunk - offs) & PAGE_MASK);
truncate_pagecache(inode, oldsize - chunk);
oldsize -= chunk;
tr = current->journal_info;
if (!test_bit(TR_TOUCHED, &tr->tr_flags))
continue;
gfs2_trans_end(sdp);
error = gfs2_trans_begin(sdp, RES_DINODE, GFS2_JTRUNC_REVOKES);
if (error)
return error;
}
return 0;
}
static int trunc_start(struct inode *inode, u64 newsize)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = NULL;
int journaled = gfs2_is_jdata(ip);
u64 oldsize = inode->i_size;
int error;
if (!gfs2_is_stuffed(ip)) {
unsigned int blocksize = i_blocksize(inode);
unsigned int offs = newsize & (blocksize - 1);
if (offs) {
error = gfs2_block_zero_range(inode, newsize,
blocksize - offs);
if (error)
return error;
}
}
if (journaled)
error = gfs2_trans_begin(sdp, RES_DINODE + RES_JDATA, GFS2_JTRUNC_REVOKES);
else
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
return error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out;
gfs2_trans_add_meta(ip->i_gl, dibh);
if (gfs2_is_stuffed(ip))
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + newsize);
else
ip->i_diskflags |= GFS2_DIF_TRUNC_IN_PROG;
i_size_write(inode, newsize);
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_dinode_out(ip, dibh->b_data);
if (journaled)
error = gfs2_journaled_truncate(inode, oldsize, newsize);
else
truncate_pagecache(inode, newsize);
out:
brelse(dibh);
if (current->journal_info)
gfs2_trans_end(sdp);
return error;
}
int gfs2_iomap_get(struct inode *inode, loff_t pos, loff_t length,
struct iomap *iomap)
{
struct metapath mp = { .mp_aheight = 1, };
int ret;
ret = __gfs2_iomap_get(inode, pos, length, 0, iomap, &mp);
release_metapath(&mp);
return ret;
}
int gfs2_iomap_alloc(struct inode *inode, loff_t pos, loff_t length,
struct iomap *iomap)
{
struct metapath mp = { .mp_aheight = 1, };
int ret;
ret = __gfs2_iomap_get(inode, pos, length, IOMAP_WRITE, iomap, &mp);
if (!ret && iomap->type == IOMAP_HOLE)
ret = __gfs2_iomap_alloc(inode, iomap, &mp);
release_metapath(&mp);
return ret;
}
/**
* sweep_bh_for_rgrps - find an rgrp in a meta buffer and free blocks therein
* @ip: inode
* @rd_gh: holder of resource group glock
* @bh: buffer head to sweep
* @start: starting point in bh
* @end: end point in bh
* @meta: true if bh points to metadata (rather than data)
* @btotal: place to keep count of total blocks freed
*
* We sweep a metadata buffer (provided by the metapath) for blocks we need to
* free, and free them all. However, we do it one rgrp at a time. If this
* block has references to multiple rgrps, we break it into individual
* transactions. This allows other processes to use the rgrps while we're
* focused on a single one, for better concurrency / performance.
* At every transaction boundary, we rewrite the inode into the journal.
* That way the bitmaps are kept consistent with the inode and we can recover
* if we're interrupted by power-outages.
*
* Returns: 0, or return code if an error occurred.
* *btotal has the total number of blocks freed
*/
static int sweep_bh_for_rgrps(struct gfs2_inode *ip, struct gfs2_holder *rd_gh,
struct buffer_head *bh, __be64 *start, __be64 *end,
bool meta, u32 *btotal)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *rgd;
struct gfs2_trans *tr;
__be64 *p;
int blks_outside_rgrp;
u64 bn, bstart, isize_blks;
s64 blen; /* needs to be s64 or gfs2_add_inode_blocks breaks */
int ret = 0;
bool buf_in_tr = false; /* buffer was added to transaction */
more_rgrps:
rgd = NULL;
if (gfs2_holder_initialized(rd_gh)) {
rgd = gfs2_glock2rgrp(rd_gh->gh_gl);
gfs2_assert_withdraw(sdp,
gfs2_glock_is_locked_by_me(rd_gh->gh_gl));
}
blks_outside_rgrp = 0;
bstart = 0;
blen = 0;
for (p = start; p < end; p++) {
if (!*p)
continue;
bn = be64_to_cpu(*p);
if (rgd) {
if (!rgrp_contains_block(rgd, bn)) {
blks_outside_rgrp++;
continue;
}
} else {
rgd = gfs2_blk2rgrpd(sdp, bn, true);
if (unlikely(!rgd)) {
ret = -EIO;
goto out;
}
ret = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, rd_gh);
if (ret)
goto out;
/* Must be done with the rgrp glock held: */
if (gfs2_rs_active(&ip->i_res) &&
rgd == ip->i_res.rs_rgd)
gfs2_rs_deltree(&ip->i_res);
}
/* The size of our transactions will be unknown until we
actually process all the metadata blocks that relate to
the rgrp. So we estimate. We know it can't be more than
the dinode's i_blocks and we don't want to exceed the
journal flush threshold, sd_log_thresh2. */
if (current->journal_info == NULL) {
unsigned int jblocks_rqsted, revokes;
jblocks_rqsted = rgd->rd_length + RES_DINODE +
RES_INDIRECT;
isize_blks = gfs2_get_inode_blocks(&ip->i_inode);
if (isize_blks > atomic_read(&sdp->sd_log_thresh2))
jblocks_rqsted +=
atomic_read(&sdp->sd_log_thresh2);
else
jblocks_rqsted += isize_blks;
revokes = jblocks_rqsted;
if (meta)
revokes += end - start;
else if (ip->i_depth)
revokes += sdp->sd_inptrs;
ret = gfs2_trans_begin(sdp, jblocks_rqsted, revokes);
if (ret)
goto out_unlock;
down_write(&ip->i_rw_mutex);
}
/* check if we will exceed the transaction blocks requested */
tr = current->journal_info;
if (tr->tr_num_buf_new + RES_STATFS +
RES_QUOTA >= atomic_read(&sdp->sd_log_thresh2)) {
/* We set blks_outside_rgrp to ensure the loop will
be repeated for the same rgrp, but with a new
transaction. */
blks_outside_rgrp++;
/* This next part is tricky. If the buffer was added
to the transaction, we've already set some block
pointers to 0, so we better follow through and free
them, or we will introduce corruption (so break).
This may be impossible, or at least rare, but I
decided to cover the case regardless.
If the buffer was not added to the transaction
(this call), doing so would exceed our transaction
size, so we need to end the transaction and start a
new one (so goto). */
if (buf_in_tr)
break;
goto out_unlock;
}
gfs2_trans_add_meta(ip->i_gl, bh);
buf_in_tr = true;
*p = 0;
if (bstart + blen == bn) {
blen++;
continue;
}
if (bstart) {
__gfs2_free_blocks(ip, rgd, bstart, (u32)blen, meta);
(*btotal) += blen;
gfs2_add_inode_blocks(&ip->i_inode, -blen);
}
bstart = bn;
blen = 1;
}
if (bstart) {
__gfs2_free_blocks(ip, rgd, bstart, (u32)blen, meta);
(*btotal) += blen;
gfs2_add_inode_blocks(&ip->i_inode, -blen);
}
out_unlock:
if (!ret && blks_outside_rgrp) { /* If buffer still has non-zero blocks
outside the rgrp we just processed,
do it all over again. */
if (current->journal_info) {
struct buffer_head *dibh;
ret = gfs2_meta_inode_buffer(ip, &dibh);
if (ret)
goto out;
/* Every transaction boundary, we rewrite the dinode
to keep its di_blocks current in case of failure. */
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
buf_in_tr = false;
}
gfs2_glock_dq_uninit(rd_gh);
cond_resched();
goto more_rgrps;
}
out:
return ret;
}
static bool mp_eq_to_hgt(struct metapath *mp, __u16 *list, unsigned int h)
{
if (memcmp(mp->mp_list, list, h * sizeof(mp->mp_list[0])))
return false;
return true;
}
/**
* find_nonnull_ptr - find a non-null pointer given a metapath and height
* @sdp: The superblock
* @mp: starting metapath
* @h: desired height to search
* @end_list: See punch_hole().
* @end_aligned: See punch_hole().
*
* Assumes the metapath is valid (with buffers) out to height h.
* Returns: true if a non-null pointer was found in the metapath buffer
* false if all remaining pointers are NULL in the buffer
*/
static bool find_nonnull_ptr(struct gfs2_sbd *sdp, struct metapath *mp,
unsigned int h,
__u16 *end_list, unsigned int end_aligned)
{
struct buffer_head *bh = mp->mp_bh[h];
__be64 *first, *ptr, *end;
first = metaptr1(h, mp);
ptr = first + mp->mp_list[h];
end = (__be64 *)(bh->b_data + bh->b_size);
if (end_list && mp_eq_to_hgt(mp, end_list, h)) {
bool keep_end = h < end_aligned;
end = first + end_list[h] + keep_end;
}
while (ptr < end) {
if (*ptr) { /* if we have a non-null pointer */
mp->mp_list[h] = ptr - first;
h++;
if (h < GFS2_MAX_META_HEIGHT)
mp->mp_list[h] = 0;
return true;
}
ptr++;
}
return false;
}
enum dealloc_states {
DEALLOC_MP_FULL = 0, /* Strip a metapath with all buffers read in */
DEALLOC_MP_LOWER = 1, /* lower the metapath strip height */
DEALLOC_FILL_MP = 2, /* Fill in the metapath to the given height. */
DEALLOC_DONE = 3, /* process complete */
};
static inline void
metapointer_range(struct metapath *mp, int height,
__u16 *start_list, unsigned int start_aligned,
__u16 *end_list, unsigned int end_aligned,
__be64 **start, __be64 **end)
{
struct buffer_head *bh = mp->mp_bh[height];
__be64 *first;
first = metaptr1(height, mp);
*start = first;
if (mp_eq_to_hgt(mp, start_list, height)) {
bool keep_start = height < start_aligned;
*start = first + start_list[height] + keep_start;
}
*end = (__be64 *)(bh->b_data + bh->b_size);
if (end_list && mp_eq_to_hgt(mp, end_list, height)) {
bool keep_end = height < end_aligned;
*end = first + end_list[height] + keep_end;
}
}
static inline bool walk_done(struct gfs2_sbd *sdp,
struct metapath *mp, int height,
__u16 *end_list, unsigned int end_aligned)
{
__u16 end;
if (end_list) {
bool keep_end = height < end_aligned;
if (!mp_eq_to_hgt(mp, end_list, height))
return false;
end = end_list[height] + keep_end;
} else
end = (height > 0) ? sdp->sd_inptrs : sdp->sd_diptrs;
return mp->mp_list[height] >= end;
}
/**
* punch_hole - deallocate blocks in a file
* @ip: inode to truncate
* @offset: the start of the hole
* @length: the size of the hole (or 0 for truncate)
*
* Punch a hole into a file or truncate a file at a given position. This
* function operates in whole blocks (@offset and @length are rounded
* accordingly); partially filled blocks must be cleared otherwise.
*
* This function works from the bottom up, and from the right to the left. In
* other words, it strips off the highest layer (data) before stripping any of
* the metadata. Doing it this way is best in case the operation is interrupted
* by power failure, etc. The dinode is rewritten in every transaction to
* guarantee integrity.
*/
static int punch_hole(struct gfs2_inode *ip, u64 offset, u64 length)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
u64 maxsize = sdp->sd_heightsize[ip->i_height];
struct metapath mp = {};
struct buffer_head *dibh, *bh;
struct gfs2_holder rd_gh;
unsigned int bsize_shift = sdp->sd_sb.sb_bsize_shift;
u64 lblock = (offset + (1 << bsize_shift) - 1) >> bsize_shift;
__u16 start_list[GFS2_MAX_META_HEIGHT];
__u16 __end_list[GFS2_MAX_META_HEIGHT], *end_list = NULL;
unsigned int start_aligned, end_aligned;
unsigned int strip_h = ip->i_height - 1;
u32 btotal = 0;
int ret, state;
int mp_h; /* metapath buffers are read in to this height */
u64 prev_bnr = 0;
__be64 *start, *end;
if (offset >= maxsize) {
/*
* The starting point lies beyond the allocated metadata;
* there are no blocks to deallocate.
*/
return 0;
}
/*
* The start position of the hole is defined by lblock, start_list, and
* start_aligned. The end position of the hole is defined by lend,
* end_list, and end_aligned.
*
* start_aligned and end_aligned define down to which height the start
* and end positions are aligned to the metadata tree (i.e., the
* position is a multiple of the metadata granularity at the height
* above). This determines at which heights additional meta pointers
* needs to be preserved for the remaining data.
*/
if (length) {
u64 end_offset = offset + length;
u64 lend;
/*
* Clip the end at the maximum file size for the given height:
* that's how far the metadata goes; files bigger than that
* will have additional layers of indirection.
*/
if (end_offset > maxsize)
end_offset = maxsize;
lend = end_offset >> bsize_shift;
if (lblock >= lend)
return 0;
find_metapath(sdp, lend, &mp, ip->i_height);
end_list = __end_list;
memcpy(end_list, mp.mp_list, sizeof(mp.mp_list));
for (mp_h = ip->i_height - 1; mp_h > 0; mp_h--) {
if (end_list[mp_h])
break;
}
end_aligned = mp_h;
}
find_metapath(sdp, lblock, &mp, ip->i_height);
memcpy(start_list, mp.mp_list, sizeof(start_list));
for (mp_h = ip->i_height - 1; mp_h > 0; mp_h--) {
if (start_list[mp_h])
break;
}
start_aligned = mp_h;
ret = gfs2_meta_inode_buffer(ip, &dibh);
if (ret)
return ret;
mp.mp_bh[0] = dibh;
ret = lookup_metapath(ip, &mp);
if (ret)
goto out_metapath;
/* issue read-ahead on metadata */
for (mp_h = 0; mp_h < mp.mp_aheight - 1; mp_h++) {
metapointer_range(&mp, mp_h, start_list, start_aligned,
end_list, end_aligned, &start, &end);
gfs2_metapath_ra(ip->i_gl, start, end);
}
if (mp.mp_aheight == ip->i_height)
state = DEALLOC_MP_FULL; /* We have a complete metapath */
else
state = DEALLOC_FILL_MP; /* deal with partial metapath */
ret = gfs2_rindex_update(sdp);
if (ret)
goto out_metapath;
ret = gfs2_quota_hold(ip, NO_UID_QUOTA_CHANGE, NO_GID_QUOTA_CHANGE);
if (ret)
goto out_metapath;
gfs2_holder_mark_uninitialized(&rd_gh);
mp_h = strip_h;
while (state != DEALLOC_DONE) {
switch (state) {
/* Truncate a full metapath at the given strip height.
* Note that strip_h == mp_h in order to be in this state. */
case DEALLOC_MP_FULL:
bh = mp.mp_bh[mp_h];
gfs2_assert_withdraw(sdp, bh);
if (gfs2_assert_withdraw(sdp,
prev_bnr != bh->b_blocknr)) {
fs_emerg(sdp, "inode %llu, block:%llu, i_h:%u,"
"s_h:%u, mp_h:%u\n",
(unsigned long long)ip->i_no_addr,
prev_bnr, ip->i_height, strip_h, mp_h);
}
prev_bnr = bh->b_blocknr;
if (gfs2_metatype_check(sdp, bh,
(mp_h ? GFS2_METATYPE_IN :
GFS2_METATYPE_DI))) {
ret = -EIO;
goto out;
}
/*
* Below, passing end_aligned as 0 gives us the
* metapointer range excluding the end point: the end
* point is the first metapath we must not deallocate!
*/
metapointer_range(&mp, mp_h, start_list, start_aligned,
end_list, 0 /* end_aligned */,
&start, &end);
ret = sweep_bh_for_rgrps(ip, &rd_gh, mp.mp_bh[mp_h],
start, end,
mp_h != ip->i_height - 1,
&btotal);
/* If we hit an error or just swept dinode buffer,
just exit. */
if (ret || !mp_h) {
state = DEALLOC_DONE;
break;
}
state = DEALLOC_MP_LOWER;
break;
/* lower the metapath strip height */
case DEALLOC_MP_LOWER:
/* We're done with the current buffer, so release it,
unless it's the dinode buffer. Then back up to the
previous pointer. */
if (mp_h) {
brelse(mp.mp_bh[mp_h]);
mp.mp_bh[mp_h] = NULL;
}
/* If we can't get any lower in height, we've stripped
off all we can. Next step is to back up and start
stripping the previous level of metadata. */
if (mp_h == 0) {
strip_h--;
memcpy(mp.mp_list, start_list, sizeof(start_list));
mp_h = strip_h;
state = DEALLOC_FILL_MP;
break;
}
mp.mp_list[mp_h] = 0;
mp_h--; /* search one metadata height down */
mp.mp_list[mp_h]++;
if (walk_done(sdp, &mp, mp_h, end_list, end_aligned))
break;
/* Here we've found a part of the metapath that is not
* allocated. We need to search at that height for the
* next non-null pointer. */
if (find_nonnull_ptr(sdp, &mp, mp_h, end_list, end_aligned)) {
state = DEALLOC_FILL_MP;
mp_h++;
}
/* No more non-null pointers at this height. Back up
to the previous height and try again. */
break; /* loop around in the same state */
/* Fill the metapath with buffers to the given height. */
case DEALLOC_FILL_MP:
/* Fill the buffers out to the current height. */
ret = fillup_metapath(ip, &mp, mp_h);
if (ret < 0)
goto out;
/* On the first pass, issue read-ahead on metadata. */
if (mp.mp_aheight > 1 && strip_h == ip->i_height - 1) {
unsigned int height = mp.mp_aheight - 1;
/* No read-ahead for data blocks. */
if (mp.mp_aheight - 1 == strip_h)
height--;
for (; height >= mp.mp_aheight - ret; height--) {
metapointer_range(&mp, height,
start_list, start_aligned,
end_list, end_aligned,
&start, &end);
gfs2_metapath_ra(ip->i_gl, start, end);
}
}
/* If buffers found for the entire strip height */
if (mp.mp_aheight - 1 == strip_h) {
state = DEALLOC_MP_FULL;
break;
}
if (mp.mp_aheight < ip->i_height) /* We have a partial height */
mp_h = mp.mp_aheight - 1;
/* If we find a non-null block pointer, crawl a bit
higher up in the metapath and try again, otherwise
we need to look lower for a new starting point. */
if (find_nonnull_ptr(sdp, &mp, mp_h, end_list, end_aligned))
mp_h++;
else
state = DEALLOC_MP_LOWER;
break;
}
}
if (btotal) {
if (current->journal_info == NULL) {
ret = gfs2_trans_begin(sdp, RES_DINODE + RES_STATFS +
RES_QUOTA, 0);
if (ret)
goto out;
down_write(&ip->i_rw_mutex);
}
gfs2_statfs_change(sdp, 0, +btotal, 0);
gfs2_quota_change(ip, -(s64)btotal, ip->i_inode.i_uid,
ip->i_inode.i_gid);
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
}
out:
if (gfs2_holder_initialized(&rd_gh))
gfs2_glock_dq_uninit(&rd_gh);
if (current->journal_info) {
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
cond_resched();
}
gfs2_quota_unhold(ip);
out_metapath:
release_metapath(&mp);
return ret;
}
static int trunc_end(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *dibh;
int error;
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
return error;
down_write(&ip->i_rw_mutex);
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto out;
if (!i_size_read(&ip->i_inode)) {
ip->i_height = 0;
ip->i_goal = ip->i_no_addr;
gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
gfs2_ordered_del_inode(ip);
}
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
ip->i_diskflags &= ~GFS2_DIF_TRUNC_IN_PROG;
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
out:
up_write(&ip->i_rw_mutex);
gfs2_trans_end(sdp);
return error;
}
/**
* do_shrink - make a file smaller
* @inode: the inode
* @newsize: the size to make the file
*
* Called with an exclusive lock on @inode. The @size must
* be equal to or smaller than the current inode size.
*
* Returns: errno
*/
static int do_shrink(struct inode *inode, u64 newsize)
{
struct gfs2_inode *ip = GFS2_I(inode);
int error;
error = trunc_start(inode, newsize);
if (error < 0)
return error;
if (gfs2_is_stuffed(ip))
return 0;
error = punch_hole(ip, newsize, 0);
if (error == 0)
error = trunc_end(ip);
return error;
}
/**
* do_grow - Touch and update inode size
* @inode: The inode
* @size: The new size
*
* This function updates the timestamps on the inode and
* may also increase the size of the inode. This function
* must not be called with @size any smaller than the current
* inode size.
*
* Although it is not strictly required to unstuff files here,
* earlier versions of GFS2 have a bug in the stuffed file reading
* code which will result in a buffer overrun if the size is larger
* than the max stuffed file size. In order to prevent this from
* occurring, such files are unstuffed, but in other cases we can
* just update the inode size directly.
*
* Returns: 0 on success, or -ve on error
*/
static int do_grow(struct inode *inode, u64 size)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_alloc_parms ap = { .target = 1, };
struct buffer_head *dibh;
int error;
int unstuff = 0;
if (gfs2_is_stuffed(ip) && size > gfs2_max_stuffed_size(ip)) {
error = gfs2_quota_lock_check(ip, &ap);
if (error)
return error;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto do_grow_qunlock;
unstuff = 1;
}
error = gfs2_trans_begin(sdp, RES_DINODE + RES_STATFS + RES_RG_BIT +
(unstuff &&
gfs2_is_jdata(ip) ? RES_JDATA : 0) +
(sdp->sd_args.ar_quota == GFS2_QUOTA_OFF ?
0 : RES_QUOTA), 0);
if (error)
goto do_grow_release;
if (unstuff) {
error = gfs2_unstuff_dinode(ip);
if (error)
goto do_end_trans;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
goto do_end_trans;
truncate_setsize(inode, size);
ip->i_inode.i_mtime = inode_set_ctime_current(&ip->i_inode);
gfs2_trans_add_meta(ip->i_gl, dibh);
gfs2_dinode_out(ip, dibh->b_data);
brelse(dibh);
do_end_trans:
gfs2_trans_end(sdp);
do_grow_release:
if (unstuff) {
gfs2_inplace_release(ip);
do_grow_qunlock:
gfs2_quota_unlock(ip);
}
return error;
}
/**
* gfs2_setattr_size - make a file a given size
* @inode: the inode
* @newsize: the size to make the file
*
* The file size can grow, shrink, or stay the same size. This
* is called holding i_rwsem and an exclusive glock on the inode
* in question.
*
* Returns: errno
*/
int gfs2_setattr_size(struct inode *inode, u64 newsize)
{
struct gfs2_inode *ip = GFS2_I(inode);
int ret;
BUG_ON(!S_ISREG(inode->i_mode));
ret = inode_newsize_ok(inode, newsize);
if (ret)
return ret;
inode_dio_wait(inode);
ret = gfs2_qa_get(ip);
if (ret)
goto out;
if (newsize >= inode->i_size) {
ret = do_grow(inode, newsize);
goto out;
}
ret = do_shrink(inode, newsize);
out:
gfs2_rs_delete(ip);
gfs2_qa_put(ip);
return ret;
}
int gfs2_truncatei_resume(struct gfs2_inode *ip)
{
int error;
error = punch_hole(ip, i_size_read(&ip->i_inode), 0);
if (!error)
error = trunc_end(ip);
return error;
}
int gfs2_file_dealloc(struct gfs2_inode *ip)
{
return punch_hole(ip, 0, 0);
}
/**
* gfs2_free_journal_extents - Free cached journal bmap info
* @jd: The journal
*
*/
void gfs2_free_journal_extents(struct gfs2_jdesc *jd)
{
struct gfs2_journal_extent *jext;
while(!list_empty(&jd->extent_list)) {
jext = list_first_entry(&jd->extent_list, struct gfs2_journal_extent, list);
list_del(&jext->list);
kfree(jext);
}
}
/**
* gfs2_add_jextent - Add or merge a new extent to extent cache
* @jd: The journal descriptor
* @lblock: The logical block at start of new extent
* @dblock: The physical block at start of new extent
* @blocks: Size of extent in fs blocks
*
* Returns: 0 on success or -ENOMEM
*/
static int gfs2_add_jextent(struct gfs2_jdesc *jd, u64 lblock, u64 dblock, u64 blocks)
{
struct gfs2_journal_extent *jext;
if (!list_empty(&jd->extent_list)) {
jext = list_last_entry(&jd->extent_list, struct gfs2_journal_extent, list);
if ((jext->dblock + jext->blocks) == dblock) {
jext->blocks += blocks;
return 0;
}
}
jext = kzalloc(sizeof(struct gfs2_journal_extent), GFP_NOFS);
if (jext == NULL)
return -ENOMEM;
jext->dblock = dblock;
jext->lblock = lblock;
jext->blocks = blocks;
list_add_tail(&jext->list, &jd->extent_list);
jd->nr_extents++;
return 0;
}
/**
* gfs2_map_journal_extents - Cache journal bmap info
* @sdp: The super block
* @jd: The journal to map
*
* Create a reusable "extent" mapping from all logical
* blocks to all physical blocks for the given journal. This will save
* us time when writing journal blocks. Most journals will have only one
* extent that maps all their logical blocks. That's because gfs2.mkfs
* arranges the journal blocks sequentially to maximize performance.
* So the extent would map the first block for the entire file length.
* However, gfs2_jadd can happen while file activity is happening, so
* those journals may not be sequential. Less likely is the case where
* the users created their own journals by mounting the metafs and
* laying it out. But it's still possible. These journals might have
* several extents.
*
* Returns: 0 on success, or error on failure
*/
int gfs2_map_journal_extents(struct gfs2_sbd *sdp, struct gfs2_jdesc *jd)
{
u64 lblock = 0;
u64 lblock_stop;
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct buffer_head bh;
unsigned int shift = sdp->sd_sb.sb_bsize_shift;
u64 size;
int rc;
ktime_t start, end;
start = ktime_get();
lblock_stop = i_size_read(jd->jd_inode) >> shift;
size = (lblock_stop - lblock) << shift;
jd->nr_extents = 0;
WARN_ON(!list_empty(&jd->extent_list));
do {
bh.b_state = 0;
bh.b_blocknr = 0;
bh.b_size = size;
rc = gfs2_block_map(jd->jd_inode, lblock, &bh, 0);
if (rc || !buffer_mapped(&bh))
goto fail;
rc = gfs2_add_jextent(jd, lblock, bh.b_blocknr, bh.b_size >> shift);
if (rc)
goto fail;
size -= bh.b_size;
lblock += (bh.b_size >> ip->i_inode.i_blkbits);
} while(size > 0);
end = ktime_get();
fs_info(sdp, "journal %d mapped with %u extents in %lldms\n", jd->jd_jid,
jd->nr_extents, ktime_ms_delta(end, start));
return 0;
fail:
fs_warn(sdp, "error %d mapping journal %u at offset %llu (extent %u)\n",
rc, jd->jd_jid,
(unsigned long long)(i_size_read(jd->jd_inode) - size),
jd->nr_extents);
fs_warn(sdp, "bmap=%d lblock=%llu block=%llu, state=0x%08lx, size=%llu\n",
rc, (unsigned long long)lblock, (unsigned long long)bh.b_blocknr,
bh.b_state, (unsigned long long)bh.b_size);
gfs2_free_journal_extents(jd);
return rc;
}
/**
* gfs2_write_alloc_required - figure out if a write will require an allocation
* @ip: the file being written to
* @offset: the offset to write to
* @len: the number of bytes being written
*
* Returns: 1 if an alloc is required, 0 otherwise
*/
int gfs2_write_alloc_required(struct gfs2_inode *ip, u64 offset,
unsigned int len)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head bh;
unsigned int shift;
u64 lblock, lblock_stop, size;
u64 end_of_file;
if (!len)
return 0;
if (gfs2_is_stuffed(ip)) {
if (offset + len > gfs2_max_stuffed_size(ip))
return 1;
return 0;
}
shift = sdp->sd_sb.sb_bsize_shift;
BUG_ON(gfs2_is_dir(ip));
end_of_file = (i_size_read(&ip->i_inode) + sdp->sd_sb.sb_bsize - 1) >> shift;
lblock = offset >> shift;
lblock_stop = (offset + len + sdp->sd_sb.sb_bsize - 1) >> shift;
if (lblock_stop > end_of_file && ip != GFS2_I(sdp->sd_rindex))
return 1;
size = (lblock_stop - lblock) << shift;
do {
bh.b_state = 0;
bh.b_size = size;
gfs2_block_map(&ip->i_inode, lblock, &bh, 0);
if (!buffer_mapped(&bh))
return 1;
size -= bh.b_size;
lblock += (bh.b_size >> ip->i_inode.i_blkbits);
} while(size > 0);
return 0;
}
static int stuffed_zero_range(struct inode *inode, loff_t offset, loff_t length)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *dibh;
int error;
if (offset >= inode->i_size)
return 0;
if (offset + length > inode->i_size)
length = inode->i_size - offset;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
gfs2_trans_add_meta(ip->i_gl, dibh);
memset(dibh->b_data + sizeof(struct gfs2_dinode) + offset, 0,
length);
brelse(dibh);
return 0;
}
static int gfs2_journaled_truncate_range(struct inode *inode, loff_t offset,
loff_t length)
{
struct gfs2_sbd *sdp = GFS2_SB(inode);
loff_t max_chunk = GFS2_JTRUNC_REVOKES * sdp->sd_vfs->s_blocksize;
int error;
while (length) {
struct gfs2_trans *tr;
loff_t chunk;
unsigned int offs;
chunk = length;
if (chunk > max_chunk)
chunk = max_chunk;
offs = offset & ~PAGE_MASK;
if (offs && chunk > PAGE_SIZE)
chunk = offs + ((chunk - offs) & PAGE_MASK);
truncate_pagecache_range(inode, offset, chunk);
offset += chunk;
length -= chunk;
tr = current->journal_info;
if (!test_bit(TR_TOUCHED, &tr->tr_flags))
continue;
gfs2_trans_end(sdp);
error = gfs2_trans_begin(sdp, RES_DINODE, GFS2_JTRUNC_REVOKES);
if (error)
return error;
}
return 0;
}
int __gfs2_punch_hole(struct file *file, loff_t offset, loff_t length)
{
struct inode *inode = file_inode(file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned int blocksize = i_blocksize(inode);
loff_t start, end;
int error;
if (!gfs2_is_stuffed(ip)) {
unsigned int start_off, end_len;
start_off = offset & (blocksize - 1);
end_len = (offset + length) & (blocksize - 1);
if (start_off) {
unsigned int len = length;
if (length > blocksize - start_off)
len = blocksize - start_off;
error = gfs2_block_zero_range(inode, offset, len);
if (error)
goto out;
if (start_off + length < blocksize)
end_len = 0;
}
if (end_len) {
error = gfs2_block_zero_range(inode,
offset + length - end_len, end_len);
if (error)
goto out;
}
}
start = round_down(offset, blocksize);
end = round_up(offset + length, blocksize) - 1;
error = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (error)
return error;
if (gfs2_is_jdata(ip))
error = gfs2_trans_begin(sdp, RES_DINODE + 2 * RES_JDATA,
GFS2_JTRUNC_REVOKES);
else
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
return error;
if (gfs2_is_stuffed(ip)) {
error = stuffed_zero_range(inode, offset, length);
if (error)
goto out;
}
if (gfs2_is_jdata(ip)) {
BUG_ON(!current->journal_info);
gfs2_journaled_truncate_range(inode, offset, length);
} else
truncate_pagecache_range(inode, offset, offset + length - 1);
file_update_time(file);
mark_inode_dirty(inode);
if (current->journal_info)
gfs2_trans_end(sdp);
if (!gfs2_is_stuffed(ip))
error = punch_hole(ip, offset, length);
out:
if (current->journal_info)
gfs2_trans_end(sdp);
return error;
}
static int gfs2_map_blocks(struct iomap_writepage_ctx *wpc, struct inode *inode,
loff_t offset)
{
int ret;
if (WARN_ON_ONCE(gfs2_is_stuffed(GFS2_I(inode))))
return -EIO;
if (offset >= wpc->iomap.offset &&
offset < wpc->iomap.offset + wpc->iomap.length)
return 0;
memset(&wpc->iomap, 0, sizeof(wpc->iomap));
ret = gfs2_iomap_get(inode, offset, INT_MAX, &wpc->iomap);
return ret;
}
const struct iomap_writeback_ops gfs2_writeback_ops = {
.map_blocks = gfs2_map_blocks,
};
| linux-master | fs/gfs2/bmap.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/fs.h>
#include <linux/gfs2_ondisk.h>
#include <linux/prefetch.h>
#include <linux/blkdev.h>
#include <linux/rbtree.h>
#include <linux/random.h>
#include "gfs2.h"
#include "incore.h"
#include "glock.h"
#include "glops.h"
#include "lops.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "super.h"
#include "trans.h"
#include "util.h"
#include "log.h"
#include "inode.h"
#include "trace_gfs2.h"
#include "dir.h"
#define BFITNOENT ((u32)~0)
#define NO_BLOCK ((u64)~0)
struct gfs2_rbm {
struct gfs2_rgrpd *rgd;
u32 offset; /* The offset is bitmap relative */
int bii; /* Bitmap index */
};
static inline struct gfs2_bitmap *rbm_bi(const struct gfs2_rbm *rbm)
{
return rbm->rgd->rd_bits + rbm->bii;
}
static inline u64 gfs2_rbm_to_block(const struct gfs2_rbm *rbm)
{
BUG_ON(rbm->offset >= rbm->rgd->rd_data);
return rbm->rgd->rd_data0 + (rbm_bi(rbm)->bi_start * GFS2_NBBY) +
rbm->offset;
}
/*
* These routines are used by the resource group routines (rgrp.c)
* to keep track of block allocation. Each block is represented by two
* bits. So, each byte represents GFS2_NBBY (i.e. 4) blocks.
*
* 0 = Free
* 1 = Used (not metadata)
* 2 = Unlinked (still in use) inode
* 3 = Used (metadata)
*/
struct gfs2_extent {
struct gfs2_rbm rbm;
u32 len;
};
static const char valid_change[16] = {
/* current */
/* n */ 0, 1, 1, 1,
/* e */ 1, 0, 0, 0,
/* w */ 0, 0, 0, 1,
1, 0, 0, 0
};
static int gfs2_rbm_find(struct gfs2_rbm *rbm, u8 state, u32 *minext,
struct gfs2_blkreserv *rs, bool nowrap);
/**
* gfs2_setbit - Set a bit in the bitmaps
* @rbm: The position of the bit to set
* @do_clone: Also set the clone bitmap, if it exists
* @new_state: the new state of the block
*
*/
static inline void gfs2_setbit(const struct gfs2_rbm *rbm, bool do_clone,
unsigned char new_state)
{
unsigned char *byte1, *byte2, *end, cur_state;
struct gfs2_bitmap *bi = rbm_bi(rbm);
unsigned int buflen = bi->bi_bytes;
const unsigned int bit = (rbm->offset % GFS2_NBBY) * GFS2_BIT_SIZE;
byte1 = bi->bi_bh->b_data + bi->bi_offset + (rbm->offset / GFS2_NBBY);
end = bi->bi_bh->b_data + bi->bi_offset + buflen;
BUG_ON(byte1 >= end);
cur_state = (*byte1 >> bit) & GFS2_BIT_MASK;
if (unlikely(!valid_change[new_state * 4 + cur_state])) {
struct gfs2_sbd *sdp = rbm->rgd->rd_sbd;
fs_warn(sdp, "buf_blk = 0x%x old_state=%d, new_state=%d\n",
rbm->offset, cur_state, new_state);
fs_warn(sdp, "rgrp=0x%llx bi_start=0x%x biblk: 0x%llx\n",
(unsigned long long)rbm->rgd->rd_addr, bi->bi_start,
(unsigned long long)bi->bi_bh->b_blocknr);
fs_warn(sdp, "bi_offset=0x%x bi_bytes=0x%x block=0x%llx\n",
bi->bi_offset, bi->bi_bytes,
(unsigned long long)gfs2_rbm_to_block(rbm));
dump_stack();
gfs2_consist_rgrpd(rbm->rgd);
return;
}
*byte1 ^= (cur_state ^ new_state) << bit;
if (do_clone && bi->bi_clone) {
byte2 = bi->bi_clone + bi->bi_offset + (rbm->offset / GFS2_NBBY);
cur_state = (*byte2 >> bit) & GFS2_BIT_MASK;
*byte2 ^= (cur_state ^ new_state) << bit;
}
}
/**
* gfs2_testbit - test a bit in the bitmaps
* @rbm: The bit to test
* @use_clone: If true, test the clone bitmap, not the official bitmap.
*
* Some callers like gfs2_unaligned_extlen need to test the clone bitmaps,
* not the "real" bitmaps, to avoid allocating recently freed blocks.
*
* Returns: The two bit block state of the requested bit
*/
static inline u8 gfs2_testbit(const struct gfs2_rbm *rbm, bool use_clone)
{
struct gfs2_bitmap *bi = rbm_bi(rbm);
const u8 *buffer;
const u8 *byte;
unsigned int bit;
if (use_clone && bi->bi_clone)
buffer = bi->bi_clone;
else
buffer = bi->bi_bh->b_data;
buffer += bi->bi_offset;
byte = buffer + (rbm->offset / GFS2_NBBY);
bit = (rbm->offset % GFS2_NBBY) * GFS2_BIT_SIZE;
return (*byte >> bit) & GFS2_BIT_MASK;
}
/**
* gfs2_bit_search
* @ptr: Pointer to bitmap data
* @mask: Mask to use (normally 0x55555.... but adjusted for search start)
* @state: The state we are searching for
*
* We xor the bitmap data with a patter which is the bitwise opposite
* of what we are looking for, this gives rise to a pattern of ones
* wherever there is a match. Since we have two bits per entry, we
* take this pattern, shift it down by one place and then and it with
* the original. All the even bit positions (0,2,4, etc) then represent
* successful matches, so we mask with 0x55555..... to remove the unwanted
* odd bit positions.
*
* This allows searching of a whole u64 at once (32 blocks) with a
* single test (on 64 bit arches).
*/
static inline u64 gfs2_bit_search(const __le64 *ptr, u64 mask, u8 state)
{
u64 tmp;
static const u64 search[] = {
[0] = 0xffffffffffffffffULL,
[1] = 0xaaaaaaaaaaaaaaaaULL,
[2] = 0x5555555555555555ULL,
[3] = 0x0000000000000000ULL,
};
tmp = le64_to_cpu(*ptr) ^ search[state];
tmp &= (tmp >> 1);
tmp &= mask;
return tmp;
}
/**
* rs_cmp - multi-block reservation range compare
* @start: start of the new reservation
* @len: number of blocks in the new reservation
* @rs: existing reservation to compare against
*
* returns: 1 if the block range is beyond the reach of the reservation
* -1 if the block range is before the start of the reservation
* 0 if the block range overlaps with the reservation
*/
static inline int rs_cmp(u64 start, u32 len, struct gfs2_blkreserv *rs)
{
if (start >= rs->rs_start + rs->rs_requested)
return 1;
if (rs->rs_start >= start + len)
return -1;
return 0;
}
/**
* gfs2_bitfit - Search an rgrp's bitmap buffer to find a bit-pair representing
* a block in a given allocation state.
* @buf: the buffer that holds the bitmaps
* @len: the length (in bytes) of the buffer
* @goal: start search at this block's bit-pair (within @buffer)
* @state: GFS2_BLKST_XXX the state of the block we're looking for.
*
* Scope of @goal and returned block number is only within this bitmap buffer,
* not entire rgrp or filesystem. @buffer will be offset from the actual
* beginning of a bitmap block buffer, skipping any header structures, but
* headers are always a multiple of 64 bits long so that the buffer is
* always aligned to a 64 bit boundary.
*
* The size of the buffer is in bytes, but is it assumed that it is
* always ok to read a complete multiple of 64 bits at the end
* of the block in case the end is no aligned to a natural boundary.
*
* Return: the block number (bitmap buffer scope) that was found
*/
static u32 gfs2_bitfit(const u8 *buf, const unsigned int len,
u32 goal, u8 state)
{
u32 spoint = (goal << 1) & ((8*sizeof(u64)) - 1);
const __le64 *ptr = ((__le64 *)buf) + (goal >> 5);
const __le64 *end = (__le64 *)(buf + ALIGN(len, sizeof(u64)));
u64 tmp;
u64 mask = 0x5555555555555555ULL;
u32 bit;
/* Mask off bits we don't care about at the start of the search */
mask <<= spoint;
tmp = gfs2_bit_search(ptr, mask, state);
ptr++;
while(tmp == 0 && ptr < end) {
tmp = gfs2_bit_search(ptr, 0x5555555555555555ULL, state);
ptr++;
}
/* Mask off any bits which are more than len bytes from the start */
if (ptr == end && (len & (sizeof(u64) - 1)))
tmp &= (((u64)~0) >> (64 - 8*(len & (sizeof(u64) - 1))));
/* Didn't find anything, so return */
if (tmp == 0)
return BFITNOENT;
ptr--;
bit = __ffs64(tmp);
bit /= 2; /* two bits per entry in the bitmap */
return (((const unsigned char *)ptr - buf) * GFS2_NBBY) + bit;
}
/**
* gfs2_rbm_from_block - Set the rbm based upon rgd and block number
* @rbm: The rbm with rgd already set correctly
* @block: The block number (filesystem relative)
*
* This sets the bi and offset members of an rbm based on a
* resource group and a filesystem relative block number. The
* resource group must be set in the rbm on entry, the bi and
* offset members will be set by this function.
*
* Returns: 0 on success, or an error code
*/
static int gfs2_rbm_from_block(struct gfs2_rbm *rbm, u64 block)
{
if (!rgrp_contains_block(rbm->rgd, block))
return -E2BIG;
rbm->bii = 0;
rbm->offset = block - rbm->rgd->rd_data0;
/* Check if the block is within the first block */
if (rbm->offset < rbm_bi(rbm)->bi_blocks)
return 0;
/* Adjust for the size diff between gfs2_meta_header and gfs2_rgrp */
rbm->offset += (sizeof(struct gfs2_rgrp) -
sizeof(struct gfs2_meta_header)) * GFS2_NBBY;
rbm->bii = rbm->offset / rbm->rgd->rd_sbd->sd_blocks_per_bitmap;
rbm->offset -= rbm->bii * rbm->rgd->rd_sbd->sd_blocks_per_bitmap;
return 0;
}
/**
* gfs2_rbm_add - add a number of blocks to an rbm
* @rbm: The rbm with rgd already set correctly
* @blocks: The number of blocks to add to rpm
*
* This function takes an existing rbm structure and adds a number of blocks to
* it.
*
* Returns: True if the new rbm would point past the end of the rgrp.
*/
static bool gfs2_rbm_add(struct gfs2_rbm *rbm, u32 blocks)
{
struct gfs2_rgrpd *rgd = rbm->rgd;
struct gfs2_bitmap *bi = rgd->rd_bits + rbm->bii;
if (rbm->offset + blocks < bi->bi_blocks) {
rbm->offset += blocks;
return false;
}
blocks -= bi->bi_blocks - rbm->offset;
for(;;) {
bi++;
if (bi == rgd->rd_bits + rgd->rd_length)
return true;
if (blocks < bi->bi_blocks) {
rbm->offset = blocks;
rbm->bii = bi - rgd->rd_bits;
return false;
}
blocks -= bi->bi_blocks;
}
}
/**
* gfs2_unaligned_extlen - Look for free blocks which are not byte aligned
* @rbm: Position to search (value/result)
* @n_unaligned: Number of unaligned blocks to check
* @len: Decremented for each block found (terminate on zero)
*
* Returns: true if a non-free block is encountered or the end of the resource
* group is reached.
*/
static bool gfs2_unaligned_extlen(struct gfs2_rbm *rbm, u32 n_unaligned, u32 *len)
{
u32 n;
u8 res;
for (n = 0; n < n_unaligned; n++) {
res = gfs2_testbit(rbm, true);
if (res != GFS2_BLKST_FREE)
return true;
(*len)--;
if (*len == 0)
return true;
if (gfs2_rbm_add(rbm, 1))
return true;
}
return false;
}
/**
* gfs2_free_extlen - Return extent length of free blocks
* @rrbm: Starting position
* @len: Max length to check
*
* Starting at the block specified by the rbm, see how many free blocks
* there are, not reading more than len blocks ahead. This can be done
* using memchr_inv when the blocks are byte aligned, but has to be done
* on a block by block basis in case of unaligned blocks. Also this
* function can cope with bitmap boundaries (although it must stop on
* a resource group boundary)
*
* Returns: Number of free blocks in the extent
*/
static u32 gfs2_free_extlen(const struct gfs2_rbm *rrbm, u32 len)
{
struct gfs2_rbm rbm = *rrbm;
u32 n_unaligned = rbm.offset & 3;
u32 size = len;
u32 bytes;
u32 chunk_size;
u8 *ptr, *start, *end;
u64 block;
struct gfs2_bitmap *bi;
if (n_unaligned &&
gfs2_unaligned_extlen(&rbm, 4 - n_unaligned, &len))
goto out;
n_unaligned = len & 3;
/* Start is now byte aligned */
while (len > 3) {
bi = rbm_bi(&rbm);
start = bi->bi_bh->b_data;
if (bi->bi_clone)
start = bi->bi_clone;
start += bi->bi_offset;
end = start + bi->bi_bytes;
BUG_ON(rbm.offset & 3);
start += (rbm.offset / GFS2_NBBY);
bytes = min_t(u32, len / GFS2_NBBY, (end - start));
ptr = memchr_inv(start, 0, bytes);
chunk_size = ((ptr == NULL) ? bytes : (ptr - start));
chunk_size *= GFS2_NBBY;
BUG_ON(len < chunk_size);
len -= chunk_size;
block = gfs2_rbm_to_block(&rbm);
if (gfs2_rbm_from_block(&rbm, block + chunk_size)) {
n_unaligned = 0;
break;
}
if (ptr) {
n_unaligned = 3;
break;
}
n_unaligned = len & 3;
}
/* Deal with any bits left over at the end */
if (n_unaligned)
gfs2_unaligned_extlen(&rbm, n_unaligned, &len);
out:
return size - len;
}
/**
* gfs2_bitcount - count the number of bits in a certain state
* @rgd: the resource group descriptor
* @buffer: the buffer that holds the bitmaps
* @buflen: the length (in bytes) of the buffer
* @state: the state of the block we're looking for
*
* Returns: The number of bits
*/
static u32 gfs2_bitcount(struct gfs2_rgrpd *rgd, const u8 *buffer,
unsigned int buflen, u8 state)
{
const u8 *byte = buffer;
const u8 *end = buffer + buflen;
const u8 state1 = state << 2;
const u8 state2 = state << 4;
const u8 state3 = state << 6;
u32 count = 0;
for (; byte < end; byte++) {
if (((*byte) & 0x03) == state)
count++;
if (((*byte) & 0x0C) == state1)
count++;
if (((*byte) & 0x30) == state2)
count++;
if (((*byte) & 0xC0) == state3)
count++;
}
return count;
}
/**
* gfs2_rgrp_verify - Verify that a resource group is consistent
* @rgd: the rgrp
*
*/
void gfs2_rgrp_verify(struct gfs2_rgrpd *rgd)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
struct gfs2_bitmap *bi = NULL;
u32 length = rgd->rd_length;
u32 count[4], tmp;
int buf, x;
memset(count, 0, 4 * sizeof(u32));
/* Count # blocks in each of 4 possible allocation states */
for (buf = 0; buf < length; buf++) {
bi = rgd->rd_bits + buf;
for (x = 0; x < 4; x++)
count[x] += gfs2_bitcount(rgd,
bi->bi_bh->b_data +
bi->bi_offset,
bi->bi_bytes, x);
}
if (count[0] != rgd->rd_free) {
gfs2_lm(sdp, "free data mismatch: %u != %u\n",
count[0], rgd->rd_free);
gfs2_consist_rgrpd(rgd);
return;
}
tmp = rgd->rd_data - rgd->rd_free - rgd->rd_dinodes;
if (count[1] != tmp) {
gfs2_lm(sdp, "used data mismatch: %u != %u\n",
count[1], tmp);
gfs2_consist_rgrpd(rgd);
return;
}
if (count[2] + count[3] != rgd->rd_dinodes) {
gfs2_lm(sdp, "used metadata mismatch: %u != %u\n",
count[2] + count[3], rgd->rd_dinodes);
gfs2_consist_rgrpd(rgd);
return;
}
}
/**
* gfs2_blk2rgrpd - Find resource group for a given data/meta block number
* @sdp: The GFS2 superblock
* @blk: The data block number
* @exact: True if this needs to be an exact match
*
* The @exact argument should be set to true by most callers. The exception
* is when we need to match blocks which are not represented by the rgrp
* bitmap, but which are part of the rgrp (i.e. padding blocks) which are
* there for alignment purposes. Another way of looking at it is that @exact
* matches only valid data/metadata blocks, but with @exact false, it will
* match any block within the extent of the rgrp.
*
* Returns: The resource group, or NULL if not found
*/
struct gfs2_rgrpd *gfs2_blk2rgrpd(struct gfs2_sbd *sdp, u64 blk, bool exact)
{
struct rb_node *n, *next;
struct gfs2_rgrpd *cur;
spin_lock(&sdp->sd_rindex_spin);
n = sdp->sd_rindex_tree.rb_node;
while (n) {
cur = rb_entry(n, struct gfs2_rgrpd, rd_node);
next = NULL;
if (blk < cur->rd_addr)
next = n->rb_left;
else if (blk >= cur->rd_data0 + cur->rd_data)
next = n->rb_right;
if (next == NULL) {
spin_unlock(&sdp->sd_rindex_spin);
if (exact) {
if (blk < cur->rd_addr)
return NULL;
if (blk >= cur->rd_data0 + cur->rd_data)
return NULL;
}
return cur;
}
n = next;
}
spin_unlock(&sdp->sd_rindex_spin);
return NULL;
}
/**
* gfs2_rgrpd_get_first - get the first Resource Group in the filesystem
* @sdp: The GFS2 superblock
*
* Returns: The first rgrp in the filesystem
*/
struct gfs2_rgrpd *gfs2_rgrpd_get_first(struct gfs2_sbd *sdp)
{
const struct rb_node *n;
struct gfs2_rgrpd *rgd;
spin_lock(&sdp->sd_rindex_spin);
n = rb_first(&sdp->sd_rindex_tree);
rgd = rb_entry(n, struct gfs2_rgrpd, rd_node);
spin_unlock(&sdp->sd_rindex_spin);
return rgd;
}
/**
* gfs2_rgrpd_get_next - get the next RG
* @rgd: the resource group descriptor
*
* Returns: The next rgrp
*/
struct gfs2_rgrpd *gfs2_rgrpd_get_next(struct gfs2_rgrpd *rgd)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
const struct rb_node *n;
spin_lock(&sdp->sd_rindex_spin);
n = rb_next(&rgd->rd_node);
if (n == NULL)
n = rb_first(&sdp->sd_rindex_tree);
if (unlikely(&rgd->rd_node == n)) {
spin_unlock(&sdp->sd_rindex_spin);
return NULL;
}
rgd = rb_entry(n, struct gfs2_rgrpd, rd_node);
spin_unlock(&sdp->sd_rindex_spin);
return rgd;
}
void check_and_update_goal(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
if (!ip->i_goal || gfs2_blk2rgrpd(sdp, ip->i_goal, 1) == NULL)
ip->i_goal = ip->i_no_addr;
}
void gfs2_free_clones(struct gfs2_rgrpd *rgd)
{
int x;
for (x = 0; x < rgd->rd_length; x++) {
struct gfs2_bitmap *bi = rgd->rd_bits + x;
kfree(bi->bi_clone);
bi->bi_clone = NULL;
}
}
static void dump_rs(struct seq_file *seq, const struct gfs2_blkreserv *rs,
const char *fs_id_buf)
{
struct gfs2_inode *ip = container_of(rs, struct gfs2_inode, i_res);
gfs2_print_dbg(seq, "%s B: n:%llu s:%llu f:%u\n",
fs_id_buf,
(unsigned long long)ip->i_no_addr,
(unsigned long long)rs->rs_start,
rs->rs_requested);
}
/**
* __rs_deltree - remove a multi-block reservation from the rgd tree
* @rs: The reservation to remove
*
*/
static void __rs_deltree(struct gfs2_blkreserv *rs)
{
struct gfs2_rgrpd *rgd;
if (!gfs2_rs_active(rs))
return;
rgd = rs->rs_rgd;
trace_gfs2_rs(rs, TRACE_RS_TREEDEL);
rb_erase(&rs->rs_node, &rgd->rd_rstree);
RB_CLEAR_NODE(&rs->rs_node);
if (rs->rs_requested) {
/* return requested blocks to the rgrp */
BUG_ON(rs->rs_rgd->rd_requested < rs->rs_requested);
rs->rs_rgd->rd_requested -= rs->rs_requested;
/* The rgrp extent failure point is likely not to increase;
it will only do so if the freed blocks are somehow
contiguous with a span of free blocks that follows. Still,
it will force the number to be recalculated later. */
rgd->rd_extfail_pt += rs->rs_requested;
rs->rs_requested = 0;
}
}
/**
* gfs2_rs_deltree - remove a multi-block reservation from the rgd tree
* @rs: The reservation to remove
*
*/
void gfs2_rs_deltree(struct gfs2_blkreserv *rs)
{
struct gfs2_rgrpd *rgd;
rgd = rs->rs_rgd;
if (rgd) {
spin_lock(&rgd->rd_rsspin);
__rs_deltree(rs);
BUG_ON(rs->rs_requested);
spin_unlock(&rgd->rd_rsspin);
}
}
/**
* gfs2_rs_delete - delete a multi-block reservation
* @ip: The inode for this reservation
*
*/
void gfs2_rs_delete(struct gfs2_inode *ip)
{
struct inode *inode = &ip->i_inode;
down_write(&ip->i_rw_mutex);
if (atomic_read(&inode->i_writecount) <= 1)
gfs2_rs_deltree(&ip->i_res);
up_write(&ip->i_rw_mutex);
}
/**
* return_all_reservations - return all reserved blocks back to the rgrp.
* @rgd: the rgrp that needs its space back
*
* We previously reserved a bunch of blocks for allocation. Now we need to
* give them back. This leave the reservation structures in tact, but removes
* all of their corresponding "no-fly zones".
*/
static void return_all_reservations(struct gfs2_rgrpd *rgd)
{
struct rb_node *n;
struct gfs2_blkreserv *rs;
spin_lock(&rgd->rd_rsspin);
while ((n = rb_first(&rgd->rd_rstree))) {
rs = rb_entry(n, struct gfs2_blkreserv, rs_node);
__rs_deltree(rs);
}
spin_unlock(&rgd->rd_rsspin);
}
void gfs2_clear_rgrpd(struct gfs2_sbd *sdp)
{
struct rb_node *n;
struct gfs2_rgrpd *rgd;
struct gfs2_glock *gl;
while ((n = rb_first(&sdp->sd_rindex_tree))) {
rgd = rb_entry(n, struct gfs2_rgrpd, rd_node);
gl = rgd->rd_gl;
rb_erase(n, &sdp->sd_rindex_tree);
if (gl) {
if (gl->gl_state != LM_ST_UNLOCKED) {
gfs2_glock_cb(gl, LM_ST_UNLOCKED);
flush_delayed_work(&gl->gl_work);
}
gfs2_rgrp_brelse(rgd);
glock_clear_object(gl, rgd);
gfs2_glock_put(gl);
}
gfs2_free_clones(rgd);
return_all_reservations(rgd);
kfree(rgd->rd_bits);
rgd->rd_bits = NULL;
kmem_cache_free(gfs2_rgrpd_cachep, rgd);
}
}
/**
* compute_bitstructs - Compute the bitmap sizes
* @rgd: The resource group descriptor
*
* Calculates bitmap descriptors, one for each block that contains bitmap data
*
* Returns: errno
*/
static int compute_bitstructs(struct gfs2_rgrpd *rgd)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
struct gfs2_bitmap *bi;
u32 length = rgd->rd_length; /* # blocks in hdr & bitmap */
u32 bytes_left, bytes;
int x;
if (!length)
return -EINVAL;
rgd->rd_bits = kcalloc(length, sizeof(struct gfs2_bitmap), GFP_NOFS);
if (!rgd->rd_bits)
return -ENOMEM;
bytes_left = rgd->rd_bitbytes;
for (x = 0; x < length; x++) {
bi = rgd->rd_bits + x;
bi->bi_flags = 0;
/* small rgrp; bitmap stored completely in header block */
if (length == 1) {
bytes = bytes_left;
bi->bi_offset = sizeof(struct gfs2_rgrp);
bi->bi_start = 0;
bi->bi_bytes = bytes;
bi->bi_blocks = bytes * GFS2_NBBY;
/* header block */
} else if (x == 0) {
bytes = sdp->sd_sb.sb_bsize - sizeof(struct gfs2_rgrp);
bi->bi_offset = sizeof(struct gfs2_rgrp);
bi->bi_start = 0;
bi->bi_bytes = bytes;
bi->bi_blocks = bytes * GFS2_NBBY;
/* last block */
} else if (x + 1 == length) {
bytes = bytes_left;
bi->bi_offset = sizeof(struct gfs2_meta_header);
bi->bi_start = rgd->rd_bitbytes - bytes_left;
bi->bi_bytes = bytes;
bi->bi_blocks = bytes * GFS2_NBBY;
/* other blocks */
} else {
bytes = sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_meta_header);
bi->bi_offset = sizeof(struct gfs2_meta_header);
bi->bi_start = rgd->rd_bitbytes - bytes_left;
bi->bi_bytes = bytes;
bi->bi_blocks = bytes * GFS2_NBBY;
}
bytes_left -= bytes;
}
if (bytes_left) {
gfs2_consist_rgrpd(rgd);
return -EIO;
}
bi = rgd->rd_bits + (length - 1);
if ((bi->bi_start + bi->bi_bytes) * GFS2_NBBY != rgd->rd_data) {
gfs2_lm(sdp,
"ri_addr = %llu\n"
"ri_length = %u\n"
"ri_data0 = %llu\n"
"ri_data = %u\n"
"ri_bitbytes = %u\n"
"start=%u len=%u offset=%u\n",
(unsigned long long)rgd->rd_addr,
rgd->rd_length,
(unsigned long long)rgd->rd_data0,
rgd->rd_data,
rgd->rd_bitbytes,
bi->bi_start, bi->bi_bytes, bi->bi_offset);
gfs2_consist_rgrpd(rgd);
return -EIO;
}
return 0;
}
/**
* gfs2_ri_total - Total up the file system space, according to the rindex.
* @sdp: the filesystem
*
*/
u64 gfs2_ri_total(struct gfs2_sbd *sdp)
{
u64 total_data = 0;
struct inode *inode = sdp->sd_rindex;
struct gfs2_inode *ip = GFS2_I(inode);
char buf[sizeof(struct gfs2_rindex)];
int error, rgrps;
for (rgrps = 0;; rgrps++) {
loff_t pos = rgrps * sizeof(struct gfs2_rindex);
if (pos + sizeof(struct gfs2_rindex) > i_size_read(inode))
break;
error = gfs2_internal_read(ip, buf, &pos,
sizeof(struct gfs2_rindex));
if (error != sizeof(struct gfs2_rindex))
break;
total_data += be32_to_cpu(((struct gfs2_rindex *)buf)->ri_data);
}
return total_data;
}
static int rgd_insert(struct gfs2_rgrpd *rgd)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
struct rb_node **newn = &sdp->sd_rindex_tree.rb_node, *parent = NULL;
/* Figure out where to put new node */
while (*newn) {
struct gfs2_rgrpd *cur = rb_entry(*newn, struct gfs2_rgrpd,
rd_node);
parent = *newn;
if (rgd->rd_addr < cur->rd_addr)
newn = &((*newn)->rb_left);
else if (rgd->rd_addr > cur->rd_addr)
newn = &((*newn)->rb_right);
else
return -EEXIST;
}
rb_link_node(&rgd->rd_node, parent, newn);
rb_insert_color(&rgd->rd_node, &sdp->sd_rindex_tree);
sdp->sd_rgrps++;
return 0;
}
/**
* read_rindex_entry - Pull in a new resource index entry from the disk
* @ip: Pointer to the rindex inode
*
* Returns: 0 on success, > 0 on EOF, error code otherwise
*/
static int read_rindex_entry(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
loff_t pos = sdp->sd_rgrps * sizeof(struct gfs2_rindex);
struct gfs2_rindex buf;
int error;
struct gfs2_rgrpd *rgd;
if (pos >= i_size_read(&ip->i_inode))
return 1;
error = gfs2_internal_read(ip, (char *)&buf, &pos,
sizeof(struct gfs2_rindex));
if (error != sizeof(struct gfs2_rindex))
return (error == 0) ? 1 : error;
rgd = kmem_cache_zalloc(gfs2_rgrpd_cachep, GFP_NOFS);
error = -ENOMEM;
if (!rgd)
return error;
rgd->rd_sbd = sdp;
rgd->rd_addr = be64_to_cpu(buf.ri_addr);
rgd->rd_length = be32_to_cpu(buf.ri_length);
rgd->rd_data0 = be64_to_cpu(buf.ri_data0);
rgd->rd_data = be32_to_cpu(buf.ri_data);
rgd->rd_bitbytes = be32_to_cpu(buf.ri_bitbytes);
spin_lock_init(&rgd->rd_rsspin);
mutex_init(&rgd->rd_mutex);
error = gfs2_glock_get(sdp, rgd->rd_addr,
&gfs2_rgrp_glops, CREATE, &rgd->rd_gl);
if (error)
goto fail;
error = compute_bitstructs(rgd);
if (error)
goto fail_glock;
rgd->rd_rgl = (struct gfs2_rgrp_lvb *)rgd->rd_gl->gl_lksb.sb_lvbptr;
rgd->rd_flags &= ~GFS2_RDF_PREFERRED;
if (rgd->rd_data > sdp->sd_max_rg_data)
sdp->sd_max_rg_data = rgd->rd_data;
spin_lock(&sdp->sd_rindex_spin);
error = rgd_insert(rgd);
spin_unlock(&sdp->sd_rindex_spin);
if (!error) {
glock_set_object(rgd->rd_gl, rgd);
return 0;
}
error = 0; /* someone else read in the rgrp; free it and ignore it */
fail_glock:
gfs2_glock_put(rgd->rd_gl);
fail:
kfree(rgd->rd_bits);
rgd->rd_bits = NULL;
kmem_cache_free(gfs2_rgrpd_cachep, rgd);
return error;
}
/**
* set_rgrp_preferences - Run all the rgrps, selecting some we prefer to use
* @sdp: the GFS2 superblock
*
* The purpose of this function is to select a subset of the resource groups
* and mark them as PREFERRED. We do it in such a way that each node prefers
* to use a unique set of rgrps to minimize glock contention.
*/
static void set_rgrp_preferences(struct gfs2_sbd *sdp)
{
struct gfs2_rgrpd *rgd, *first;
int i;
/* Skip an initial number of rgrps, based on this node's journal ID.
That should start each node out on its own set. */
rgd = gfs2_rgrpd_get_first(sdp);
for (i = 0; i < sdp->sd_lockstruct.ls_jid; i++)
rgd = gfs2_rgrpd_get_next(rgd);
first = rgd;
do {
rgd->rd_flags |= GFS2_RDF_PREFERRED;
for (i = 0; i < sdp->sd_journals; i++) {
rgd = gfs2_rgrpd_get_next(rgd);
if (!rgd || rgd == first)
break;
}
} while (rgd && rgd != first);
}
/**
* gfs2_ri_update - Pull in a new resource index from the disk
* @ip: pointer to the rindex inode
*
* Returns: 0 on successful update, error code otherwise
*/
static int gfs2_ri_update(struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
int error;
do {
error = read_rindex_entry(ip);
} while (error == 0);
if (error < 0)
return error;
if (RB_EMPTY_ROOT(&sdp->sd_rindex_tree)) {
fs_err(sdp, "no resource groups found in the file system.\n");
return -ENOENT;
}
set_rgrp_preferences(sdp);
sdp->sd_rindex_uptodate = 1;
return 0;
}
/**
* gfs2_rindex_update - Update the rindex if required
* @sdp: The GFS2 superblock
*
* We grab a lock on the rindex inode to make sure that it doesn't
* change whilst we are performing an operation. We keep this lock
* for quite long periods of time compared to other locks. This
* doesn't matter, since it is shared and it is very, very rarely
* accessed in the exclusive mode (i.e. only when expanding the filesystem).
*
* This makes sure that we're using the latest copy of the resource index
* special file, which might have been updated if someone expanded the
* filesystem (via gfs2_grow utility), which adds new resource groups.
*
* Returns: 0 on succeess, error code otherwise
*/
int gfs2_rindex_update(struct gfs2_sbd *sdp)
{
struct gfs2_inode *ip = GFS2_I(sdp->sd_rindex);
struct gfs2_glock *gl = ip->i_gl;
struct gfs2_holder ri_gh;
int error = 0;
int unlock_required = 0;
/* Read new copy from disk if we don't have the latest */
if (!sdp->sd_rindex_uptodate) {
if (!gfs2_glock_is_locked_by_me(gl)) {
error = gfs2_glock_nq_init(gl, LM_ST_SHARED, 0, &ri_gh);
if (error)
return error;
unlock_required = 1;
}
if (!sdp->sd_rindex_uptodate)
error = gfs2_ri_update(ip);
if (unlock_required)
gfs2_glock_dq_uninit(&ri_gh);
}
return error;
}
static void gfs2_rgrp_in(struct gfs2_rgrpd *rgd, const void *buf)
{
const struct gfs2_rgrp *str = buf;
u32 rg_flags;
rg_flags = be32_to_cpu(str->rg_flags);
rg_flags &= ~GFS2_RDF_MASK;
rgd->rd_flags &= GFS2_RDF_MASK;
rgd->rd_flags |= rg_flags;
rgd->rd_free = be32_to_cpu(str->rg_free);
rgd->rd_dinodes = be32_to_cpu(str->rg_dinodes);
rgd->rd_igeneration = be64_to_cpu(str->rg_igeneration);
/* rd_data0, rd_data and rd_bitbytes already set from rindex */
}
static void gfs2_rgrp_ondisk2lvb(struct gfs2_rgrp_lvb *rgl, const void *buf)
{
const struct gfs2_rgrp *str = buf;
rgl->rl_magic = cpu_to_be32(GFS2_MAGIC);
rgl->rl_flags = str->rg_flags;
rgl->rl_free = str->rg_free;
rgl->rl_dinodes = str->rg_dinodes;
rgl->rl_igeneration = str->rg_igeneration;
rgl->__pad = 0UL;
}
static void gfs2_rgrp_out(struct gfs2_rgrpd *rgd, void *buf)
{
struct gfs2_rgrpd *next = gfs2_rgrpd_get_next(rgd);
struct gfs2_rgrp *str = buf;
u32 crc;
str->rg_flags = cpu_to_be32(rgd->rd_flags & ~GFS2_RDF_MASK);
str->rg_free = cpu_to_be32(rgd->rd_free);
str->rg_dinodes = cpu_to_be32(rgd->rd_dinodes);
if (next == NULL)
str->rg_skip = 0;
else if (next->rd_addr > rgd->rd_addr)
str->rg_skip = cpu_to_be32(next->rd_addr - rgd->rd_addr);
str->rg_igeneration = cpu_to_be64(rgd->rd_igeneration);
str->rg_data0 = cpu_to_be64(rgd->rd_data0);
str->rg_data = cpu_to_be32(rgd->rd_data);
str->rg_bitbytes = cpu_to_be32(rgd->rd_bitbytes);
str->rg_crc = 0;
crc = gfs2_disk_hash(buf, sizeof(struct gfs2_rgrp));
str->rg_crc = cpu_to_be32(crc);
memset(&str->rg_reserved, 0, sizeof(str->rg_reserved));
gfs2_rgrp_ondisk2lvb(rgd->rd_rgl, buf);
}
static int gfs2_rgrp_lvb_valid(struct gfs2_rgrpd *rgd)
{
struct gfs2_rgrp_lvb *rgl = rgd->rd_rgl;
struct gfs2_rgrp *str = (struct gfs2_rgrp *)rgd->rd_bits[0].bi_bh->b_data;
struct gfs2_sbd *sdp = rgd->rd_sbd;
int valid = 1;
if (rgl->rl_flags != str->rg_flags) {
fs_warn(sdp, "GFS2: rgd: %llu lvb flag mismatch %u/%u",
(unsigned long long)rgd->rd_addr,
be32_to_cpu(rgl->rl_flags), be32_to_cpu(str->rg_flags));
valid = 0;
}
if (rgl->rl_free != str->rg_free) {
fs_warn(sdp, "GFS2: rgd: %llu lvb free mismatch %u/%u",
(unsigned long long)rgd->rd_addr,
be32_to_cpu(rgl->rl_free), be32_to_cpu(str->rg_free));
valid = 0;
}
if (rgl->rl_dinodes != str->rg_dinodes) {
fs_warn(sdp, "GFS2: rgd: %llu lvb dinode mismatch %u/%u",
(unsigned long long)rgd->rd_addr,
be32_to_cpu(rgl->rl_dinodes),
be32_to_cpu(str->rg_dinodes));
valid = 0;
}
if (rgl->rl_igeneration != str->rg_igeneration) {
fs_warn(sdp, "GFS2: rgd: %llu lvb igen mismatch %llu/%llu",
(unsigned long long)rgd->rd_addr,
(unsigned long long)be64_to_cpu(rgl->rl_igeneration),
(unsigned long long)be64_to_cpu(str->rg_igeneration));
valid = 0;
}
return valid;
}
static u32 count_unlinked(struct gfs2_rgrpd *rgd)
{
struct gfs2_bitmap *bi;
const u32 length = rgd->rd_length;
const u8 *buffer = NULL;
u32 i, goal, count = 0;
for (i = 0, bi = rgd->rd_bits; i < length; i++, bi++) {
goal = 0;
buffer = bi->bi_bh->b_data + bi->bi_offset;
WARN_ON(!buffer_uptodate(bi->bi_bh));
while (goal < bi->bi_blocks) {
goal = gfs2_bitfit(buffer, bi->bi_bytes, goal,
GFS2_BLKST_UNLINKED);
if (goal == BFITNOENT)
break;
count++;
goal++;
}
}
return count;
}
static void rgrp_set_bitmap_flags(struct gfs2_rgrpd *rgd)
{
struct gfs2_bitmap *bi;
int x;
if (rgd->rd_free) {
for (x = 0; x < rgd->rd_length; x++) {
bi = rgd->rd_bits + x;
clear_bit(GBF_FULL, &bi->bi_flags);
}
} else {
for (x = 0; x < rgd->rd_length; x++) {
bi = rgd->rd_bits + x;
set_bit(GBF_FULL, &bi->bi_flags);
}
}
}
/**
* gfs2_rgrp_go_instantiate - Read in a RG's header and bitmaps
* @gh: the glock holder representing the rgrpd to read in
*
* Read in all of a Resource Group's header and bitmap blocks.
* Caller must eventually call gfs2_rgrp_brelse() to free the bitmaps.
*
* Returns: errno
*/
int gfs2_rgrp_go_instantiate(struct gfs2_glock *gl)
{
struct gfs2_rgrpd *rgd = gl->gl_object;
struct gfs2_sbd *sdp = rgd->rd_sbd;
unsigned int length = rgd->rd_length;
struct gfs2_bitmap *bi;
unsigned int x, y;
int error;
if (rgd->rd_bits[0].bi_bh != NULL)
return 0;
for (x = 0; x < length; x++) {
bi = rgd->rd_bits + x;
error = gfs2_meta_read(gl, rgd->rd_addr + x, 0, 0, &bi->bi_bh);
if (error)
goto fail;
}
for (y = length; y--;) {
bi = rgd->rd_bits + y;
error = gfs2_meta_wait(sdp, bi->bi_bh);
if (error)
goto fail;
if (gfs2_metatype_check(sdp, bi->bi_bh, y ? GFS2_METATYPE_RB :
GFS2_METATYPE_RG)) {
error = -EIO;
goto fail;
}
}
gfs2_rgrp_in(rgd, (rgd->rd_bits[0].bi_bh)->b_data);
rgrp_set_bitmap_flags(rgd);
rgd->rd_flags |= GFS2_RDF_CHECK;
rgd->rd_free_clone = rgd->rd_free;
GLOCK_BUG_ON(rgd->rd_gl, rgd->rd_reserved);
/* max out the rgrp allocation failure point */
rgd->rd_extfail_pt = rgd->rd_free;
if (cpu_to_be32(GFS2_MAGIC) != rgd->rd_rgl->rl_magic) {
rgd->rd_rgl->rl_unlinked = cpu_to_be32(count_unlinked(rgd));
gfs2_rgrp_ondisk2lvb(rgd->rd_rgl,
rgd->rd_bits[0].bi_bh->b_data);
} else if (sdp->sd_args.ar_rgrplvb) {
if (!gfs2_rgrp_lvb_valid(rgd)){
gfs2_consist_rgrpd(rgd);
error = -EIO;
goto fail;
}
if (rgd->rd_rgl->rl_unlinked == 0)
rgd->rd_flags &= ~GFS2_RDF_CHECK;
}
return 0;
fail:
while (x--) {
bi = rgd->rd_bits + x;
brelse(bi->bi_bh);
bi->bi_bh = NULL;
gfs2_assert_warn(sdp, !bi->bi_clone);
}
return error;
}
static int update_rgrp_lvb(struct gfs2_rgrpd *rgd, struct gfs2_holder *gh)
{
u32 rl_flags;
if (!test_bit(GLF_INSTANTIATE_NEEDED, &gh->gh_gl->gl_flags))
return 0;
if (cpu_to_be32(GFS2_MAGIC) != rgd->rd_rgl->rl_magic)
return gfs2_instantiate(gh);
rl_flags = be32_to_cpu(rgd->rd_rgl->rl_flags);
rl_flags &= ~GFS2_RDF_MASK;
rgd->rd_flags &= GFS2_RDF_MASK;
rgd->rd_flags |= (rl_flags | GFS2_RDF_CHECK);
if (rgd->rd_rgl->rl_unlinked == 0)
rgd->rd_flags &= ~GFS2_RDF_CHECK;
rgd->rd_free = be32_to_cpu(rgd->rd_rgl->rl_free);
rgrp_set_bitmap_flags(rgd);
rgd->rd_free_clone = rgd->rd_free;
GLOCK_BUG_ON(rgd->rd_gl, rgd->rd_reserved);
/* max out the rgrp allocation failure point */
rgd->rd_extfail_pt = rgd->rd_free;
rgd->rd_dinodes = be32_to_cpu(rgd->rd_rgl->rl_dinodes);
rgd->rd_igeneration = be64_to_cpu(rgd->rd_rgl->rl_igeneration);
return 0;
}
/**
* gfs2_rgrp_brelse - Release RG bitmaps read in with gfs2_rgrp_bh_get()
* @rgd: The resource group
*
*/
void gfs2_rgrp_brelse(struct gfs2_rgrpd *rgd)
{
int x, length = rgd->rd_length;
for (x = 0; x < length; x++) {
struct gfs2_bitmap *bi = rgd->rd_bits + x;
if (bi->bi_bh) {
brelse(bi->bi_bh);
bi->bi_bh = NULL;
}
}
set_bit(GLF_INSTANTIATE_NEEDED, &rgd->rd_gl->gl_flags);
}
int gfs2_rgrp_send_discards(struct gfs2_sbd *sdp, u64 offset,
struct buffer_head *bh,
const struct gfs2_bitmap *bi, unsigned minlen, u64 *ptrimmed)
{
struct super_block *sb = sdp->sd_vfs;
u64 blk;
sector_t start = 0;
sector_t nr_blks = 0;
int rv = -EIO;
unsigned int x;
u32 trimmed = 0;
u8 diff;
for (x = 0; x < bi->bi_bytes; x++) {
const u8 *clone = bi->bi_clone ? bi->bi_clone : bi->bi_bh->b_data;
clone += bi->bi_offset;
clone += x;
if (bh) {
const u8 *orig = bh->b_data + bi->bi_offset + x;
diff = ~(*orig | (*orig >> 1)) & (*clone | (*clone >> 1));
} else {
diff = ~(*clone | (*clone >> 1));
}
diff &= 0x55;
if (diff == 0)
continue;
blk = offset + ((bi->bi_start + x) * GFS2_NBBY);
while(diff) {
if (diff & 1) {
if (nr_blks == 0)
goto start_new_extent;
if ((start + nr_blks) != blk) {
if (nr_blks >= minlen) {
rv = sb_issue_discard(sb,
start, nr_blks,
GFP_NOFS, 0);
if (rv)
goto fail;
trimmed += nr_blks;
}
nr_blks = 0;
start_new_extent:
start = blk;
}
nr_blks++;
}
diff >>= 2;
blk++;
}
}
if (nr_blks >= minlen) {
rv = sb_issue_discard(sb, start, nr_blks, GFP_NOFS, 0);
if (rv)
goto fail;
trimmed += nr_blks;
}
if (ptrimmed)
*ptrimmed = trimmed;
return 0;
fail:
if (sdp->sd_args.ar_discard)
fs_warn(sdp, "error %d on discard request, turning discards off for this filesystem\n", rv);
sdp->sd_args.ar_discard = 0;
return rv;
}
/**
* gfs2_fitrim - Generate discard requests for unused bits of the filesystem
* @filp: Any file on the filesystem
* @argp: Pointer to the arguments (also used to pass result)
*
* Returns: 0 on success, otherwise error code
*/
int gfs2_fitrim(struct file *filp, void __user *argp)
{
struct inode *inode = file_inode(filp);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct block_device *bdev = sdp->sd_vfs->s_bdev;
struct buffer_head *bh;
struct gfs2_rgrpd *rgd;
struct gfs2_rgrpd *rgd_end;
struct gfs2_holder gh;
struct fstrim_range r;
int ret = 0;
u64 amt;
u64 trimmed = 0;
u64 start, end, minlen;
unsigned int x;
unsigned bs_shift = sdp->sd_sb.sb_bsize_shift;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!test_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags))
return -EROFS;
if (!bdev_max_discard_sectors(bdev))
return -EOPNOTSUPP;
if (copy_from_user(&r, argp, sizeof(r)))
return -EFAULT;
ret = gfs2_rindex_update(sdp);
if (ret)
return ret;
start = r.start >> bs_shift;
end = start + (r.len >> bs_shift);
minlen = max_t(u64, r.minlen, sdp->sd_sb.sb_bsize);
minlen = max_t(u64, minlen, bdev_discard_granularity(bdev)) >> bs_shift;
if (end <= start || minlen > sdp->sd_max_rg_data)
return -EINVAL;
rgd = gfs2_blk2rgrpd(sdp, start, 0);
rgd_end = gfs2_blk2rgrpd(sdp, end, 0);
if ((gfs2_rgrpd_get_first(sdp) == gfs2_rgrpd_get_next(rgd_end))
&& (start > rgd_end->rd_data0 + rgd_end->rd_data))
return -EINVAL; /* start is beyond the end of the fs */
while (1) {
ret = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_EXCLUSIVE,
LM_FLAG_NODE_SCOPE, &gh);
if (ret)
goto out;
if (!(rgd->rd_flags & GFS2_RGF_TRIMMED)) {
/* Trim each bitmap in the rgrp */
for (x = 0; x < rgd->rd_length; x++) {
struct gfs2_bitmap *bi = rgd->rd_bits + x;
rgrp_lock_local(rgd);
ret = gfs2_rgrp_send_discards(sdp,
rgd->rd_data0, NULL, bi, minlen,
&amt);
rgrp_unlock_local(rgd);
if (ret) {
gfs2_glock_dq_uninit(&gh);
goto out;
}
trimmed += amt;
}
/* Mark rgrp as having been trimmed */
ret = gfs2_trans_begin(sdp, RES_RG_HDR, 0);
if (ret == 0) {
bh = rgd->rd_bits[0].bi_bh;
rgrp_lock_local(rgd);
rgd->rd_flags |= GFS2_RGF_TRIMMED;
gfs2_trans_add_meta(rgd->rd_gl, bh);
gfs2_rgrp_out(rgd, bh->b_data);
rgrp_unlock_local(rgd);
gfs2_trans_end(sdp);
}
}
gfs2_glock_dq_uninit(&gh);
if (rgd == rgd_end)
break;
rgd = gfs2_rgrpd_get_next(rgd);
}
out:
r.len = trimmed << bs_shift;
if (copy_to_user(argp, &r, sizeof(r)))
return -EFAULT;
return ret;
}
/**
* rs_insert - insert a new multi-block reservation into the rgrp's rb_tree
* @ip: the inode structure
*
*/
static void rs_insert(struct gfs2_inode *ip)
{
struct rb_node **newn, *parent = NULL;
int rc;
struct gfs2_blkreserv *rs = &ip->i_res;
struct gfs2_rgrpd *rgd = rs->rs_rgd;
BUG_ON(gfs2_rs_active(rs));
spin_lock(&rgd->rd_rsspin);
newn = &rgd->rd_rstree.rb_node;
while (*newn) {
struct gfs2_blkreserv *cur =
rb_entry(*newn, struct gfs2_blkreserv, rs_node);
parent = *newn;
rc = rs_cmp(rs->rs_start, rs->rs_requested, cur);
if (rc > 0)
newn = &((*newn)->rb_right);
else if (rc < 0)
newn = &((*newn)->rb_left);
else {
spin_unlock(&rgd->rd_rsspin);
WARN_ON(1);
return;
}
}
rb_link_node(&rs->rs_node, parent, newn);
rb_insert_color(&rs->rs_node, &rgd->rd_rstree);
/* Do our rgrp accounting for the reservation */
rgd->rd_requested += rs->rs_requested; /* blocks requested */
spin_unlock(&rgd->rd_rsspin);
trace_gfs2_rs(rs, TRACE_RS_INSERT);
}
/**
* rgd_free - return the number of free blocks we can allocate
* @rgd: the resource group
* @rs: The reservation to free
*
* This function returns the number of free blocks for an rgrp.
* That's the clone-free blocks (blocks that are free, not including those
* still being used for unlinked files that haven't been deleted.)
*
* It also subtracts any blocks reserved by someone else, but does not
* include free blocks that are still part of our current reservation,
* because obviously we can (and will) allocate them.
*/
static inline u32 rgd_free(struct gfs2_rgrpd *rgd, struct gfs2_blkreserv *rs)
{
u32 tot_reserved, tot_free;
if (WARN_ON_ONCE(rgd->rd_requested < rs->rs_requested))
return 0;
tot_reserved = rgd->rd_requested - rs->rs_requested;
if (rgd->rd_free_clone < tot_reserved)
tot_reserved = 0;
tot_free = rgd->rd_free_clone - tot_reserved;
return tot_free;
}
/**
* rg_mblk_search - find a group of multiple free blocks to form a reservation
* @rgd: the resource group descriptor
* @ip: pointer to the inode for which we're reserving blocks
* @ap: the allocation parameters
*
*/
static void rg_mblk_search(struct gfs2_rgrpd *rgd, struct gfs2_inode *ip,
const struct gfs2_alloc_parms *ap)
{
struct gfs2_rbm rbm = { .rgd = rgd, };
u64 goal;
struct gfs2_blkreserv *rs = &ip->i_res;
u32 extlen;
u32 free_blocks, blocks_available;
int ret;
struct inode *inode = &ip->i_inode;
spin_lock(&rgd->rd_rsspin);
free_blocks = rgd_free(rgd, rs);
if (rgd->rd_free_clone < rgd->rd_requested)
free_blocks = 0;
blocks_available = rgd->rd_free_clone - rgd->rd_reserved;
if (rgd == rs->rs_rgd)
blocks_available += rs->rs_reserved;
spin_unlock(&rgd->rd_rsspin);
if (S_ISDIR(inode->i_mode))
extlen = 1;
else {
extlen = max_t(u32, atomic_read(&ip->i_sizehint), ap->target);
extlen = clamp(extlen, (u32)RGRP_RSRV_MINBLKS, free_blocks);
}
if (free_blocks < extlen || blocks_available < extlen)
return;
/* Find bitmap block that contains bits for goal block */
if (rgrp_contains_block(rgd, ip->i_goal))
goal = ip->i_goal;
else
goal = rgd->rd_last_alloc + rgd->rd_data0;
if (WARN_ON(gfs2_rbm_from_block(&rbm, goal)))
return;
ret = gfs2_rbm_find(&rbm, GFS2_BLKST_FREE, &extlen, &ip->i_res, true);
if (ret == 0) {
rs->rs_start = gfs2_rbm_to_block(&rbm);
rs->rs_requested = extlen;
rs_insert(ip);
} else {
if (goal == rgd->rd_last_alloc + rgd->rd_data0)
rgd->rd_last_alloc = 0;
}
}
/**
* gfs2_next_unreserved_block - Return next block that is not reserved
* @rgd: The resource group
* @block: The starting block
* @length: The required length
* @ignore_rs: Reservation to ignore
*
* If the block does not appear in any reservation, then return the
* block number unchanged. If it does appear in the reservation, then
* keep looking through the tree of reservations in order to find the
* first block number which is not reserved.
*/
static u64 gfs2_next_unreserved_block(struct gfs2_rgrpd *rgd, u64 block,
u32 length,
struct gfs2_blkreserv *ignore_rs)
{
struct gfs2_blkreserv *rs;
struct rb_node *n;
int rc;
spin_lock(&rgd->rd_rsspin);
n = rgd->rd_rstree.rb_node;
while (n) {
rs = rb_entry(n, struct gfs2_blkreserv, rs_node);
rc = rs_cmp(block, length, rs);
if (rc < 0)
n = n->rb_left;
else if (rc > 0)
n = n->rb_right;
else
break;
}
if (n) {
while (rs_cmp(block, length, rs) == 0 && rs != ignore_rs) {
block = rs->rs_start + rs->rs_requested;
n = n->rb_right;
if (n == NULL)
break;
rs = rb_entry(n, struct gfs2_blkreserv, rs_node);
}
}
spin_unlock(&rgd->rd_rsspin);
return block;
}
/**
* gfs2_reservation_check_and_update - Check for reservations during block alloc
* @rbm: The current position in the resource group
* @rs: Our own reservation
* @minext: The minimum extent length
* @maxext: A pointer to the maximum extent structure
*
* This checks the current position in the rgrp to see whether there is
* a reservation covering this block. If not then this function is a
* no-op. If there is, then the position is moved to the end of the
* contiguous reservation(s) so that we are pointing at the first
* non-reserved block.
*
* Returns: 0 if no reservation, 1 if @rbm has changed, otherwise an error
*/
static int gfs2_reservation_check_and_update(struct gfs2_rbm *rbm,
struct gfs2_blkreserv *rs,
u32 minext,
struct gfs2_extent *maxext)
{
u64 block = gfs2_rbm_to_block(rbm);
u32 extlen = 1;
u64 nblock;
/*
* If we have a minimum extent length, then skip over any extent
* which is less than the min extent length in size.
*/
if (minext > 1) {
extlen = gfs2_free_extlen(rbm, minext);
if (extlen <= maxext->len)
goto fail;
}
/*
* Check the extent which has been found against the reservations
* and skip if parts of it are already reserved
*/
nblock = gfs2_next_unreserved_block(rbm->rgd, block, extlen, rs);
if (nblock == block) {
if (!minext || extlen >= minext)
return 0;
if (extlen > maxext->len) {
maxext->len = extlen;
maxext->rbm = *rbm;
}
} else {
u64 len = nblock - block;
if (len >= (u64)1 << 32)
return -E2BIG;
extlen = len;
}
fail:
if (gfs2_rbm_add(rbm, extlen))
return -E2BIG;
return 1;
}
/**
* gfs2_rbm_find - Look for blocks of a particular state
* @rbm: Value/result starting position and final position
* @state: The state which we want to find
* @minext: Pointer to the requested extent length
* This is updated to be the actual reservation size.
* @rs: Our own reservation (NULL to skip checking for reservations)
* @nowrap: Stop looking at the end of the rgrp, rather than wrapping
* around until we've reached the starting point.
*
* Side effects:
* - If looking for free blocks, we set GBF_FULL on each bitmap which
* has no free blocks in it.
* - If looking for free blocks, we set rd_extfail_pt on each rgrp which
* has come up short on a free block search.
*
* Returns: 0 on success, -ENOSPC if there is no block of the requested state
*/
static int gfs2_rbm_find(struct gfs2_rbm *rbm, u8 state, u32 *minext,
struct gfs2_blkreserv *rs, bool nowrap)
{
bool scan_from_start = rbm->bii == 0 && rbm->offset == 0;
struct buffer_head *bh;
int last_bii;
u32 offset;
u8 *buffer;
bool wrapped = false;
int ret;
struct gfs2_bitmap *bi;
struct gfs2_extent maxext = { .rbm.rgd = rbm->rgd, };
/*
* Determine the last bitmap to search. If we're not starting at the
* beginning of a bitmap, we need to search that bitmap twice to scan
* the entire resource group.
*/
last_bii = rbm->bii - (rbm->offset == 0);
while(1) {
bi = rbm_bi(rbm);
if (test_bit(GBF_FULL, &bi->bi_flags) &&
(state == GFS2_BLKST_FREE))
goto next_bitmap;
bh = bi->bi_bh;
buffer = bh->b_data + bi->bi_offset;
WARN_ON(!buffer_uptodate(bh));
if (state != GFS2_BLKST_UNLINKED && bi->bi_clone)
buffer = bi->bi_clone + bi->bi_offset;
offset = gfs2_bitfit(buffer, bi->bi_bytes, rbm->offset, state);
if (offset == BFITNOENT) {
if (state == GFS2_BLKST_FREE && rbm->offset == 0)
set_bit(GBF_FULL, &bi->bi_flags);
goto next_bitmap;
}
rbm->offset = offset;
if (!rs || !minext)
return 0;
ret = gfs2_reservation_check_and_update(rbm, rs, *minext,
&maxext);
if (ret == 0)
return 0;
if (ret > 0)
goto next_iter;
if (ret == -E2BIG) {
rbm->bii = 0;
rbm->offset = 0;
goto res_covered_end_of_rgrp;
}
return ret;
next_bitmap: /* Find next bitmap in the rgrp */
rbm->offset = 0;
rbm->bii++;
if (rbm->bii == rbm->rgd->rd_length)
rbm->bii = 0;
res_covered_end_of_rgrp:
if (rbm->bii == 0) {
if (wrapped)
break;
wrapped = true;
if (nowrap)
break;
}
next_iter:
/* Have we scanned the entire resource group? */
if (wrapped && rbm->bii > last_bii)
break;
}
if (state != GFS2_BLKST_FREE)
return -ENOSPC;
/* If the extent was too small, and it's smaller than the smallest
to have failed before, remember for future reference that it's
useless to search this rgrp again for this amount or more. */
if (wrapped && (scan_from_start || rbm->bii > last_bii) &&
*minext < rbm->rgd->rd_extfail_pt)
rbm->rgd->rd_extfail_pt = *minext - 1;
/* If the maximum extent we found is big enough to fulfill the
minimum requirements, use it anyway. */
if (maxext.len) {
*rbm = maxext.rbm;
*minext = maxext.len;
return 0;
}
return -ENOSPC;
}
/**
* try_rgrp_unlink - Look for any unlinked, allocated, but unused inodes
* @rgd: The rgrp
* @last_unlinked: block address of the last dinode we unlinked
* @skip: block address we should explicitly not unlink
*
* Returns: 0 if no error
* The inode, if one has been found, in inode.
*/
static void try_rgrp_unlink(struct gfs2_rgrpd *rgd, u64 *last_unlinked, u64 skip)
{
u64 block;
struct gfs2_sbd *sdp = rgd->rd_sbd;
struct gfs2_glock *gl;
struct gfs2_inode *ip;
int error;
int found = 0;
struct gfs2_rbm rbm = { .rgd = rgd, .bii = 0, .offset = 0 };
while (1) {
error = gfs2_rbm_find(&rbm, GFS2_BLKST_UNLINKED, NULL, NULL,
true);
if (error == -ENOSPC)
break;
if (WARN_ON_ONCE(error))
break;
block = gfs2_rbm_to_block(&rbm);
if (gfs2_rbm_from_block(&rbm, block + 1))
break;
if (*last_unlinked != NO_BLOCK && block <= *last_unlinked)
continue;
if (block == skip)
continue;
*last_unlinked = block;
error = gfs2_glock_get(sdp, block, &gfs2_iopen_glops, CREATE, &gl);
if (error)
continue;
/* If the inode is already in cache, we can ignore it here
* because the existing inode disposal code will deal with
* it when all refs have gone away. Accessing gl_object like
* this is not safe in general. Here it is ok because we do
* not dereference the pointer, and we only need an approx
* answer to whether it is NULL or not.
*/
ip = gl->gl_object;
if (ip || !gfs2_queue_try_to_evict(gl))
gfs2_glock_put(gl);
else
found++;
/* Limit reclaim to sensible number of tasks */
if (found > NR_CPUS)
return;
}
rgd->rd_flags &= ~GFS2_RDF_CHECK;
return;
}
/**
* gfs2_rgrp_congested - Use stats to figure out whether an rgrp is congested
* @rgd: The rgrp in question
* @loops: An indication of how picky we can be (0=very, 1=less so)
*
* This function uses the recently added glock statistics in order to
* figure out whether a parciular resource group is suffering from
* contention from multiple nodes. This is done purely on the basis
* of timings, since this is the only data we have to work with and
* our aim here is to reject a resource group which is highly contended
* but (very important) not to do this too often in order to ensure that
* we do not land up introducing fragmentation by changing resource
* groups when not actually required.
*
* The calculation is fairly simple, we want to know whether the SRTTB
* (i.e. smoothed round trip time for blocking operations) to acquire
* the lock for this rgrp's glock is significantly greater than the
* time taken for resource groups on average. We introduce a margin in
* the form of the variable @var which is computed as the sum of the two
* respective variences, and multiplied by a factor depending on @loops
* and whether we have a lot of data to base the decision on. This is
* then tested against the square difference of the means in order to
* decide whether the result is statistically significant or not.
*
* Returns: A boolean verdict on the congestion status
*/
static bool gfs2_rgrp_congested(const struct gfs2_rgrpd *rgd, int loops)
{
const struct gfs2_glock *gl = rgd->rd_gl;
const struct gfs2_sbd *sdp = gl->gl_name.ln_sbd;
struct gfs2_lkstats *st;
u64 r_dcount, l_dcount;
u64 l_srttb, a_srttb = 0;
s64 srttb_diff;
u64 sqr_diff;
u64 var;
int cpu, nonzero = 0;
preempt_disable();
for_each_present_cpu(cpu) {
st = &per_cpu_ptr(sdp->sd_lkstats, cpu)->lkstats[LM_TYPE_RGRP];
if (st->stats[GFS2_LKS_SRTTB]) {
a_srttb += st->stats[GFS2_LKS_SRTTB];
nonzero++;
}
}
st = &this_cpu_ptr(sdp->sd_lkstats)->lkstats[LM_TYPE_RGRP];
if (nonzero)
do_div(a_srttb, nonzero);
r_dcount = st->stats[GFS2_LKS_DCOUNT];
var = st->stats[GFS2_LKS_SRTTVARB] +
gl->gl_stats.stats[GFS2_LKS_SRTTVARB];
preempt_enable();
l_srttb = gl->gl_stats.stats[GFS2_LKS_SRTTB];
l_dcount = gl->gl_stats.stats[GFS2_LKS_DCOUNT];
if ((l_dcount < 1) || (r_dcount < 1) || (a_srttb == 0))
return false;
srttb_diff = a_srttb - l_srttb;
sqr_diff = srttb_diff * srttb_diff;
var *= 2;
if (l_dcount < 8 || r_dcount < 8)
var *= 2;
if (loops == 1)
var *= 2;
return ((srttb_diff < 0) && (sqr_diff > var));
}
/**
* gfs2_rgrp_used_recently
* @rs: The block reservation with the rgrp to test
* @msecs: The time limit in milliseconds
*
* Returns: True if the rgrp glock has been used within the time limit
*/
static bool gfs2_rgrp_used_recently(const struct gfs2_blkreserv *rs,
u64 msecs)
{
u64 tdiff;
tdiff = ktime_to_ns(ktime_sub(ktime_get_real(),
rs->rs_rgd->rd_gl->gl_dstamp));
return tdiff > (msecs * 1000 * 1000);
}
static u32 gfs2_orlov_skip(const struct gfs2_inode *ip)
{
const struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
u32 skip;
get_random_bytes(&skip, sizeof(skip));
return skip % sdp->sd_rgrps;
}
static bool gfs2_select_rgrp(struct gfs2_rgrpd **pos, const struct gfs2_rgrpd *begin)
{
struct gfs2_rgrpd *rgd = *pos;
struct gfs2_sbd *sdp = rgd->rd_sbd;
rgd = gfs2_rgrpd_get_next(rgd);
if (rgd == NULL)
rgd = gfs2_rgrpd_get_first(sdp);
*pos = rgd;
if (rgd != begin) /* If we didn't wrap */
return true;
return false;
}
/**
* fast_to_acquire - determine if a resource group will be fast to acquire
* @rgd: The rgrp
*
* If this is one of our preferred rgrps, it should be quicker to acquire,
* because we tried to set ourselves up as dlm lock master.
*/
static inline int fast_to_acquire(struct gfs2_rgrpd *rgd)
{
struct gfs2_glock *gl = rgd->rd_gl;
if (gl->gl_state != LM_ST_UNLOCKED && list_empty(&gl->gl_holders) &&
!test_bit(GLF_DEMOTE_IN_PROGRESS, &gl->gl_flags) &&
!test_bit(GLF_DEMOTE, &gl->gl_flags))
return 1;
if (rgd->rd_flags & GFS2_RDF_PREFERRED)
return 1;
return 0;
}
/**
* gfs2_inplace_reserve - Reserve space in the filesystem
* @ip: the inode to reserve space for
* @ap: the allocation parameters
*
* We try our best to find an rgrp that has at least ap->target blocks
* available. After a couple of passes (loops == 2), the prospects of finding
* such an rgrp diminish. At this stage, we return the first rgrp that has
* at least ap->min_target blocks available.
*
* Returns: 0 on success,
* -ENOMEM if a suitable rgrp can't be found
* errno otherwise
*/
int gfs2_inplace_reserve(struct gfs2_inode *ip, struct gfs2_alloc_parms *ap)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *begin = NULL;
struct gfs2_blkreserv *rs = &ip->i_res;
int error = 0, flags = LM_FLAG_NODE_SCOPE;
bool rg_locked;
u64 last_unlinked = NO_BLOCK;
u32 target = ap->target;
int loops = 0;
u32 free_blocks, blocks_available, skip = 0;
BUG_ON(rs->rs_reserved);
if (sdp->sd_args.ar_rgrplvb)
flags |= GL_SKIP;
if (gfs2_assert_warn(sdp, target))
return -EINVAL;
if (gfs2_rs_active(rs)) {
begin = rs->rs_rgd;
} else if (rs->rs_rgd &&
rgrp_contains_block(rs->rs_rgd, ip->i_goal)) {
begin = rs->rs_rgd;
} else {
check_and_update_goal(ip);
rs->rs_rgd = begin = gfs2_blk2rgrpd(sdp, ip->i_goal, 1);
}
if (S_ISDIR(ip->i_inode.i_mode) && (ap->aflags & GFS2_AF_ORLOV))
skip = gfs2_orlov_skip(ip);
if (rs->rs_rgd == NULL)
return -EBADSLT;
while (loops < 3) {
struct gfs2_rgrpd *rgd;
rg_locked = gfs2_glock_is_locked_by_me(rs->rs_rgd->rd_gl);
if (rg_locked) {
rgrp_lock_local(rs->rs_rgd);
} else {
if (skip && skip--)
goto next_rgrp;
if (!gfs2_rs_active(rs)) {
if (loops == 0 &&
!fast_to_acquire(rs->rs_rgd))
goto next_rgrp;
if ((loops < 2) &&
gfs2_rgrp_used_recently(rs, 1000) &&
gfs2_rgrp_congested(rs->rs_rgd, loops))
goto next_rgrp;
}
error = gfs2_glock_nq_init(rs->rs_rgd->rd_gl,
LM_ST_EXCLUSIVE, flags,
&ip->i_rgd_gh);
if (unlikely(error))
return error;
rgrp_lock_local(rs->rs_rgd);
if (!gfs2_rs_active(rs) && (loops < 2) &&
gfs2_rgrp_congested(rs->rs_rgd, loops))
goto skip_rgrp;
if (sdp->sd_args.ar_rgrplvb) {
error = update_rgrp_lvb(rs->rs_rgd,
&ip->i_rgd_gh);
if (unlikely(error)) {
rgrp_unlock_local(rs->rs_rgd);
gfs2_glock_dq_uninit(&ip->i_rgd_gh);
return error;
}
}
}
/* Skip unusable resource groups */
if ((rs->rs_rgd->rd_flags & (GFS2_RGF_NOALLOC |
GFS2_RDF_ERROR)) ||
(loops == 0 && target > rs->rs_rgd->rd_extfail_pt))
goto skip_rgrp;
if (sdp->sd_args.ar_rgrplvb) {
error = gfs2_instantiate(&ip->i_rgd_gh);
if (error)
goto skip_rgrp;
}
/* Get a reservation if we don't already have one */
if (!gfs2_rs_active(rs))
rg_mblk_search(rs->rs_rgd, ip, ap);
/* Skip rgrps when we can't get a reservation on first pass */
if (!gfs2_rs_active(rs) && (loops < 1))
goto check_rgrp;
/* If rgrp has enough free space, use it */
rgd = rs->rs_rgd;
spin_lock(&rgd->rd_rsspin);
free_blocks = rgd_free(rgd, rs);
blocks_available = rgd->rd_free_clone - rgd->rd_reserved;
if (free_blocks < target || blocks_available < target) {
spin_unlock(&rgd->rd_rsspin);
goto check_rgrp;
}
rs->rs_reserved = ap->target;
if (rs->rs_reserved > blocks_available)
rs->rs_reserved = blocks_available;
rgd->rd_reserved += rs->rs_reserved;
spin_unlock(&rgd->rd_rsspin);
rgrp_unlock_local(rs->rs_rgd);
return 0;
check_rgrp:
/* Check for unlinked inodes which can be reclaimed */
if (rs->rs_rgd->rd_flags & GFS2_RDF_CHECK)
try_rgrp_unlink(rs->rs_rgd, &last_unlinked,
ip->i_no_addr);
skip_rgrp:
rgrp_unlock_local(rs->rs_rgd);
/* Drop reservation, if we couldn't use reserved rgrp */
if (gfs2_rs_active(rs))
gfs2_rs_deltree(rs);
/* Unlock rgrp if required */
if (!rg_locked)
gfs2_glock_dq_uninit(&ip->i_rgd_gh);
next_rgrp:
/* Find the next rgrp, and continue looking */
if (gfs2_select_rgrp(&rs->rs_rgd, begin))
continue;
if (skip)
continue;
/* If we've scanned all the rgrps, but found no free blocks
* then this checks for some less likely conditions before
* trying again.
*/
loops++;
/* Check that fs hasn't grown if writing to rindex */
if (ip == GFS2_I(sdp->sd_rindex) && !sdp->sd_rindex_uptodate) {
error = gfs2_ri_update(ip);
if (error)
return error;
}
/* Flushing the log may release space */
if (loops == 2) {
if (ap->min_target)
target = ap->min_target;
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_INPLACE_RESERVE);
}
}
return -ENOSPC;
}
/**
* gfs2_inplace_release - release an inplace reservation
* @ip: the inode the reservation was taken out on
*
* Release a reservation made by gfs2_inplace_reserve().
*/
void gfs2_inplace_release(struct gfs2_inode *ip)
{
struct gfs2_blkreserv *rs = &ip->i_res;
if (rs->rs_reserved) {
struct gfs2_rgrpd *rgd = rs->rs_rgd;
spin_lock(&rgd->rd_rsspin);
GLOCK_BUG_ON(rgd->rd_gl, rgd->rd_reserved < rs->rs_reserved);
rgd->rd_reserved -= rs->rs_reserved;
spin_unlock(&rgd->rd_rsspin);
rs->rs_reserved = 0;
}
if (gfs2_holder_initialized(&ip->i_rgd_gh))
gfs2_glock_dq_uninit(&ip->i_rgd_gh);
}
/**
* gfs2_alloc_extent - allocate an extent from a given bitmap
* @rbm: the resource group information
* @dinode: TRUE if the first block we allocate is for a dinode
* @n: The extent length (value/result)
*
* Add the bitmap buffer to the transaction.
* Set the found bits to @new_state to change block's allocation state.
*/
static void gfs2_alloc_extent(const struct gfs2_rbm *rbm, bool dinode,
unsigned int *n)
{
struct gfs2_rbm pos = { .rgd = rbm->rgd, };
const unsigned int elen = *n;
u64 block;
int ret;
*n = 1;
block = gfs2_rbm_to_block(rbm);
gfs2_trans_add_meta(rbm->rgd->rd_gl, rbm_bi(rbm)->bi_bh);
gfs2_setbit(rbm, true, dinode ? GFS2_BLKST_DINODE : GFS2_BLKST_USED);
block++;
while (*n < elen) {
ret = gfs2_rbm_from_block(&pos, block);
if (ret || gfs2_testbit(&pos, true) != GFS2_BLKST_FREE)
break;
gfs2_trans_add_meta(pos.rgd->rd_gl, rbm_bi(&pos)->bi_bh);
gfs2_setbit(&pos, true, GFS2_BLKST_USED);
(*n)++;
block++;
}
}
/**
* rgblk_free - Change alloc state of given block(s)
* @sdp: the filesystem
* @rgd: the resource group the blocks are in
* @bstart: the start of a run of blocks to free
* @blen: the length of the block run (all must lie within ONE RG!)
* @new_state: GFS2_BLKST_XXX the after-allocation block state
*/
static void rgblk_free(struct gfs2_sbd *sdp, struct gfs2_rgrpd *rgd,
u64 bstart, u32 blen, unsigned char new_state)
{
struct gfs2_rbm rbm;
struct gfs2_bitmap *bi, *bi_prev = NULL;
rbm.rgd = rgd;
if (WARN_ON_ONCE(gfs2_rbm_from_block(&rbm, bstart)))
return;
while (blen--) {
bi = rbm_bi(&rbm);
if (bi != bi_prev) {
if (!bi->bi_clone) {
bi->bi_clone = kmalloc(bi->bi_bh->b_size,
GFP_NOFS | __GFP_NOFAIL);
memcpy(bi->bi_clone + bi->bi_offset,
bi->bi_bh->b_data + bi->bi_offset,
bi->bi_bytes);
}
gfs2_trans_add_meta(rbm.rgd->rd_gl, bi->bi_bh);
bi_prev = bi;
}
gfs2_setbit(&rbm, false, new_state);
gfs2_rbm_add(&rbm, 1);
}
}
/**
* gfs2_rgrp_dump - print out an rgrp
* @seq: The iterator
* @rgd: The rgrp in question
* @fs_id_buf: pointer to file system id (if requested)
*
*/
void gfs2_rgrp_dump(struct seq_file *seq, struct gfs2_rgrpd *rgd,
const char *fs_id_buf)
{
struct gfs2_blkreserv *trs;
const struct rb_node *n;
spin_lock(&rgd->rd_rsspin);
gfs2_print_dbg(seq, "%s R: n:%llu f:%02x b:%u/%u i:%u q:%u r:%u e:%u\n",
fs_id_buf,
(unsigned long long)rgd->rd_addr, rgd->rd_flags,
rgd->rd_free, rgd->rd_free_clone, rgd->rd_dinodes,
rgd->rd_requested, rgd->rd_reserved, rgd->rd_extfail_pt);
if (rgd->rd_sbd->sd_args.ar_rgrplvb) {
struct gfs2_rgrp_lvb *rgl = rgd->rd_rgl;
gfs2_print_dbg(seq, "%s L: f:%02x b:%u i:%u\n", fs_id_buf,
be32_to_cpu(rgl->rl_flags),
be32_to_cpu(rgl->rl_free),
be32_to_cpu(rgl->rl_dinodes));
}
for (n = rb_first(&rgd->rd_rstree); n; n = rb_next(&trs->rs_node)) {
trs = rb_entry(n, struct gfs2_blkreserv, rs_node);
dump_rs(seq, trs, fs_id_buf);
}
spin_unlock(&rgd->rd_rsspin);
}
static void gfs2_rgrp_error(struct gfs2_rgrpd *rgd)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
char fs_id_buf[sizeof(sdp->sd_fsname) + 7];
fs_warn(sdp, "rgrp %llu has an error, marking it readonly until umount\n",
(unsigned long long)rgd->rd_addr);
fs_warn(sdp, "umount on all nodes and run fsck.gfs2 to fix the error\n");
sprintf(fs_id_buf, "fsid=%s: ", sdp->sd_fsname);
gfs2_rgrp_dump(NULL, rgd, fs_id_buf);
rgd->rd_flags |= GFS2_RDF_ERROR;
}
/**
* gfs2_adjust_reservation - Adjust (or remove) a reservation after allocation
* @ip: The inode we have just allocated blocks for
* @rbm: The start of the allocated blocks
* @len: The extent length
*
* Adjusts a reservation after an allocation has taken place. If the
* reservation does not match the allocation, or if it is now empty
* then it is removed.
*/
static void gfs2_adjust_reservation(struct gfs2_inode *ip,
const struct gfs2_rbm *rbm, unsigned len)
{
struct gfs2_blkreserv *rs = &ip->i_res;
struct gfs2_rgrpd *rgd = rbm->rgd;
BUG_ON(rs->rs_reserved < len);
rs->rs_reserved -= len;
if (gfs2_rs_active(rs)) {
u64 start = gfs2_rbm_to_block(rbm);
if (rs->rs_start == start) {
unsigned int rlen;
rs->rs_start += len;
rlen = min(rs->rs_requested, len);
rs->rs_requested -= rlen;
rgd->rd_requested -= rlen;
trace_gfs2_rs(rs, TRACE_RS_CLAIM);
if (rs->rs_start < rgd->rd_data0 + rgd->rd_data &&
rs->rs_requested)
return;
/* We used up our block reservation, so we should
reserve more blocks next time. */
atomic_add(RGRP_RSRV_ADDBLKS, &ip->i_sizehint);
}
__rs_deltree(rs);
}
}
/**
* gfs2_set_alloc_start - Set starting point for block allocation
* @rbm: The rbm which will be set to the required location
* @ip: The gfs2 inode
* @dinode: Flag to say if allocation includes a new inode
*
* This sets the starting point from the reservation if one is active
* otherwise it falls back to guessing a start point based on the
* inode's goal block or the last allocation point in the rgrp.
*/
static void gfs2_set_alloc_start(struct gfs2_rbm *rbm,
const struct gfs2_inode *ip, bool dinode)
{
u64 goal;
if (gfs2_rs_active(&ip->i_res)) {
goal = ip->i_res.rs_start;
} else {
if (!dinode && rgrp_contains_block(rbm->rgd, ip->i_goal))
goal = ip->i_goal;
else
goal = rbm->rgd->rd_last_alloc + rbm->rgd->rd_data0;
}
if (WARN_ON_ONCE(gfs2_rbm_from_block(rbm, goal))) {
rbm->bii = 0;
rbm->offset = 0;
}
}
/**
* gfs2_alloc_blocks - Allocate one or more blocks of data and/or a dinode
* @ip: the inode to allocate the block for
* @bn: Used to return the starting block number
* @nblocks: requested number of blocks/extent length (value/result)
* @dinode: 1 if we're allocating a dinode block, else 0
* @generation: the generation number of the inode
*
* Returns: 0 or error
*/
int gfs2_alloc_blocks(struct gfs2_inode *ip, u64 *bn, unsigned int *nblocks,
bool dinode, u64 *generation)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct buffer_head *dibh;
struct gfs2_rbm rbm = { .rgd = ip->i_res.rs_rgd, };
u64 block; /* block, within the file system scope */
u32 minext = 1;
int error = -ENOSPC;
BUG_ON(ip->i_res.rs_reserved < *nblocks);
rgrp_lock_local(rbm.rgd);
if (gfs2_rs_active(&ip->i_res)) {
gfs2_set_alloc_start(&rbm, ip, dinode);
error = gfs2_rbm_find(&rbm, GFS2_BLKST_FREE, &minext, &ip->i_res, false);
}
if (error == -ENOSPC) {
gfs2_set_alloc_start(&rbm, ip, dinode);
error = gfs2_rbm_find(&rbm, GFS2_BLKST_FREE, &minext, NULL, false);
}
/* Since all blocks are reserved in advance, this shouldn't happen */
if (error) {
fs_warn(sdp, "inum=%llu error=%d, nblocks=%u, full=%d fail_pt=%d\n",
(unsigned long long)ip->i_no_addr, error, *nblocks,
test_bit(GBF_FULL, &rbm.rgd->rd_bits->bi_flags),
rbm.rgd->rd_extfail_pt);
goto rgrp_error;
}
gfs2_alloc_extent(&rbm, dinode, nblocks);
block = gfs2_rbm_to_block(&rbm);
rbm.rgd->rd_last_alloc = block - rbm.rgd->rd_data0;
if (!dinode) {
ip->i_goal = block + *nblocks - 1;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error == 0) {
struct gfs2_dinode *di =
(struct gfs2_dinode *)dibh->b_data;
gfs2_trans_add_meta(ip->i_gl, dibh);
di->di_goal_meta = di->di_goal_data =
cpu_to_be64(ip->i_goal);
brelse(dibh);
}
}
spin_lock(&rbm.rgd->rd_rsspin);
gfs2_adjust_reservation(ip, &rbm, *nblocks);
if (rbm.rgd->rd_free < *nblocks || rbm.rgd->rd_reserved < *nblocks) {
fs_warn(sdp, "nblocks=%u\n", *nblocks);
spin_unlock(&rbm.rgd->rd_rsspin);
goto rgrp_error;
}
GLOCK_BUG_ON(rbm.rgd->rd_gl, rbm.rgd->rd_reserved < *nblocks);
GLOCK_BUG_ON(rbm.rgd->rd_gl, rbm.rgd->rd_free_clone < *nblocks);
GLOCK_BUG_ON(rbm.rgd->rd_gl, rbm.rgd->rd_free < *nblocks);
rbm.rgd->rd_reserved -= *nblocks;
rbm.rgd->rd_free_clone -= *nblocks;
rbm.rgd->rd_free -= *nblocks;
spin_unlock(&rbm.rgd->rd_rsspin);
if (dinode) {
rbm.rgd->rd_dinodes++;
*generation = rbm.rgd->rd_igeneration++;
if (*generation == 0)
*generation = rbm.rgd->rd_igeneration++;
}
gfs2_trans_add_meta(rbm.rgd->rd_gl, rbm.rgd->rd_bits[0].bi_bh);
gfs2_rgrp_out(rbm.rgd, rbm.rgd->rd_bits[0].bi_bh->b_data);
rgrp_unlock_local(rbm.rgd);
gfs2_statfs_change(sdp, 0, -(s64)*nblocks, dinode ? 1 : 0);
if (dinode)
gfs2_trans_remove_revoke(sdp, block, *nblocks);
gfs2_quota_change(ip, *nblocks, ip->i_inode.i_uid, ip->i_inode.i_gid);
trace_gfs2_block_alloc(ip, rbm.rgd, block, *nblocks,
dinode ? GFS2_BLKST_DINODE : GFS2_BLKST_USED);
*bn = block;
return 0;
rgrp_error:
rgrp_unlock_local(rbm.rgd);
gfs2_rgrp_error(rbm.rgd);
return -EIO;
}
/**
* __gfs2_free_blocks - free a contiguous run of block(s)
* @ip: the inode these blocks are being freed from
* @rgd: the resource group the blocks are in
* @bstart: first block of a run of contiguous blocks
* @blen: the length of the block run
* @meta: 1 if the blocks represent metadata
*
*/
void __gfs2_free_blocks(struct gfs2_inode *ip, struct gfs2_rgrpd *rgd,
u64 bstart, u32 blen, int meta)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
rgrp_lock_local(rgd);
rgblk_free(sdp, rgd, bstart, blen, GFS2_BLKST_FREE);
trace_gfs2_block_alloc(ip, rgd, bstart, blen, GFS2_BLKST_FREE);
rgd->rd_free += blen;
rgd->rd_flags &= ~GFS2_RGF_TRIMMED;
gfs2_trans_add_meta(rgd->rd_gl, rgd->rd_bits[0].bi_bh);
gfs2_rgrp_out(rgd, rgd->rd_bits[0].bi_bh->b_data);
rgrp_unlock_local(rgd);
/* Directories keep their data in the metadata address space */
if (meta || ip->i_depth || gfs2_is_jdata(ip))
gfs2_journal_wipe(ip, bstart, blen);
}
/**
* gfs2_free_meta - free a contiguous run of data block(s)
* @ip: the inode these blocks are being freed from
* @rgd: the resource group the blocks are in
* @bstart: first block of a run of contiguous blocks
* @blen: the length of the block run
*
*/
void gfs2_free_meta(struct gfs2_inode *ip, struct gfs2_rgrpd *rgd,
u64 bstart, u32 blen)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
__gfs2_free_blocks(ip, rgd, bstart, blen, 1);
gfs2_statfs_change(sdp, 0, +blen, 0);
gfs2_quota_change(ip, -(s64)blen, ip->i_inode.i_uid, ip->i_inode.i_gid);
}
void gfs2_unlink_di(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_rgrpd *rgd;
u64 blkno = ip->i_no_addr;
rgd = gfs2_blk2rgrpd(sdp, blkno, true);
if (!rgd)
return;
rgrp_lock_local(rgd);
rgblk_free(sdp, rgd, blkno, 1, GFS2_BLKST_UNLINKED);
trace_gfs2_block_alloc(ip, rgd, blkno, 1, GFS2_BLKST_UNLINKED);
gfs2_trans_add_meta(rgd->rd_gl, rgd->rd_bits[0].bi_bh);
gfs2_rgrp_out(rgd, rgd->rd_bits[0].bi_bh->b_data);
be32_add_cpu(&rgd->rd_rgl->rl_unlinked, 1);
rgrp_unlock_local(rgd);
}
void gfs2_free_di(struct gfs2_rgrpd *rgd, struct gfs2_inode *ip)
{
struct gfs2_sbd *sdp = rgd->rd_sbd;
rgrp_lock_local(rgd);
rgblk_free(sdp, rgd, ip->i_no_addr, 1, GFS2_BLKST_FREE);
if (!rgd->rd_dinodes)
gfs2_consist_rgrpd(rgd);
rgd->rd_dinodes--;
rgd->rd_free++;
gfs2_trans_add_meta(rgd->rd_gl, rgd->rd_bits[0].bi_bh);
gfs2_rgrp_out(rgd, rgd->rd_bits[0].bi_bh->b_data);
be32_add_cpu(&rgd->rd_rgl->rl_unlinked, -1);
rgrp_unlock_local(rgd);
gfs2_statfs_change(sdp, 0, +1, -1);
trace_gfs2_block_alloc(ip, rgd, ip->i_no_addr, 1, GFS2_BLKST_FREE);
gfs2_quota_change(ip, -1, ip->i_inode.i_uid, ip->i_inode.i_gid);
gfs2_journal_wipe(ip, ip->i_no_addr, 1);
}
/**
* gfs2_check_blk_type - Check the type of a block
* @sdp: The superblock
* @no_addr: The block number to check
* @type: The block type we are looking for
*
* The inode glock of @no_addr must be held. The @type to check for is either
* GFS2_BLKST_DINODE or GFS2_BLKST_UNLINKED; checking for type GFS2_BLKST_FREE
* or GFS2_BLKST_USED would make no sense.
*
* Returns: 0 if the block type matches the expected type
* -ESTALE if it doesn't match
* or -ve errno if something went wrong while checking
*/
int gfs2_check_blk_type(struct gfs2_sbd *sdp, u64 no_addr, unsigned int type)
{
struct gfs2_rgrpd *rgd;
struct gfs2_holder rgd_gh;
struct gfs2_rbm rbm;
int error = -EINVAL;
rgd = gfs2_blk2rgrpd(sdp, no_addr, 1);
if (!rgd)
goto fail;
error = gfs2_glock_nq_init(rgd->rd_gl, LM_ST_SHARED, 0, &rgd_gh);
if (error)
goto fail;
rbm.rgd = rgd;
error = gfs2_rbm_from_block(&rbm, no_addr);
if (!WARN_ON_ONCE(error)) {
/*
* No need to take the local resource group lock here; the
* inode glock of @no_addr provides the necessary
* synchronization in case the block is an inode. (In case
* the block is not an inode, the block type will not match
* the @type we are looking for.)
*/
if (gfs2_testbit(&rbm, false) != type)
error = -ESTALE;
}
gfs2_glock_dq_uninit(&rgd_gh);
fail:
return error;
}
/**
* gfs2_rlist_add - add a RG to a list of RGs
* @ip: the inode
* @rlist: the list of resource groups
* @block: the block
*
* Figure out what RG a block belongs to and add that RG to the list
*
* FIXME: Don't use NOFAIL
*
*/
void gfs2_rlist_add(struct gfs2_inode *ip, struct gfs2_rgrp_list *rlist,
u64 block)
{
struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
struct gfs2_rgrpd *rgd;
struct gfs2_rgrpd **tmp;
unsigned int new_space;
unsigned int x;
if (gfs2_assert_warn(sdp, !rlist->rl_ghs))
return;
/*
* The resource group last accessed is kept in the last position.
*/
if (rlist->rl_rgrps) {
rgd = rlist->rl_rgd[rlist->rl_rgrps - 1];
if (rgrp_contains_block(rgd, block))
return;
rgd = gfs2_blk2rgrpd(sdp, block, 1);
} else {
rgd = ip->i_res.rs_rgd;
if (!rgd || !rgrp_contains_block(rgd, block))
rgd = gfs2_blk2rgrpd(sdp, block, 1);
}
if (!rgd) {
fs_err(sdp, "rlist_add: no rgrp for block %llu\n",
(unsigned long long)block);
return;
}
for (x = 0; x < rlist->rl_rgrps; x++) {
if (rlist->rl_rgd[x] == rgd) {
swap(rlist->rl_rgd[x],
rlist->rl_rgd[rlist->rl_rgrps - 1]);
return;
}
}
if (rlist->rl_rgrps == rlist->rl_space) {
new_space = rlist->rl_space + 10;
tmp = kcalloc(new_space, sizeof(struct gfs2_rgrpd *),
GFP_NOFS | __GFP_NOFAIL);
if (rlist->rl_rgd) {
memcpy(tmp, rlist->rl_rgd,
rlist->rl_space * sizeof(struct gfs2_rgrpd *));
kfree(rlist->rl_rgd);
}
rlist->rl_space = new_space;
rlist->rl_rgd = tmp;
}
rlist->rl_rgd[rlist->rl_rgrps++] = rgd;
}
/**
* gfs2_rlist_alloc - all RGs have been added to the rlist, now allocate
* and initialize an array of glock holders for them
* @rlist: the list of resource groups
* @state: the state we're requesting
* @flags: the modifier flags
*
* FIXME: Don't use NOFAIL
*
*/
void gfs2_rlist_alloc(struct gfs2_rgrp_list *rlist,
unsigned int state, u16 flags)
{
unsigned int x;
rlist->rl_ghs = kmalloc_array(rlist->rl_rgrps,
sizeof(struct gfs2_holder),
GFP_NOFS | __GFP_NOFAIL);
for (x = 0; x < rlist->rl_rgrps; x++)
gfs2_holder_init(rlist->rl_rgd[x]->rd_gl, state, flags,
&rlist->rl_ghs[x]);
}
/**
* gfs2_rlist_free - free a resource group list
* @rlist: the list of resource groups
*
*/
void gfs2_rlist_free(struct gfs2_rgrp_list *rlist)
{
unsigned int x;
kfree(rlist->rl_rgd);
if (rlist->rl_ghs) {
for (x = 0; x < rlist->rl_rgrps; x++)
gfs2_holder_uninit(&rlist->rl_ghs[x]);
kfree(rlist->rl_ghs);
rlist->rl_ghs = NULL;
}
}
void rgrp_lock_local(struct gfs2_rgrpd *rgd)
{
mutex_lock(&rgd->rd_mutex);
}
void rgrp_unlock_local(struct gfs2_rgrpd *rgd)
{
mutex_unlock(&rgd->rd_mutex);
}
| linux-master | fs/gfs2/rgrp.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/mpage.h>
#include <linux/fs.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/gfs2_ondisk.h>
#include <linux/backing-dev.h>
#include <linux/uio.h>
#include <trace/events/writeback.h>
#include <linux/sched/signal.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "trans.h"
#include "rgrp.h"
#include "super.h"
#include "util.h"
#include "glops.h"
#include "aops.h"
void gfs2_trans_add_databufs(struct gfs2_inode *ip, struct folio *folio,
size_t from, size_t len)
{
struct buffer_head *head = folio_buffers(folio);
unsigned int bsize = head->b_size;
struct buffer_head *bh;
size_t to = from + len;
size_t start, end;
for (bh = head, start = 0; bh != head || !start;
bh = bh->b_this_page, start = end) {
end = start + bsize;
if (end <= from)
continue;
if (start >= to)
break;
set_buffer_uptodate(bh);
gfs2_trans_add_data(ip->i_gl, bh);
}
}
/**
* gfs2_get_block_noalloc - Fills in a buffer head with details about a block
* @inode: The inode
* @lblock: The block number to look up
* @bh_result: The buffer head to return the result in
* @create: Non-zero if we may add block to the file
*
* Returns: errno
*/
static int gfs2_get_block_noalloc(struct inode *inode, sector_t lblock,
struct buffer_head *bh_result, int create)
{
int error;
error = gfs2_block_map(inode, lblock, bh_result, 0);
if (error)
return error;
if (!buffer_mapped(bh_result))
return -ENODATA;
return 0;
}
/**
* gfs2_write_jdata_folio - gfs2 jdata-specific version of block_write_full_page
* @folio: The folio to write
* @wbc: The writeback control
*
* This is the same as calling block_write_full_page, but it also
* writes pages outside of i_size
*/
static int gfs2_write_jdata_folio(struct folio *folio,
struct writeback_control *wbc)
{
struct inode * const inode = folio->mapping->host;
loff_t i_size = i_size_read(inode);
/*
* The folio straddles i_size. It must be zeroed out on each and every
* writepage invocation because it may be mmapped. "A file is mapped
* in multiples of the page size. For a file that is not a multiple of
* the page size, the remaining memory is zeroed when mapped, and
* writes to that region are not written out to the file."
*/
if (folio_pos(folio) < i_size &&
i_size < folio_pos(folio) + folio_size(folio))
folio_zero_segment(folio, offset_in_folio(folio, i_size),
folio_size(folio));
return __block_write_full_folio(inode, folio, gfs2_get_block_noalloc,
wbc, end_buffer_async_write);
}
/**
* __gfs2_jdata_write_folio - The core of jdata writepage
* @folio: The folio to write
* @wbc: The writeback control
*
* This is shared between writepage and writepages and implements the
* core of the writepage operation. If a transaction is required then
* the checked flag will have been set and the transaction will have
* already been started before this is called.
*/
static int __gfs2_jdata_write_folio(struct folio *folio,
struct writeback_control *wbc)
{
struct inode *inode = folio->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
if (folio_test_checked(folio)) {
folio_clear_checked(folio);
if (!folio_buffers(folio)) {
folio_create_empty_buffers(folio,
inode->i_sb->s_blocksize,
BIT(BH_Dirty)|BIT(BH_Uptodate));
}
gfs2_trans_add_databufs(ip, folio, 0, folio_size(folio));
}
return gfs2_write_jdata_folio(folio, wbc);
}
/**
* gfs2_jdata_writepage - Write complete page
* @page: Page to write
* @wbc: The writeback control
*
* Returns: errno
*
*/
static int gfs2_jdata_writepage(struct page *page, struct writeback_control *wbc)
{
struct folio *folio = page_folio(page);
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
if (gfs2_assert_withdraw(sdp, gfs2_glock_is_held_excl(ip->i_gl)))
goto out;
if (folio_test_checked(folio) || current->journal_info)
goto out_ignore;
return __gfs2_jdata_write_folio(folio, wbc);
out_ignore:
folio_redirty_for_writepage(wbc, folio);
out:
folio_unlock(folio);
return 0;
}
/**
* gfs2_writepages - Write a bunch of dirty pages back to disk
* @mapping: The mapping to write
* @wbc: Write-back control
*
* Used for both ordered and writeback modes.
*/
static int gfs2_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct gfs2_sbd *sdp = gfs2_mapping2sbd(mapping);
struct iomap_writepage_ctx wpc = { };
int ret;
/*
* Even if we didn't write enough pages here, we might still be holding
* dirty pages in the ail. We forcibly flush the ail because we don't
* want balance_dirty_pages() to loop indefinitely trying to write out
* pages held in the ail that it can't find.
*/
ret = iomap_writepages(mapping, wbc, &wpc, &gfs2_writeback_ops);
if (ret == 0 && wbc->nr_to_write > 0)
set_bit(SDF_FORCE_AIL_FLUSH, &sdp->sd_flags);
return ret;
}
/**
* gfs2_write_jdata_batch - Write back a folio batch's worth of folios
* @mapping: The mapping
* @wbc: The writeback control
* @fbatch: The batch of folios
* @done_index: Page index
*
* Returns: non-zero if loop should terminate, zero otherwise
*/
static int gfs2_write_jdata_batch(struct address_space *mapping,
struct writeback_control *wbc,
struct folio_batch *fbatch,
pgoff_t *done_index)
{
struct inode *inode = mapping->host;
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned nrblocks;
int i;
int ret;
int nr_pages = 0;
int nr_folios = folio_batch_count(fbatch);
for (i = 0; i < nr_folios; i++)
nr_pages += folio_nr_pages(fbatch->folios[i]);
nrblocks = nr_pages * (PAGE_SIZE >> inode->i_blkbits);
ret = gfs2_trans_begin(sdp, nrblocks, nrblocks);
if (ret < 0)
return ret;
for (i = 0; i < nr_folios; i++) {
struct folio *folio = fbatch->folios[i];
*done_index = folio->index;
folio_lock(folio);
if (unlikely(folio->mapping != mapping)) {
continue_unlock:
folio_unlock(folio);
continue;
}
if (!folio_test_dirty(folio)) {
/* someone wrote it for us */
goto continue_unlock;
}
if (folio_test_writeback(folio)) {
if (wbc->sync_mode != WB_SYNC_NONE)
folio_wait_writeback(folio);
else
goto continue_unlock;
}
BUG_ON(folio_test_writeback(folio));
if (!folio_clear_dirty_for_io(folio))
goto continue_unlock;
trace_wbc_writepage(wbc, inode_to_bdi(inode));
ret = __gfs2_jdata_write_folio(folio, wbc);
if (unlikely(ret)) {
if (ret == AOP_WRITEPAGE_ACTIVATE) {
folio_unlock(folio);
ret = 0;
} else {
/*
* done_index is set past this page,
* so media errors will not choke
* background writeout for the entire
* file. This has consequences for
* range_cyclic semantics (ie. it may
* not be suitable for data integrity
* writeout).
*/
*done_index = folio_next_index(folio);
ret = 1;
break;
}
}
/*
* We stop writing back only if we are not doing
* integrity sync. In case of integrity sync we have to
* keep going until we have written all the pages
* we tagged for writeback prior to entering this loop.
*/
if (--wbc->nr_to_write <= 0 && wbc->sync_mode == WB_SYNC_NONE) {
ret = 1;
break;
}
}
gfs2_trans_end(sdp);
return ret;
}
/**
* gfs2_write_cache_jdata - Like write_cache_pages but different
* @mapping: The mapping to write
* @wbc: The writeback control
*
* The reason that we use our own function here is that we need to
* start transactions before we grab page locks. This allows us
* to get the ordering right.
*/
static int gfs2_write_cache_jdata(struct address_space *mapping,
struct writeback_control *wbc)
{
int ret = 0;
int done = 0;
struct folio_batch fbatch;
int nr_folios;
pgoff_t writeback_index;
pgoff_t index;
pgoff_t end;
pgoff_t done_index;
int cycled;
int range_whole = 0;
xa_mark_t tag;
folio_batch_init(&fbatch);
if (wbc->range_cyclic) {
writeback_index = mapping->writeback_index; /* prev offset */
index = writeback_index;
if (index == 0)
cycled = 1;
else
cycled = 0;
end = -1;
} else {
index = wbc->range_start >> PAGE_SHIFT;
end = wbc->range_end >> PAGE_SHIFT;
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
cycled = 1; /* ignore range_cyclic tests */
}
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag = PAGECACHE_TAG_TOWRITE;
else
tag = PAGECACHE_TAG_DIRTY;
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag_pages_for_writeback(mapping, index, end);
done_index = index;
while (!done && (index <= end)) {
nr_folios = filemap_get_folios_tag(mapping, &index, end,
tag, &fbatch);
if (nr_folios == 0)
break;
ret = gfs2_write_jdata_batch(mapping, wbc, &fbatch,
&done_index);
if (ret)
done = 1;
if (ret > 0)
ret = 0;
folio_batch_release(&fbatch);
cond_resched();
}
if (!cycled && !done) {
/*
* range_cyclic:
* We hit the last page and there is more work to be done: wrap
* back to the start of the file
*/
cycled = 1;
index = 0;
end = writeback_index - 1;
goto retry;
}
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
mapping->writeback_index = done_index;
return ret;
}
/**
* gfs2_jdata_writepages - Write a bunch of dirty pages back to disk
* @mapping: The mapping to write
* @wbc: The writeback control
*
*/
static int gfs2_jdata_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(mapping->host);
int ret;
ret = gfs2_write_cache_jdata(mapping, wbc);
if (ret == 0 && wbc->sync_mode == WB_SYNC_ALL) {
gfs2_log_flush(sdp, ip->i_gl, GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_JDATA_WPAGES);
ret = gfs2_write_cache_jdata(mapping, wbc);
}
return ret;
}
/**
* stuffed_readpage - Fill in a Linux page with stuffed file data
* @ip: the inode
* @page: the page
*
* Returns: errno
*/
static int stuffed_readpage(struct gfs2_inode *ip, struct page *page)
{
struct buffer_head *dibh;
u64 dsize = i_size_read(&ip->i_inode);
void *kaddr;
int error;
/*
* Due to the order of unstuffing files and ->fault(), we can be
* asked for a zero page in the case of a stuffed file being extended,
* so we need to supply one here. It doesn't happen often.
*/
if (unlikely(page->index)) {
zero_user(page, 0, PAGE_SIZE);
SetPageUptodate(page);
return 0;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
kaddr = kmap_local_page(page);
memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode), dsize);
memset(kaddr + dsize, 0, PAGE_SIZE - dsize);
kunmap_local(kaddr);
flush_dcache_page(page);
brelse(dibh);
SetPageUptodate(page);
return 0;
}
/**
* gfs2_read_folio - read a folio from a file
* @file: The file to read
* @folio: The folio in the file
*/
static int gfs2_read_folio(struct file *file, struct folio *folio)
{
struct inode *inode = folio->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
int error;
if (!gfs2_is_jdata(ip) ||
(i_blocksize(inode) == PAGE_SIZE && !folio_buffers(folio))) {
error = iomap_read_folio(folio, &gfs2_iomap_ops);
} else if (gfs2_is_stuffed(ip)) {
error = stuffed_readpage(ip, &folio->page);
folio_unlock(folio);
} else {
error = mpage_read_folio(folio, gfs2_block_map);
}
if (unlikely(gfs2_withdrawn(sdp)))
return -EIO;
return error;
}
/**
* gfs2_internal_read - read an internal file
* @ip: The gfs2 inode
* @buf: The buffer to fill
* @pos: The file position
* @size: The amount to read
*
*/
int gfs2_internal_read(struct gfs2_inode *ip, char *buf, loff_t *pos,
unsigned size)
{
struct address_space *mapping = ip->i_inode.i_mapping;
unsigned long index = *pos >> PAGE_SHIFT;
unsigned offset = *pos & (PAGE_SIZE - 1);
unsigned copied = 0;
unsigned amt;
struct page *page;
do {
page = read_cache_page(mapping, index, gfs2_read_folio, NULL);
if (IS_ERR(page)) {
if (PTR_ERR(page) == -EINTR)
continue;
return PTR_ERR(page);
}
amt = size - copied;
if (offset + size > PAGE_SIZE)
amt = PAGE_SIZE - offset;
memcpy_from_page(buf + copied, page, offset, amt);
put_page(page);
copied += amt;
index++;
offset = 0;
} while(copied < size);
(*pos) += size;
return size;
}
/**
* gfs2_readahead - Read a bunch of pages at once
* @rac: Read-ahead control structure
*
* Some notes:
* 1. This is only for readahead, so we can simply ignore any things
* which are slightly inconvenient (such as locking conflicts between
* the page lock and the glock) and return having done no I/O. Its
* obviously not something we'd want to do on too regular a basis.
* Any I/O we ignore at this time will be done via readpage later.
* 2. We don't handle stuffed files here we let readpage do the honours.
* 3. mpage_readahead() does most of the heavy lifting in the common case.
* 4. gfs2_block_map() is relied upon to set BH_Boundary in the right places.
*/
static void gfs2_readahead(struct readahead_control *rac)
{
struct inode *inode = rac->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
if (gfs2_is_stuffed(ip))
;
else if (gfs2_is_jdata(ip))
mpage_readahead(rac, gfs2_block_map);
else
iomap_readahead(rac, &gfs2_iomap_ops);
}
/**
* adjust_fs_space - Adjusts the free space available due to gfs2_grow
* @inode: the rindex inode
*/
void adjust_fs_space(struct inode *inode)
{
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct buffer_head *m_bh;
u64 fs_total, new_free;
if (gfs2_trans_begin(sdp, 2 * RES_STATFS, 0) != 0)
return;
/* Total up the file system space, according to the latest rindex. */
fs_total = gfs2_ri_total(sdp);
if (gfs2_meta_inode_buffer(m_ip, &m_bh) != 0)
goto out;
spin_lock(&sdp->sd_statfs_spin);
gfs2_statfs_change_in(m_sc, m_bh->b_data +
sizeof(struct gfs2_dinode));
if (fs_total > (m_sc->sc_total + l_sc->sc_total))
new_free = fs_total - (m_sc->sc_total + l_sc->sc_total);
else
new_free = 0;
spin_unlock(&sdp->sd_statfs_spin);
fs_warn(sdp, "File system extended by %llu blocks.\n",
(unsigned long long)new_free);
gfs2_statfs_change(sdp, new_free, new_free, 0);
update_statfs(sdp, m_bh);
brelse(m_bh);
out:
sdp->sd_rindex_uptodate = 0;
gfs2_trans_end(sdp);
}
static bool jdata_dirty_folio(struct address_space *mapping,
struct folio *folio)
{
if (current->journal_info)
folio_set_checked(folio);
return block_dirty_folio(mapping, folio);
}
/**
* gfs2_bmap - Block map function
* @mapping: Address space info
* @lblock: The block to map
*
* Returns: The disk address for the block or 0 on hole or error
*/
static sector_t gfs2_bmap(struct address_space *mapping, sector_t lblock)
{
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_holder i_gh;
sector_t dblock = 0;
int error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh);
if (error)
return 0;
if (!gfs2_is_stuffed(ip))
dblock = iomap_bmap(mapping, lblock, &gfs2_iomap_ops);
gfs2_glock_dq_uninit(&i_gh);
return dblock;
}
static void gfs2_discard(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
struct gfs2_bufdata *bd;
lock_buffer(bh);
gfs2_log_lock(sdp);
clear_buffer_dirty(bh);
bd = bh->b_private;
if (bd) {
if (!list_empty(&bd->bd_list) && !buffer_pinned(bh))
list_del_init(&bd->bd_list);
else {
spin_lock(&sdp->sd_ail_lock);
gfs2_remove_from_journal(bh, REMOVE_JDATA);
spin_unlock(&sdp->sd_ail_lock);
}
}
bh->b_bdev = NULL;
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
gfs2_log_unlock(sdp);
unlock_buffer(bh);
}
static void gfs2_invalidate_folio(struct folio *folio, size_t offset,
size_t length)
{
struct gfs2_sbd *sdp = GFS2_SB(folio->mapping->host);
size_t stop = offset + length;
int partial_page = (offset || length < folio_size(folio));
struct buffer_head *bh, *head;
unsigned long pos = 0;
BUG_ON(!folio_test_locked(folio));
if (!partial_page)
folio_clear_checked(folio);
head = folio_buffers(folio);
if (!head)
goto out;
bh = head;
do {
if (pos + bh->b_size > stop)
return;
if (offset <= pos)
gfs2_discard(sdp, bh);
pos += bh->b_size;
bh = bh->b_this_page;
} while (bh != head);
out:
if (!partial_page)
filemap_release_folio(folio, 0);
}
/**
* gfs2_release_folio - free the metadata associated with a folio
* @folio: the folio that's being released
* @gfp_mask: passed from Linux VFS, ignored by us
*
* Calls try_to_free_buffers() to free the buffers and put the folio if the
* buffers can be released.
*
* Returns: true if the folio was put or else false
*/
bool gfs2_release_folio(struct folio *folio, gfp_t gfp_mask)
{
struct address_space *mapping = folio->mapping;
struct gfs2_sbd *sdp = gfs2_mapping2sbd(mapping);
struct buffer_head *bh, *head;
struct gfs2_bufdata *bd;
head = folio_buffers(folio);
if (!head)
return false;
/*
* mm accommodates an old ext3 case where clean folios might
* not have had the dirty bit cleared. Thus, it can send actual
* dirty folios to ->release_folio() via shrink_active_list().
*
* As a workaround, we skip folios that contain dirty buffers
* below. Once ->release_folio isn't called on dirty folios
* anymore, we can warn on dirty buffers like we used to here
* again.
*/
gfs2_log_lock(sdp);
bh = head;
do {
if (atomic_read(&bh->b_count))
goto cannot_release;
bd = bh->b_private;
if (bd && bd->bd_tr)
goto cannot_release;
if (buffer_dirty(bh) || WARN_ON(buffer_pinned(bh)))
goto cannot_release;
bh = bh->b_this_page;
} while (bh != head);
bh = head;
do {
bd = bh->b_private;
if (bd) {
gfs2_assert_warn(sdp, bd->bd_bh == bh);
bd->bd_bh = NULL;
bh->b_private = NULL;
/*
* The bd may still be queued as a revoke, in which
* case we must not dequeue nor free it.
*/
if (!bd->bd_blkno && !list_empty(&bd->bd_list))
list_del_init(&bd->bd_list);
if (list_empty(&bd->bd_list))
kmem_cache_free(gfs2_bufdata_cachep, bd);
}
bh = bh->b_this_page;
} while (bh != head);
gfs2_log_unlock(sdp);
return try_to_free_buffers(folio);
cannot_release:
gfs2_log_unlock(sdp);
return false;
}
static const struct address_space_operations gfs2_aops = {
.writepages = gfs2_writepages,
.read_folio = gfs2_read_folio,
.readahead = gfs2_readahead,
.dirty_folio = iomap_dirty_folio,
.release_folio = iomap_release_folio,
.invalidate_folio = iomap_invalidate_folio,
.bmap = gfs2_bmap,
.migrate_folio = filemap_migrate_folio,
.is_partially_uptodate = iomap_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations gfs2_jdata_aops = {
.writepage = gfs2_jdata_writepage,
.writepages = gfs2_jdata_writepages,
.read_folio = gfs2_read_folio,
.readahead = gfs2_readahead,
.dirty_folio = jdata_dirty_folio,
.bmap = gfs2_bmap,
.invalidate_folio = gfs2_invalidate_folio,
.release_folio = gfs2_release_folio,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
void gfs2_set_aops(struct inode *inode)
{
if (gfs2_is_jdata(GFS2_I(inode)))
inode->i_mapping->a_ops = &gfs2_jdata_aops;
else
inode->i_mapping->a_ops = &gfs2_aops;
}
| linux-master | fs/gfs2/aops.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/gfs2_ondisk.h>
#include <linux/crc32.h>
#include "gfs2.h"
#include "incore.h"
#include "dir.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "super.h"
#include "rgrp.h"
#include "util.h"
#define GFS2_SMALL_FH_SIZE 4
#define GFS2_LARGE_FH_SIZE 8
#define GFS2_OLD_FH_SIZE 10
static int gfs2_encode_fh(struct inode *inode, __u32 *p, int *len,
struct inode *parent)
{
__be32 *fh = (__force __be32 *)p;
struct super_block *sb = inode->i_sb;
struct gfs2_inode *ip = GFS2_I(inode);
if (parent && (*len < GFS2_LARGE_FH_SIZE)) {
*len = GFS2_LARGE_FH_SIZE;
return FILEID_INVALID;
} else if (*len < GFS2_SMALL_FH_SIZE) {
*len = GFS2_SMALL_FH_SIZE;
return FILEID_INVALID;
}
fh[0] = cpu_to_be32(ip->i_no_formal_ino >> 32);
fh[1] = cpu_to_be32(ip->i_no_formal_ino & 0xFFFFFFFF);
fh[2] = cpu_to_be32(ip->i_no_addr >> 32);
fh[3] = cpu_to_be32(ip->i_no_addr & 0xFFFFFFFF);
*len = GFS2_SMALL_FH_SIZE;
if (!parent || inode == d_inode(sb->s_root))
return *len;
ip = GFS2_I(parent);
fh[4] = cpu_to_be32(ip->i_no_formal_ino >> 32);
fh[5] = cpu_to_be32(ip->i_no_formal_ino & 0xFFFFFFFF);
fh[6] = cpu_to_be32(ip->i_no_addr >> 32);
fh[7] = cpu_to_be32(ip->i_no_addr & 0xFFFFFFFF);
*len = GFS2_LARGE_FH_SIZE;
return *len;
}
struct get_name_filldir {
struct dir_context ctx;
struct gfs2_inum_host inum;
char *name;
};
static bool get_name_filldir(struct dir_context *ctx, const char *name,
int length, loff_t offset, u64 inum,
unsigned int type)
{
struct get_name_filldir *gnfd =
container_of(ctx, struct get_name_filldir, ctx);
if (inum != gnfd->inum.no_addr)
return true;
memcpy(gnfd->name, name, length);
gnfd->name[length] = 0;
return false;
}
static int gfs2_get_name(struct dentry *parent, char *name,
struct dentry *child)
{
struct inode *dir = d_inode(parent);
struct inode *inode = d_inode(child);
struct gfs2_inode *dip, *ip;
struct get_name_filldir gnfd = {
.ctx.actor = get_name_filldir,
.name = name
};
struct gfs2_holder gh;
int error;
struct file_ra_state f_ra = { .start = 0 };
if (!dir)
return -EINVAL;
if (!S_ISDIR(dir->i_mode) || !inode)
return -EINVAL;
dip = GFS2_I(dir);
ip = GFS2_I(inode);
*name = 0;
gnfd.inum.no_addr = ip->i_no_addr;
gnfd.inum.no_formal_ino = ip->i_no_formal_ino;
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, &gh);
if (error)
return error;
error = gfs2_dir_read(dir, &gnfd.ctx, &f_ra);
gfs2_glock_dq_uninit(&gh);
if (!error && !*name)
error = -ENOENT;
return error;
}
static struct dentry *gfs2_get_parent(struct dentry *child)
{
return d_obtain_alias(gfs2_lookupi(d_inode(child), &gfs2_qdotdot, 1));
}
static struct dentry *gfs2_get_dentry(struct super_block *sb,
struct gfs2_inum_host *inum)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct inode *inode;
if (!inum->no_formal_ino)
return ERR_PTR(-ESTALE);
inode = gfs2_lookup_by_inum(sdp, inum->no_addr, inum->no_formal_ino,
GFS2_BLKST_DINODE);
if (IS_ERR(inode))
return ERR_CAST(inode);
return d_obtain_alias(inode);
}
static struct dentry *gfs2_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
struct gfs2_inum_host this;
__be32 *fh = (__force __be32 *)fid->raw;
switch (fh_type) {
case GFS2_SMALL_FH_SIZE:
case GFS2_LARGE_FH_SIZE:
case GFS2_OLD_FH_SIZE:
if (fh_len < GFS2_SMALL_FH_SIZE)
return NULL;
this.no_formal_ino = ((u64)be32_to_cpu(fh[0])) << 32;
this.no_formal_ino |= be32_to_cpu(fh[1]);
this.no_addr = ((u64)be32_to_cpu(fh[2])) << 32;
this.no_addr |= be32_to_cpu(fh[3]);
return gfs2_get_dentry(sb, &this);
default:
return NULL;
}
}
static struct dentry *gfs2_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
struct gfs2_inum_host parent;
__be32 *fh = (__force __be32 *)fid->raw;
switch (fh_type) {
case GFS2_LARGE_FH_SIZE:
case GFS2_OLD_FH_SIZE:
if (fh_len < GFS2_LARGE_FH_SIZE)
return NULL;
parent.no_formal_ino = ((u64)be32_to_cpu(fh[4])) << 32;
parent.no_formal_ino |= be32_to_cpu(fh[5]);
parent.no_addr = ((u64)be32_to_cpu(fh[6])) << 32;
parent.no_addr |= be32_to_cpu(fh[7]);
return gfs2_get_dentry(sb, &parent);
default:
return NULL;
}
}
const struct export_operations gfs2_export_ops = {
.encode_fh = gfs2_encode_fh,
.fh_to_dentry = gfs2_fh_to_dentry,
.fh_to_parent = gfs2_fh_to_parent,
.get_name = gfs2_get_name,
.get_parent = gfs2_get_parent,
};
| linux-master | fs/gfs2/export.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/gfs2_ondisk.h>
#include "gfs2.h"
#include "incore.h"
#include "acl.h"
#include "xattr.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
static const char *gfs2_acl_name(int type)
{
switch (type) {
case ACL_TYPE_ACCESS:
return XATTR_POSIX_ACL_ACCESS;
case ACL_TYPE_DEFAULT:
return XATTR_POSIX_ACL_DEFAULT;
}
return NULL;
}
static struct posix_acl *__gfs2_get_acl(struct inode *inode, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct posix_acl *acl;
const char *name;
char *data;
int len;
if (!ip->i_eattr)
return NULL;
name = gfs2_acl_name(type);
len = gfs2_xattr_acl_get(ip, name, &data);
if (len <= 0)
return ERR_PTR(len);
acl = posix_acl_from_xattr(&init_user_ns, data, len);
kfree(data);
return acl;
}
struct posix_acl *gfs2_get_acl(struct inode *inode, int type, bool rcu)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
struct posix_acl *acl;
if (rcu)
return ERR_PTR(-ECHILD);
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
int ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED,
LM_FLAG_ANY, &gh);
if (ret)
return ERR_PTR(ret);
need_unlock = true;
}
acl = __gfs2_get_acl(inode, type);
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
return acl;
}
int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
size_t len;
char *data;
const char *name = gfs2_acl_name(type);
if (acl) {
len = posix_acl_xattr_size(acl->a_count);
data = kmalloc(len, GFP_NOFS);
if (data == NULL)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, data, len);
if (error < 0)
goto out;
} else {
data = NULL;
len = 0;
}
error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);
if (error)
goto out;
set_cached_acl(inode, type, acl);
out:
kfree(data);
return error;
}
int gfs2_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
struct posix_acl *acl, int type)
{
struct inode *inode = d_inode(dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
int ret;
umode_t mode;
if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))
return -E2BIG;
ret = gfs2_qa_get(ip);
if (ret)
return ret;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (ret)
goto out;
need_unlock = true;
}
mode = inode->i_mode;
if (type == ACL_TYPE_ACCESS && acl) {
ret = posix_acl_update_mode(&nop_mnt_idmap, inode, &mode, &acl);
if (ret)
goto unlock;
}
ret = __gfs2_set_acl(inode, acl, type);
if (!ret && mode != inode->i_mode) {
inode_set_ctime_current(inode);
inode->i_mode = mode;
mark_inode_dirty(inode);
}
unlock:
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
out:
gfs2_qa_put(ip);
return ret;
}
| linux-master | fs/gfs2/acl.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/uio.h>
#include <linux/blkdev.h>
#include <linux/mm.h>
#include <linux/mount.h>
#include <linux/fs.h>
#include <linux/filelock.h>
#include <linux/gfs2_ondisk.h>
#include <linux/falloc.h>
#include <linux/swap.h>
#include <linux/crc32.h>
#include <linux/writeback.h>
#include <linux/uaccess.h>
#include <linux/dlm.h>
#include <linux/dlm_plock.h>
#include <linux/delay.h>
#include <linux/backing-dev.h>
#include <linux/fileattr.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "aops.h"
#include "dir.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
/**
* gfs2_llseek - seek to a location in a file
* @file: the file
* @offset: the offset
* @whence: Where to seek from (SEEK_SET, SEEK_CUR, or SEEK_END)
*
* SEEK_END requires the glock for the file because it references the
* file's size.
*
* Returns: The new offset, or errno
*/
static loff_t gfs2_llseek(struct file *file, loff_t offset, int whence)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_holder i_gh;
loff_t error;
switch (whence) {
case SEEK_END:
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (!error) {
error = generic_file_llseek(file, offset, whence);
gfs2_glock_dq_uninit(&i_gh);
}
break;
case SEEK_DATA:
error = gfs2_seek_data(file, offset);
break;
case SEEK_HOLE:
error = gfs2_seek_hole(file, offset);
break;
case SEEK_CUR:
case SEEK_SET:
/*
* These don't reference inode->i_size and don't depend on the
* block mapping, so we don't need the glock.
*/
error = generic_file_llseek(file, offset, whence);
break;
default:
error = -EINVAL;
}
return error;
}
/**
* gfs2_readdir - Iterator for a directory
* @file: The directory to read from
* @ctx: What to feed directory entries to
*
* Returns: errno
*/
static int gfs2_readdir(struct file *file, struct dir_context *ctx)
{
struct inode *dir = file->f_mapping->host;
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_holder d_gh;
int error;
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
if (error)
return error;
error = gfs2_dir_read(dir, ctx, &file->f_ra);
gfs2_glock_dq_uninit(&d_gh);
return error;
}
/*
* struct fsflag_gfs2flag
*
* The FS_JOURNAL_DATA_FL flag maps to GFS2_DIF_INHERIT_JDATA for directories,
* and to GFS2_DIF_JDATA for non-directories.
*/
static struct {
u32 fsflag;
u32 gfsflag;
} fsflag_gfs2flag[] = {
{FS_SYNC_FL, GFS2_DIF_SYNC},
{FS_IMMUTABLE_FL, GFS2_DIF_IMMUTABLE},
{FS_APPEND_FL, GFS2_DIF_APPENDONLY},
{FS_NOATIME_FL, GFS2_DIF_NOATIME},
{FS_INDEX_FL, GFS2_DIF_EXHASH},
{FS_TOPDIR_FL, GFS2_DIF_TOPDIR},
{FS_JOURNAL_DATA_FL, GFS2_DIF_JDATA | GFS2_DIF_INHERIT_JDATA},
};
static inline u32 gfs2_gfsflags_to_fsflags(struct inode *inode, u32 gfsflags)
{
int i;
u32 fsflags = 0;
if (S_ISDIR(inode->i_mode))
gfsflags &= ~GFS2_DIF_JDATA;
else
gfsflags &= ~GFS2_DIF_INHERIT_JDATA;
for (i = 0; i < ARRAY_SIZE(fsflag_gfs2flag); i++)
if (gfsflags & fsflag_gfs2flag[i].gfsflag)
fsflags |= fsflag_gfs2flag[i].fsflag;
return fsflags;
}
int gfs2_fileattr_get(struct dentry *dentry, struct fileattr *fa)
{
struct inode *inode = d_inode(dentry);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int error;
u32 fsflags;
if (d_is_special(dentry))
return -ENOTTY;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
error = gfs2_glock_nq(&gh);
if (error)
goto out_uninit;
fsflags = gfs2_gfsflags_to_fsflags(inode, ip->i_diskflags);
fileattr_fill_flags(fa, fsflags);
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
return error;
}
void gfs2_set_inode_flags(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int flags = inode->i_flags;
flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_NOSEC);
if ((ip->i_eattr == 0) && !is_sxid(inode->i_mode))
flags |= S_NOSEC;
if (ip->i_diskflags & GFS2_DIF_IMMUTABLE)
flags |= S_IMMUTABLE;
if (ip->i_diskflags & GFS2_DIF_APPENDONLY)
flags |= S_APPEND;
if (ip->i_diskflags & GFS2_DIF_NOATIME)
flags |= S_NOATIME;
if (ip->i_diskflags & GFS2_DIF_SYNC)
flags |= S_SYNC;
inode->i_flags = flags;
}
/* Flags that can be set by user space */
#define GFS2_FLAGS_USER_SET (GFS2_DIF_JDATA| \
GFS2_DIF_IMMUTABLE| \
GFS2_DIF_APPENDONLY| \
GFS2_DIF_NOATIME| \
GFS2_DIF_SYNC| \
GFS2_DIF_TOPDIR| \
GFS2_DIF_INHERIT_JDATA)
/**
* do_gfs2_set_flags - set flags on an inode
* @inode: The inode
* @reqflags: The flags to set
* @mask: Indicates which flags are valid
*
*/
static int do_gfs2_set_flags(struct inode *inode, u32 reqflags, u32 mask)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *bh;
struct gfs2_holder gh;
int error;
u32 new_flags, flags;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (error)
return error;
error = 0;
flags = ip->i_diskflags;
new_flags = (flags & ~mask) | (reqflags & mask);
if ((new_flags ^ flags) == 0)
goto out;
if (!IS_IMMUTABLE(inode)) {
error = gfs2_permission(&nop_mnt_idmap, inode, MAY_WRITE);
if (error)
goto out;
}
if ((flags ^ new_flags) & GFS2_DIF_JDATA) {
if (new_flags & GFS2_DIF_JDATA)
gfs2_log_flush(sdp, ip->i_gl,
GFS2_LOG_HEAD_FLUSH_NORMAL |
GFS2_LFC_SET_FLAGS);
error = filemap_fdatawrite(inode->i_mapping);
if (error)
goto out;
error = filemap_fdatawait(inode->i_mapping);
if (error)
goto out;
if (new_flags & GFS2_DIF_JDATA)
gfs2_ordered_del_inode(ip);
}
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
goto out;
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
goto out_trans_end;
inode_set_ctime_current(inode);
gfs2_trans_add_meta(ip->i_gl, bh);
ip->i_diskflags = new_flags;
gfs2_dinode_out(ip, bh->b_data);
brelse(bh);
gfs2_set_inode_flags(inode);
gfs2_set_aops(inode);
out_trans_end:
gfs2_trans_end(sdp);
out:
gfs2_glock_dq_uninit(&gh);
return error;
}
int gfs2_fileattr_set(struct mnt_idmap *idmap,
struct dentry *dentry, struct fileattr *fa)
{
struct inode *inode = d_inode(dentry);
u32 fsflags = fa->flags, gfsflags = 0;
u32 mask;
int i;
if (d_is_special(dentry))
return -ENOTTY;
if (fileattr_has_fsx(fa))
return -EOPNOTSUPP;
for (i = 0; i < ARRAY_SIZE(fsflag_gfs2flag); i++) {
if (fsflags & fsflag_gfs2flag[i].fsflag) {
fsflags &= ~fsflag_gfs2flag[i].fsflag;
gfsflags |= fsflag_gfs2flag[i].gfsflag;
}
}
if (fsflags || gfsflags & ~GFS2_FLAGS_USER_SET)
return -EINVAL;
mask = GFS2_FLAGS_USER_SET;
if (S_ISDIR(inode->i_mode)) {
mask &= ~GFS2_DIF_JDATA;
} else {
/* The GFS2_DIF_TOPDIR flag is only valid for directories. */
if (gfsflags & GFS2_DIF_TOPDIR)
return -EINVAL;
mask &= ~(GFS2_DIF_TOPDIR | GFS2_DIF_INHERIT_JDATA);
}
return do_gfs2_set_flags(inode, gfsflags, mask);
}
static int gfs2_getlabel(struct file *filp, char __user *label)
{
struct inode *inode = file_inode(filp);
struct gfs2_sbd *sdp = GFS2_SB(inode);
if (copy_to_user(label, sdp->sd_sb.sb_locktable, GFS2_LOCKNAME_LEN))
return -EFAULT;
return 0;
}
static long gfs2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
switch(cmd) {
case FITRIM:
return gfs2_fitrim(filp, (void __user *)arg);
case FS_IOC_GETFSLABEL:
return gfs2_getlabel(filp, (char __user *)arg);
}
return -ENOTTY;
}
#ifdef CONFIG_COMPAT
static long gfs2_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
switch(cmd) {
/* Keep this list in sync with gfs2_ioctl */
case FITRIM:
case FS_IOC_GETFSLABEL:
break;
default:
return -ENOIOCTLCMD;
}
return gfs2_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
}
#else
#define gfs2_compat_ioctl NULL
#endif
/**
* gfs2_size_hint - Give a hint to the size of a write request
* @filep: The struct file
* @offset: The file offset of the write
* @size: The length of the write
*
* When we are about to do a write, this function records the total
* write size in order to provide a suitable hint to the lower layers
* about how many blocks will be required.
*
*/
static void gfs2_size_hint(struct file *filep, loff_t offset, size_t size)
{
struct inode *inode = file_inode(filep);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
size_t blks = (size + sdp->sd_sb.sb_bsize - 1) >> sdp->sd_sb.sb_bsize_shift;
int hint = min_t(size_t, INT_MAX, blks);
if (hint > atomic_read(&ip->i_sizehint))
atomic_set(&ip->i_sizehint, hint);
}
/**
* gfs2_allocate_page_backing - Allocate blocks for a write fault
* @page: The (locked) page to allocate backing for
* @length: Size of the allocation
*
* We try to allocate all the blocks required for the page in one go. This
* might fail for various reasons, so we keep trying until all the blocks to
* back this page are allocated. If some of the blocks are already allocated,
* that is ok too.
*/
static int gfs2_allocate_page_backing(struct page *page, unsigned int length)
{
u64 pos = page_offset(page);
do {
struct iomap iomap = { };
if (gfs2_iomap_alloc(page->mapping->host, pos, length, &iomap))
return -EIO;
if (length < iomap.length)
iomap.length = length;
length -= iomap.length;
pos += iomap.length;
} while (length > 0);
return 0;
}
/**
* gfs2_page_mkwrite - Make a shared, mmap()ed, page writable
* @vmf: The virtual memory fault containing the page to become writable
*
* When the page becomes writable, we need to ensure that we have
* blocks allocated on disk to back that page.
*/
static vm_fault_t gfs2_page_mkwrite(struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = file_inode(vmf->vma->vm_file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_alloc_parms ap = { .aflags = 0, };
u64 offset = page_offset(page);
unsigned int data_blocks, ind_blocks, rblocks;
vm_fault_t ret = VM_FAULT_LOCKED;
struct gfs2_holder gh;
unsigned int length;
loff_t size;
int err;
sb_start_pagefault(inode->i_sb);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
err = gfs2_glock_nq(&gh);
if (err) {
ret = vmf_fs_error(err);
goto out_uninit;
}
/* Check page index against inode size */
size = i_size_read(inode);
if (offset >= size) {
ret = VM_FAULT_SIGBUS;
goto out_unlock;
}
/* Update file times before taking page lock */
file_update_time(vmf->vma->vm_file);
/* page is wholly or partially inside EOF */
if (size - offset < PAGE_SIZE)
length = size - offset;
else
length = PAGE_SIZE;
gfs2_size_hint(vmf->vma->vm_file, offset, length);
set_bit(GLF_DIRTY, &ip->i_gl->gl_flags);
set_bit(GIF_SW_PAGED, &ip->i_flags);
/*
* iomap_writepage / iomap_writepages currently don't support inline
* files, so always unstuff here.
*/
if (!gfs2_is_stuffed(ip) &&
!gfs2_write_alloc_required(ip, offset, length)) {
lock_page(page);
if (!PageUptodate(page) || page->mapping != inode->i_mapping) {
ret = VM_FAULT_NOPAGE;
unlock_page(page);
}
goto out_unlock;
}
err = gfs2_rindex_update(sdp);
if (err) {
ret = vmf_fs_error(err);
goto out_unlock;
}
gfs2_write_calc_reserv(ip, length, &data_blocks, &ind_blocks);
ap.target = data_blocks + ind_blocks;
err = gfs2_quota_lock_check(ip, &ap);
if (err) {
ret = vmf_fs_error(err);
goto out_unlock;
}
err = gfs2_inplace_reserve(ip, &ap);
if (err) {
ret = vmf_fs_error(err);
goto out_quota_unlock;
}
rblocks = RES_DINODE + ind_blocks;
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
if (ind_blocks || data_blocks) {
rblocks += RES_STATFS + RES_QUOTA;
rblocks += gfs2_rg_blocks(ip, data_blocks + ind_blocks);
}
err = gfs2_trans_begin(sdp, rblocks, 0);
if (err) {
ret = vmf_fs_error(err);
goto out_trans_fail;
}
/* Unstuff, if required, and allocate backing blocks for page */
if (gfs2_is_stuffed(ip)) {
err = gfs2_unstuff_dinode(ip);
if (err) {
ret = vmf_fs_error(err);
goto out_trans_end;
}
}
lock_page(page);
/* If truncated, we must retry the operation, we may have raced
* with the glock demotion code.
*/
if (!PageUptodate(page) || page->mapping != inode->i_mapping) {
ret = VM_FAULT_NOPAGE;
goto out_page_locked;
}
err = gfs2_allocate_page_backing(page, length);
if (err)
ret = vmf_fs_error(err);
out_page_locked:
if (ret != VM_FAULT_LOCKED)
unlock_page(page);
out_trans_end:
gfs2_trans_end(sdp);
out_trans_fail:
gfs2_inplace_release(ip);
out_quota_unlock:
gfs2_quota_unlock(ip);
out_unlock:
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
if (ret == VM_FAULT_LOCKED) {
set_page_dirty(page);
wait_for_stable_page(page);
}
sb_end_pagefault(inode->i_sb);
return ret;
}
static vm_fault_t gfs2_fault(struct vm_fault *vmf)
{
struct inode *inode = file_inode(vmf->vma->vm_file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
vm_fault_t ret;
int err;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
err = gfs2_glock_nq(&gh);
if (err) {
ret = vmf_fs_error(err);
goto out_uninit;
}
ret = filemap_fault(vmf);
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
return ret;
}
static const struct vm_operations_struct gfs2_vm_ops = {
.fault = gfs2_fault,
.map_pages = filemap_map_pages,
.page_mkwrite = gfs2_page_mkwrite,
};
/**
* gfs2_mmap
* @file: The file to map
* @vma: The VMA which described the mapping
*
* There is no need to get a lock here unless we should be updating
* atime. We ignore any locking errors since the only consequence is
* a missed atime update (which will just be deferred until later).
*
* Returns: 0
*/
static int gfs2_mmap(struct file *file, struct vm_area_struct *vma)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
if (!(file->f_flags & O_NOATIME) &&
!IS_NOATIME(&ip->i_inode)) {
struct gfs2_holder i_gh;
int error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
return error;
/* grab lock to update inode */
gfs2_glock_dq_uninit(&i_gh);
file_accessed(file);
}
vma->vm_ops = &gfs2_vm_ops;
return 0;
}
/**
* gfs2_open_common - This is common to open and atomic_open
* @inode: The inode being opened
* @file: The file being opened
*
* This maybe called under a glock or not depending upon how it has
* been called. We must always be called under a glock for regular
* files, however. For other file types, it does not matter whether
* we hold the glock or not.
*
* Returns: Error code or 0 for success
*/
int gfs2_open_common(struct inode *inode, struct file *file)
{
struct gfs2_file *fp;
int ret;
if (S_ISREG(inode->i_mode)) {
ret = generic_file_open(inode, file);
if (ret)
return ret;
if (!gfs2_is_jdata(GFS2_I(inode)))
file->f_mode |= FMODE_CAN_ODIRECT;
}
fp = kzalloc(sizeof(struct gfs2_file), GFP_NOFS);
if (!fp)
return -ENOMEM;
mutex_init(&fp->f_fl_mutex);
gfs2_assert_warn(GFS2_SB(inode), !file->private_data);
file->private_data = fp;
if (file->f_mode & FMODE_WRITE) {
ret = gfs2_qa_get(GFS2_I(inode));
if (ret)
goto fail;
}
return 0;
fail:
kfree(file->private_data);
file->private_data = NULL;
return ret;
}
/**
* gfs2_open - open a file
* @inode: the inode to open
* @file: the struct file for this opening
*
* After atomic_open, this function is only used for opening files
* which are already cached. We must still get the glock for regular
* files to ensure that we have the file size uptodate for the large
* file check which is in the common code. That is only an issue for
* regular files though.
*
* Returns: errno
*/
static int gfs2_open(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
int error;
bool need_unlock = false;
if (S_ISREG(ip->i_inode.i_mode)) {
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
return error;
need_unlock = true;
}
error = gfs2_open_common(inode, file);
if (need_unlock)
gfs2_glock_dq_uninit(&i_gh);
return error;
}
/**
* gfs2_release - called to close a struct file
* @inode: the inode the struct file belongs to
* @file: the struct file being closed
*
* Returns: errno
*/
static int gfs2_release(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
kfree(file->private_data);
file->private_data = NULL;
if (file->f_mode & FMODE_WRITE) {
if (gfs2_rs_active(&ip->i_res))
gfs2_rs_delete(ip);
gfs2_qa_put(ip);
}
return 0;
}
/**
* gfs2_fsync - sync the dirty data for a file (across the cluster)
* @file: the file that points to the dentry
* @start: the start position in the file to sync
* @end: the end position in the file to sync
* @datasync: set if we can ignore timestamp changes
*
* We split the data flushing here so that we don't wait for the data
* until after we've also sent the metadata to disk. Note that for
* data=ordered, we will write & wait for the data at the log flush
* stage anyway, so this is unlikely to make much of a difference
* except in the data=writeback case.
*
* If the fdatawrite fails due to any reason except -EIO, we will
* continue the remainder of the fsync, although we'll still report
* the error at the end. This is to match filemap_write_and_wait_range()
* behaviour.
*
* Returns: errno
*/
static int gfs2_fsync(struct file *file, loff_t start, loff_t end,
int datasync)
{
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
int sync_state = inode->i_state & I_DIRTY;
struct gfs2_inode *ip = GFS2_I(inode);
int ret = 0, ret1 = 0;
if (mapping->nrpages) {
ret1 = filemap_fdatawrite_range(mapping, start, end);
if (ret1 == -EIO)
return ret1;
}
if (!gfs2_is_jdata(ip))
sync_state &= ~I_DIRTY_PAGES;
if (datasync)
sync_state &= ~I_DIRTY_SYNC;
if (sync_state) {
ret = sync_inode_metadata(inode, 1);
if (ret)
return ret;
if (gfs2_is_jdata(ip))
ret = file_write_and_wait(file);
if (ret)
return ret;
gfs2_ail_flush(ip->i_gl, 1);
}
if (mapping->nrpages)
ret = file_fdatawait_range(file, start, end);
return ret ? ret : ret1;
}
static inline bool should_fault_in_pages(struct iov_iter *i,
struct kiocb *iocb,
size_t *prev_count,
size_t *window_size)
{
size_t count = iov_iter_count(i);
size_t size, offs;
if (!count)
return false;
if (!user_backed_iter(i))
return false;
/*
* Try to fault in multiple pages initially. When that doesn't result
* in any progress, fall back to a single page.
*/
size = PAGE_SIZE;
offs = offset_in_page(iocb->ki_pos);
if (*prev_count != count) {
size_t nr_dirtied;
nr_dirtied = max(current->nr_dirtied_pause -
current->nr_dirtied, 8);
size = min_t(size_t, SZ_1M, nr_dirtied << PAGE_SHIFT);
}
*prev_count = count;
*window_size = size - offs;
return true;
}
static ssize_t gfs2_file_direct_read(struct kiocb *iocb, struct iov_iter *to,
struct gfs2_holder *gh)
{
struct file *file = iocb->ki_filp;
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
size_t prev_count = 0, window_size = 0;
size_t read = 0;
ssize_t ret;
/*
* In this function, we disable page faults when we're holding the
* inode glock while doing I/O. If a page fault occurs, we indicate
* that the inode glock may be dropped, fault in the pages manually,
* and retry.
*
* Unlike generic_file_read_iter, for reads, iomap_dio_rw can trigger
* physical as well as manual page faults, and we need to disable both
* kinds.
*
* For direct I/O, gfs2 takes the inode glock in deferred mode. This
* locking mode is compatible with other deferred holders, so multiple
* processes and nodes can do direct I/O to a file at the same time.
* There's no guarantee that reads or writes will be atomic. Any
* coordination among readers and writers needs to happen externally.
*/
if (!iov_iter_count(to))
return 0; /* skip atime */
gfs2_holder_init(ip->i_gl, LM_ST_DEFERRED, 0, gh);
retry:
ret = gfs2_glock_nq(gh);
if (ret)
goto out_uninit;
pagefault_disable();
to->nofault = true;
ret = iomap_dio_rw(iocb, to, &gfs2_iomap_ops, NULL,
IOMAP_DIO_PARTIAL, NULL, read);
to->nofault = false;
pagefault_enable();
if (ret <= 0 && ret != -EFAULT)
goto out_unlock;
/* No increment (+=) because iomap_dio_rw returns a cumulative value. */
if (ret > 0)
read = ret;
if (should_fault_in_pages(to, iocb, &prev_count, &window_size)) {
gfs2_glock_dq(gh);
window_size -= fault_in_iov_iter_writeable(to, window_size);
if (window_size)
goto retry;
}
out_unlock:
if (gfs2_holder_queued(gh))
gfs2_glock_dq(gh);
out_uninit:
gfs2_holder_uninit(gh);
/* User space doesn't expect partial success. */
if (ret < 0)
return ret;
return read;
}
static ssize_t gfs2_file_direct_write(struct kiocb *iocb, struct iov_iter *from,
struct gfs2_holder *gh)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
size_t prev_count = 0, window_size = 0;
size_t written = 0;
bool enough_retries;
ssize_t ret;
/*
* In this function, we disable page faults when we're holding the
* inode glock while doing I/O. If a page fault occurs, we indicate
* that the inode glock may be dropped, fault in the pages manually,
* and retry.
*
* For writes, iomap_dio_rw only triggers manual page faults, so we
* don't need to disable physical ones.
*/
/*
* Deferred lock, even if its a write, since we do no allocation on
* this path. All we need to change is the atime, and this lock mode
* ensures that other nodes have flushed their buffered read caches
* (i.e. their page cache entries for this inode). We do not,
* unfortunately, have the option of only flushing a range like the
* VFS does.
*/
gfs2_holder_init(ip->i_gl, LM_ST_DEFERRED, 0, gh);
retry:
ret = gfs2_glock_nq(gh);
if (ret)
goto out_uninit;
/* Silently fall back to buffered I/O when writing beyond EOF */
if (iocb->ki_pos + iov_iter_count(from) > i_size_read(&ip->i_inode))
goto out_unlock;
from->nofault = true;
ret = iomap_dio_rw(iocb, from, &gfs2_iomap_ops, NULL,
IOMAP_DIO_PARTIAL, NULL, written);
from->nofault = false;
if (ret <= 0) {
if (ret == -ENOTBLK)
ret = 0;
if (ret != -EFAULT)
goto out_unlock;
}
/* No increment (+=) because iomap_dio_rw returns a cumulative value. */
if (ret > 0)
written = ret;
enough_retries = prev_count == iov_iter_count(from) &&
window_size <= PAGE_SIZE;
if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
gfs2_glock_dq(gh);
window_size -= fault_in_iov_iter_readable(from, window_size);
if (window_size) {
if (!enough_retries)
goto retry;
/* fall back to buffered I/O */
ret = 0;
}
}
out_unlock:
if (gfs2_holder_queued(gh))
gfs2_glock_dq(gh);
out_uninit:
gfs2_holder_uninit(gh);
/* User space doesn't expect partial success. */
if (ret < 0)
return ret;
return written;
}
static ssize_t gfs2_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct gfs2_inode *ip;
struct gfs2_holder gh;
size_t prev_count = 0, window_size = 0;
size_t read = 0;
ssize_t ret;
/*
* In this function, we disable page faults when we're holding the
* inode glock while doing I/O. If a page fault occurs, we indicate
* that the inode glock may be dropped, fault in the pages manually,
* and retry.
*/
if (iocb->ki_flags & IOCB_DIRECT)
return gfs2_file_direct_read(iocb, to, &gh);
pagefault_disable();
iocb->ki_flags |= IOCB_NOIO;
ret = generic_file_read_iter(iocb, to);
iocb->ki_flags &= ~IOCB_NOIO;
pagefault_enable();
if (ret >= 0) {
if (!iov_iter_count(to))
return ret;
read = ret;
} else if (ret != -EFAULT) {
if (ret != -EAGAIN)
return ret;
if (iocb->ki_flags & IOCB_NOWAIT)
return ret;
}
ip = GFS2_I(iocb->ki_filp->f_mapping->host);
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
retry:
ret = gfs2_glock_nq(&gh);
if (ret)
goto out_uninit;
pagefault_disable();
ret = generic_file_read_iter(iocb, to);
pagefault_enable();
if (ret <= 0 && ret != -EFAULT)
goto out_unlock;
if (ret > 0)
read += ret;
if (should_fault_in_pages(to, iocb, &prev_count, &window_size)) {
gfs2_glock_dq(&gh);
window_size -= fault_in_iov_iter_writeable(to, window_size);
if (window_size)
goto retry;
}
out_unlock:
if (gfs2_holder_queued(&gh))
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
return read ? read : ret;
}
static ssize_t gfs2_file_buffered_write(struct kiocb *iocb,
struct iov_iter *from,
struct gfs2_holder *gh)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file_inode(file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_holder *statfs_gh = NULL;
size_t prev_count = 0, window_size = 0;
size_t orig_count = iov_iter_count(from);
size_t written = 0;
ssize_t ret;
/*
* In this function, we disable page faults when we're holding the
* inode glock while doing I/O. If a page fault occurs, we indicate
* that the inode glock may be dropped, fault in the pages manually,
* and retry.
*/
if (inode == sdp->sd_rindex) {
statfs_gh = kmalloc(sizeof(*statfs_gh), GFP_NOFS);
if (!statfs_gh)
return -ENOMEM;
}
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, gh);
if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
retry:
window_size -= fault_in_iov_iter_readable(from, window_size);
if (!window_size) {
ret = -EFAULT;
goto out_uninit;
}
from->count = min(from->count, window_size);
}
ret = gfs2_glock_nq(gh);
if (ret)
goto out_uninit;
if (inode == sdp->sd_rindex) {
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
ret = gfs2_glock_nq_init(m_ip->i_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, statfs_gh);
if (ret)
goto out_unlock;
}
pagefault_disable();
ret = iomap_file_buffered_write(iocb, from, &gfs2_iomap_ops);
pagefault_enable();
if (ret > 0)
written += ret;
if (inode == sdp->sd_rindex)
gfs2_glock_dq_uninit(statfs_gh);
if (ret <= 0 && ret != -EFAULT)
goto out_unlock;
from->count = orig_count - written;
if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
gfs2_glock_dq(gh);
goto retry;
}
out_unlock:
if (gfs2_holder_queued(gh))
gfs2_glock_dq(gh);
out_uninit:
gfs2_holder_uninit(gh);
kfree(statfs_gh);
from->count = orig_count - written;
return written ? written : ret;
}
/**
* gfs2_file_write_iter - Perform a write to a file
* @iocb: The io context
* @from: The data to write
*
* We have to do a lock/unlock here to refresh the inode size for
* O_APPEND writes, otherwise we can land up writing at the wrong
* offset. There is still a race, but provided the app is using its
* own file locking, this will make O_APPEND work as expected.
*
*/
static ssize_t gfs2_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file_inode(file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
ssize_t ret;
gfs2_size_hint(file, iocb->ki_pos, iov_iter_count(from));
if (iocb->ki_flags & IOCB_APPEND) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (ret)
return ret;
gfs2_glock_dq_uninit(&gh);
}
inode_lock(inode);
ret = generic_write_checks(iocb, from);
if (ret <= 0)
goto out_unlock;
ret = file_remove_privs(file);
if (ret)
goto out_unlock;
ret = file_update_time(file);
if (ret)
goto out_unlock;
if (iocb->ki_flags & IOCB_DIRECT) {
struct address_space *mapping = file->f_mapping;
ssize_t buffered, ret2;
ret = gfs2_file_direct_write(iocb, from, &gh);
if (ret < 0 || !iov_iter_count(from))
goto out_unlock;
iocb->ki_flags |= IOCB_DSYNC;
buffered = gfs2_file_buffered_write(iocb, from, &gh);
if (unlikely(buffered <= 0)) {
if (!ret)
ret = buffered;
goto out_unlock;
}
/*
* We need to ensure that the page cache pages are written to
* disk and invalidated to preserve the expected O_DIRECT
* semantics. If the writeback or invalidate fails, only report
* the direct I/O range as we don't know if the buffered pages
* made it to disk.
*/
ret2 = generic_write_sync(iocb, buffered);
invalidate_mapping_pages(mapping,
(iocb->ki_pos - buffered) >> PAGE_SHIFT,
(iocb->ki_pos - 1) >> PAGE_SHIFT);
if (!ret || ret2 > 0)
ret += ret2;
} else {
ret = gfs2_file_buffered_write(iocb, from, &gh);
if (likely(ret > 0))
ret = generic_write_sync(iocb, ret);
}
out_unlock:
inode_unlock(inode);
return ret;
}
static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,
int mode)
{
struct super_block *sb = inode->i_sb;
struct gfs2_inode *ip = GFS2_I(inode);
loff_t end = offset + len;
struct buffer_head *dibh;
int error;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(error))
return error;
gfs2_trans_add_meta(ip->i_gl, dibh);
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip);
if (unlikely(error))
goto out;
}
while (offset < end) {
struct iomap iomap = { };
error = gfs2_iomap_alloc(inode, offset, end - offset, &iomap);
if (error)
goto out;
offset = iomap.offset + iomap.length;
if (!(iomap.flags & IOMAP_F_NEW))
continue;
error = sb_issue_zeroout(sb, iomap.addr >> inode->i_blkbits,
iomap.length >> inode->i_blkbits,
GFP_NOFS);
if (error) {
fs_err(GFS2_SB(inode), "Failed to zero data buffers\n");
goto out;
}
}
out:
brelse(dibh);
return error;
}
/**
* calc_max_reserv() - Reverse of write_calc_reserv. Given a number of
* blocks, determine how many bytes can be written.
* @ip: The inode in question.
* @len: Max cap of bytes. What we return in *len must be <= this.
* @data_blocks: Compute and return the number of data blocks needed
* @ind_blocks: Compute and return the number of indirect blocks needed
* @max_blocks: The total blocks available to work with.
*
* Returns: void, but @len, @data_blocks and @ind_blocks are filled in.
*/
static void calc_max_reserv(struct gfs2_inode *ip, loff_t *len,
unsigned int *data_blocks, unsigned int *ind_blocks,
unsigned int max_blocks)
{
loff_t max = *len;
const struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
unsigned int tmp, max_data = max_blocks - 3 * (sdp->sd_max_height - 1);
for (tmp = max_data; tmp > sdp->sd_diptrs;) {
tmp = DIV_ROUND_UP(tmp, sdp->sd_inptrs);
max_data -= tmp;
}
*data_blocks = max_data;
*ind_blocks = max_blocks - max_data;
*len = ((loff_t)max_data - 3) << sdp->sd_sb.sb_bsize_shift;
if (*len > max) {
*len = max;
gfs2_write_calc_reserv(ip, max, data_blocks, ind_blocks);
}
}
static long __gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_alloc_parms ap = { .aflags = 0, };
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
loff_t bytes, max_bytes, max_blks;
int error;
const loff_t pos = offset;
const loff_t count = len;
loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
loff_t max_chunk_size = UINT_MAX & bsize_mask;
next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
offset &= bsize_mask;
len = next - offset;
bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
if (!bytes)
bytes = UINT_MAX;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
gfs2_size_hint(file, offset, len);
gfs2_write_calc_reserv(ip, PAGE_SIZE, &data_blocks, &ind_blocks);
ap.min_target = data_blocks + ind_blocks;
while (len > 0) {
if (len < bytes)
bytes = len;
if (!gfs2_write_alloc_required(ip, offset, bytes)) {
len -= bytes;
offset += bytes;
continue;
}
/* We need to determine how many bytes we can actually
* fallocate without exceeding quota or going over the
* end of the fs. We start off optimistically by assuming
* we can write max_bytes */
max_bytes = (len > max_chunk_size) ? max_chunk_size : len;
/* Since max_bytes is most likely a theoretical max, we
* calculate a more realistic 'bytes' to serve as a good
* starting point for the number of bytes we may be able
* to write */
gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
ap.target = data_blocks + ind_blocks;
error = gfs2_quota_lock_check(ip, &ap);
if (error)
return error;
/* ap.allowed tells us how many blocks quota will allow
* us to write. Check if this reduces max_blks */
max_blks = UINT_MAX;
if (ap.allowed)
max_blks = ap.allowed;
error = gfs2_inplace_reserve(ip, &ap);
if (error)
goto out_qunlock;
/* check if the selected rgrp limits our max_blks further */
if (ip->i_res.rs_reserved < max_blks)
max_blks = ip->i_res.rs_reserved;
/* Almost done. Calculate bytes that can be written using
* max_blks. We also recompute max_bytes, data_blocks and
* ind_blocks */
calc_max_reserv(ip, &max_bytes, &data_blocks,
&ind_blocks, max_blks);
rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
RES_RG_HDR + gfs2_rg_blocks(ip, data_blocks + ind_blocks);
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
error = gfs2_trans_begin(sdp, rblocks,
PAGE_SIZE >> inode->i_blkbits);
if (error)
goto out_trans_fail;
error = fallocate_chunk(inode, offset, max_bytes, mode);
gfs2_trans_end(sdp);
if (error)
goto out_trans_fail;
len -= max_bytes;
offset += max_bytes;
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
}
if (!(mode & FALLOC_FL_KEEP_SIZE) && (pos + count) > inode->i_size)
i_size_write(inode, pos + count);
file_update_time(file);
mark_inode_dirty(inode);
if ((file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host))
return vfs_fsync_range(file, pos, pos + count - 1,
(file->f_flags & __O_SYNC) ? 0 : 1);
return 0;
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
return error;
}
static long gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int ret;
if (mode & ~(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE))
return -EOPNOTSUPP;
/* fallocate is needed by gfs2_grow to reserve space in the rindex */
if (gfs2_is_jdata(ip) && inode != sdp->sd_rindex)
return -EOPNOTSUPP;
inode_lock(inode);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
ret = gfs2_glock_nq(&gh);
if (ret)
goto out_uninit;
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len) > inode->i_size) {
ret = inode_newsize_ok(inode, offset + len);
if (ret)
goto out_unlock;
}
ret = get_write_access(inode);
if (ret)
goto out_unlock;
if (mode & FALLOC_FL_PUNCH_HOLE) {
ret = __gfs2_punch_hole(file, offset, len);
} else {
ret = __gfs2_fallocate(file, mode, offset, len);
if (ret)
gfs2_rs_deltree(&ip->i_res);
}
put_write_access(inode);
out_unlock:
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
inode_unlock(inode);
return ret;
}
static ssize_t gfs2_file_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
ssize_t ret;
gfs2_size_hint(out, *ppos, len);
ret = iter_file_splice_write(pipe, out, ppos, len, flags);
return ret;
}
#ifdef CONFIG_GFS2_FS_LOCKING_DLM
/**
* gfs2_lock - acquire/release a posix lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_lock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(file->f_mapping->host);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (!(fl->fl_flags & FL_POSIX))
return -ENOLCK;
if (unlikely(gfs2_withdrawn(sdp))) {
if (fl->fl_type == F_UNLCK)
locks_lock_file_wait(file, fl);
return -EIO;
}
if (cmd == F_CANCELLK)
return dlm_posix_cancel(ls->ls_dlm, ip->i_no_addr, file, fl);
else if (IS_GETLK(cmd))
return dlm_posix_get(ls->ls_dlm, ip->i_no_addr, file, fl);
else if (fl->fl_type == F_UNLCK)
return dlm_posix_unlock(ls->ls_dlm, ip->i_no_addr, file, fl);
else
return dlm_posix_lock(ls->ls_dlm, ip->i_no_addr, file, cmd, fl);
}
static void __flock_holder_uninit(struct file *file, struct gfs2_holder *fl_gh)
{
struct gfs2_glock *gl = gfs2_glock_hold(fl_gh->gh_gl);
/*
* Make sure gfs2_glock_put() won't sleep under the file->f_lock
* spinlock.
*/
spin_lock(&file->f_lock);
gfs2_holder_uninit(fl_gh);
spin_unlock(&file->f_lock);
gfs2_glock_put(gl);
}
static int do_flock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
struct gfs2_inode *ip = GFS2_I(file_inode(file));
struct gfs2_glock *gl;
unsigned int state;
u16 flags;
int error = 0;
int sleeptime;
state = (fl->fl_type == F_WRLCK) ? LM_ST_EXCLUSIVE : LM_ST_SHARED;
flags = GL_EXACT | GL_NOPID;
if (!IS_SETLKW(cmd))
flags |= LM_FLAG_TRY_1CB;
mutex_lock(&fp->f_fl_mutex);
if (gfs2_holder_initialized(fl_gh)) {
struct file_lock request;
if (fl_gh->gh_state == state)
goto out;
locks_init_lock(&request);
request.fl_type = F_UNLCK;
request.fl_flags = FL_FLOCK;
locks_lock_file_wait(file, &request);
gfs2_glock_dq(fl_gh);
gfs2_holder_reinit(state, flags, fl_gh);
} else {
error = gfs2_glock_get(GFS2_SB(&ip->i_inode), ip->i_no_addr,
&gfs2_flock_glops, CREATE, &gl);
if (error)
goto out;
spin_lock(&file->f_lock);
gfs2_holder_init(gl, state, flags, fl_gh);
spin_unlock(&file->f_lock);
gfs2_glock_put(gl);
}
for (sleeptime = 1; sleeptime <= 4; sleeptime <<= 1) {
error = gfs2_glock_nq(fl_gh);
if (error != GLR_TRYFAILED)
break;
fl_gh->gh_flags &= ~LM_FLAG_TRY_1CB;
fl_gh->gh_flags |= LM_FLAG_TRY;
msleep(sleeptime);
}
if (error) {
__flock_holder_uninit(file, fl_gh);
if (error == GLR_TRYFAILED)
error = -EAGAIN;
} else {
error = locks_lock_file_wait(file, fl);
gfs2_assert_warn(GFS2_SB(&ip->i_inode), !error);
}
out:
mutex_unlock(&fp->f_fl_mutex);
return error;
}
static void do_unflock(struct file *file, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
mutex_lock(&fp->f_fl_mutex);
locks_lock_file_wait(file, fl);
if (gfs2_holder_initialized(fl_gh)) {
gfs2_glock_dq(fl_gh);
__flock_holder_uninit(file, fl_gh);
}
mutex_unlock(&fp->f_fl_mutex);
}
/**
* gfs2_flock - acquire/release a flock lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_flock(struct file *file, int cmd, struct file_lock *fl)
{
if (!(fl->fl_flags & FL_FLOCK))
return -ENOLCK;
if (fl->fl_type == F_UNLCK) {
do_unflock(file, fl);
return 0;
} else {
return do_flock(file, cmd, fl);
}
}
const struct file_operations gfs2_file_fops = {
.llseek = gfs2_llseek,
.read_iter = gfs2_file_read_iter,
.write_iter = gfs2_file_write_iter,
.iopoll = iocb_bio_iopoll,
.unlocked_ioctl = gfs2_ioctl,
.compat_ioctl = gfs2_compat_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.splice_read = copy_splice_read,
.splice_write = gfs2_file_splice_write,
.setlease = simple_nosetlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops = {
.iterate_shared = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.compat_ioctl = gfs2_compat_ioctl,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.llseek = default_llseek,
};
#endif /* CONFIG_GFS2_FS_LOCKING_DLM */
const struct file_operations gfs2_file_fops_nolock = {
.llseek = gfs2_llseek,
.read_iter = gfs2_file_read_iter,
.write_iter = gfs2_file_write_iter,
.iopoll = iocb_bio_iopoll,
.unlocked_ioctl = gfs2_ioctl,
.compat_ioctl = gfs2_compat_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.splice_read = copy_splice_read,
.splice_write = gfs2_file_splice_write,
.setlease = generic_setlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops_nolock = {
.iterate_shared = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.compat_ioctl = gfs2_compat_ioctl,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.llseek = default_llseek,
};
| linux-master | fs/gfs2/file.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/export.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/gfs2_ondisk.h>
#include <linux/quotaops.h>
#include <linux/lockdep.h>
#include <linux/module.h>
#include <linux/backing-dev.h>
#include <linux/fs_parser.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "recovery.h"
#include "rgrp.h"
#include "super.h"
#include "sys.h"
#include "util.h"
#include "log.h"
#include "quota.h"
#include "dir.h"
#include "meta_io.h"
#include "trace_gfs2.h"
#include "lops.h"
#define DO 0
#define UNDO 1
/**
* gfs2_tune_init - Fill a gfs2_tune structure with default values
* @gt: tune
*
*/
static void gfs2_tune_init(struct gfs2_tune *gt)
{
spin_lock_init(>->gt_spin);
gt->gt_quota_warn_period = 10;
gt->gt_quota_scale_num = 1;
gt->gt_quota_scale_den = 1;
gt->gt_new_files_jdata = 0;
gt->gt_max_readahead = BIT(18);
gt->gt_complain_secs = 10;
}
void free_sbd(struct gfs2_sbd *sdp)
{
if (sdp->sd_lkstats)
free_percpu(sdp->sd_lkstats);
kfree(sdp);
}
static struct gfs2_sbd *init_sbd(struct super_block *sb)
{
struct gfs2_sbd *sdp;
struct address_space *mapping;
sdp = kzalloc(sizeof(struct gfs2_sbd), GFP_KERNEL);
if (!sdp)
return NULL;
sdp->sd_vfs = sb;
sdp->sd_lkstats = alloc_percpu(struct gfs2_pcpu_lkstats);
if (!sdp->sd_lkstats)
goto fail;
sb->s_fs_info = sdp;
set_bit(SDF_NOJOURNALID, &sdp->sd_flags);
gfs2_tune_init(&sdp->sd_tune);
init_waitqueue_head(&sdp->sd_kill_wait);
init_waitqueue_head(&sdp->sd_async_glock_wait);
atomic_set(&sdp->sd_glock_disposal, 0);
init_completion(&sdp->sd_locking_init);
init_completion(&sdp->sd_wdack);
spin_lock_init(&sdp->sd_statfs_spin);
spin_lock_init(&sdp->sd_rindex_spin);
sdp->sd_rindex_tree.rb_node = NULL;
INIT_LIST_HEAD(&sdp->sd_jindex_list);
spin_lock_init(&sdp->sd_jindex_spin);
mutex_init(&sdp->sd_jindex_mutex);
init_completion(&sdp->sd_journal_ready);
INIT_LIST_HEAD(&sdp->sd_quota_list);
mutex_init(&sdp->sd_quota_mutex);
mutex_init(&sdp->sd_quota_sync_mutex);
init_waitqueue_head(&sdp->sd_quota_wait);
spin_lock_init(&sdp->sd_bitmap_lock);
INIT_LIST_HEAD(&sdp->sd_sc_inodes_list);
mapping = &sdp->sd_aspace;
address_space_init_once(mapping);
mapping->a_ops = &gfs2_rgrp_aops;
mapping->host = sb->s_bdev->bd_inode;
mapping->flags = 0;
mapping_set_gfp_mask(mapping, GFP_NOFS);
mapping->private_data = NULL;
mapping->writeback_index = 0;
spin_lock_init(&sdp->sd_log_lock);
atomic_set(&sdp->sd_log_pinned, 0);
INIT_LIST_HEAD(&sdp->sd_log_revokes);
INIT_LIST_HEAD(&sdp->sd_log_ordered);
spin_lock_init(&sdp->sd_ordered_lock);
init_waitqueue_head(&sdp->sd_log_waitq);
init_waitqueue_head(&sdp->sd_logd_waitq);
spin_lock_init(&sdp->sd_ail_lock);
INIT_LIST_HEAD(&sdp->sd_ail1_list);
INIT_LIST_HEAD(&sdp->sd_ail2_list);
init_rwsem(&sdp->sd_log_flush_lock);
atomic_set(&sdp->sd_log_in_flight, 0);
init_waitqueue_head(&sdp->sd_log_flush_wait);
mutex_init(&sdp->sd_freeze_mutex);
return sdp;
fail:
free_sbd(sdp);
return NULL;
}
/**
* gfs2_check_sb - Check superblock
* @sdp: the filesystem
* @silent: Don't print a message if the check fails
*
* Checks the version code of the FS is one that we understand how to
* read and that the sizes of the various on-disk structures have not
* changed.
*/
static int gfs2_check_sb(struct gfs2_sbd *sdp, int silent)
{
struct gfs2_sb_host *sb = &sdp->sd_sb;
if (sb->sb_magic != GFS2_MAGIC ||
sb->sb_type != GFS2_METATYPE_SB) {
if (!silent)
pr_warn("not a GFS2 filesystem\n");
return -EINVAL;
}
if (sb->sb_fs_format < GFS2_FS_FORMAT_MIN ||
sb->sb_fs_format > GFS2_FS_FORMAT_MAX ||
sb->sb_multihost_format != GFS2_FORMAT_MULTI) {
fs_warn(sdp, "Unknown on-disk format, unable to mount\n");
return -EINVAL;
}
if (sb->sb_bsize < 512 || sb->sb_bsize > PAGE_SIZE ||
(sb->sb_bsize & (sb->sb_bsize - 1))) {
pr_warn("Invalid block size\n");
return -EINVAL;
}
if (sb->sb_bsize_shift != ffs(sb->sb_bsize) - 1) {
pr_warn("Invalid block size shift\n");
return -EINVAL;
}
return 0;
}
static void end_bio_io_page(struct bio *bio)
{
struct page *page = bio->bi_private;
if (!bio->bi_status)
SetPageUptodate(page);
else
pr_warn("error %d reading superblock\n", bio->bi_status);
unlock_page(page);
}
static void gfs2_sb_in(struct gfs2_sbd *sdp, const void *buf)
{
struct gfs2_sb_host *sb = &sdp->sd_sb;
struct super_block *s = sdp->sd_vfs;
const struct gfs2_sb *str = buf;
sb->sb_magic = be32_to_cpu(str->sb_header.mh_magic);
sb->sb_type = be32_to_cpu(str->sb_header.mh_type);
sb->sb_fs_format = be32_to_cpu(str->sb_fs_format);
sb->sb_multihost_format = be32_to_cpu(str->sb_multihost_format);
sb->sb_bsize = be32_to_cpu(str->sb_bsize);
sb->sb_bsize_shift = be32_to_cpu(str->sb_bsize_shift);
sb->sb_master_dir.no_addr = be64_to_cpu(str->sb_master_dir.no_addr);
sb->sb_master_dir.no_formal_ino = be64_to_cpu(str->sb_master_dir.no_formal_ino);
sb->sb_root_dir.no_addr = be64_to_cpu(str->sb_root_dir.no_addr);
sb->sb_root_dir.no_formal_ino = be64_to_cpu(str->sb_root_dir.no_formal_ino);
memcpy(sb->sb_lockproto, str->sb_lockproto, GFS2_LOCKNAME_LEN);
memcpy(sb->sb_locktable, str->sb_locktable, GFS2_LOCKNAME_LEN);
memcpy(&s->s_uuid, str->sb_uuid, 16);
}
/**
* gfs2_read_super - Read the gfs2 super block from disk
* @sdp: The GFS2 super block
* @sector: The location of the super block
* @silent: Don't print a message if the check fails
*
* This uses the bio functions to read the super block from disk
* because we want to be 100% sure that we never read cached data.
* A super block is read twice only during each GFS2 mount and is
* never written to by the filesystem. The first time its read no
* locks are held, and the only details which are looked at are those
* relating to the locking protocol. Once locking is up and working,
* the sb is read again under the lock to establish the location of
* the master directory (contains pointers to journals etc) and the
* root directory.
*
* Returns: 0 on success or error
*/
static int gfs2_read_super(struct gfs2_sbd *sdp, sector_t sector, int silent)
{
struct super_block *sb = sdp->sd_vfs;
struct gfs2_sb *p;
struct page *page;
struct bio *bio;
page = alloc_page(GFP_NOFS);
if (unlikely(!page))
return -ENOMEM;
ClearPageUptodate(page);
ClearPageDirty(page);
lock_page(page);
bio = bio_alloc(sb->s_bdev, 1, REQ_OP_READ | REQ_META, GFP_NOFS);
bio->bi_iter.bi_sector = sector * (sb->s_blocksize >> 9);
__bio_add_page(bio, page, PAGE_SIZE, 0);
bio->bi_end_io = end_bio_io_page;
bio->bi_private = page;
submit_bio(bio);
wait_on_page_locked(page);
bio_put(bio);
if (!PageUptodate(page)) {
__free_page(page);
return -EIO;
}
p = kmap(page);
gfs2_sb_in(sdp, p);
kunmap(page);
__free_page(page);
return gfs2_check_sb(sdp, silent);
}
/**
* gfs2_read_sb - Read super block
* @sdp: The GFS2 superblock
* @silent: Don't print message if mount fails
*
*/
static int gfs2_read_sb(struct gfs2_sbd *sdp, int silent)
{
u32 hash_blocks, ind_blocks, leaf_blocks;
u32 tmp_blocks;
unsigned int x;
int error;
error = gfs2_read_super(sdp, GFS2_SB_ADDR >> sdp->sd_fsb2bb_shift, silent);
if (error) {
if (!silent)
fs_err(sdp, "can't read superblock\n");
return error;
}
sdp->sd_fsb2bb_shift = sdp->sd_sb.sb_bsize_shift -
GFS2_BASIC_BLOCK_SHIFT;
sdp->sd_fsb2bb = BIT(sdp->sd_fsb2bb_shift);
sdp->sd_diptrs = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_dinode)) / sizeof(u64);
sdp->sd_inptrs = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_meta_header)) / sizeof(u64);
sdp->sd_ldptrs = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_log_descriptor)) / sizeof(u64);
sdp->sd_jbsize = sdp->sd_sb.sb_bsize - sizeof(struct gfs2_meta_header);
sdp->sd_hash_bsize = sdp->sd_sb.sb_bsize / 2;
sdp->sd_hash_bsize_shift = sdp->sd_sb.sb_bsize_shift - 1;
sdp->sd_hash_ptrs = sdp->sd_hash_bsize / sizeof(u64);
sdp->sd_qc_per_block = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_meta_header)) /
sizeof(struct gfs2_quota_change);
sdp->sd_blocks_per_bitmap = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_meta_header))
* GFS2_NBBY; /* not the rgrp bitmap, subsequent bitmaps only */
/*
* We always keep at least one block reserved for revokes in
* transactions. This greatly simplifies allocating additional
* revoke blocks.
*/
atomic_set(&sdp->sd_log_revokes_available, sdp->sd_ldptrs);
/* Compute maximum reservation required to add a entry to a directory */
hash_blocks = DIV_ROUND_UP(sizeof(u64) * BIT(GFS2_DIR_MAX_DEPTH),
sdp->sd_jbsize);
ind_blocks = 0;
for (tmp_blocks = hash_blocks; tmp_blocks > sdp->sd_diptrs;) {
tmp_blocks = DIV_ROUND_UP(tmp_blocks, sdp->sd_inptrs);
ind_blocks += tmp_blocks;
}
leaf_blocks = 2 + GFS2_DIR_MAX_DEPTH;
sdp->sd_max_dirres = hash_blocks + ind_blocks + leaf_blocks;
sdp->sd_heightsize[0] = sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_dinode);
sdp->sd_heightsize[1] = sdp->sd_sb.sb_bsize * sdp->sd_diptrs;
for (x = 2;; x++) {
u64 space, d;
u32 m;
space = sdp->sd_heightsize[x - 1] * sdp->sd_inptrs;
d = space;
m = do_div(d, sdp->sd_inptrs);
if (d != sdp->sd_heightsize[x - 1] || m)
break;
sdp->sd_heightsize[x] = space;
}
sdp->sd_max_height = x;
sdp->sd_heightsize[x] = ~0;
gfs2_assert(sdp, sdp->sd_max_height <= GFS2_MAX_META_HEIGHT);
sdp->sd_max_dents_per_leaf = (sdp->sd_sb.sb_bsize -
sizeof(struct gfs2_leaf)) /
GFS2_MIN_DIRENT_SIZE;
return 0;
}
static int init_names(struct gfs2_sbd *sdp, int silent)
{
char *proto, *table;
int error = 0;
proto = sdp->sd_args.ar_lockproto;
table = sdp->sd_args.ar_locktable;
/* Try to autodetect */
if (!proto[0] || !table[0]) {
error = gfs2_read_super(sdp, GFS2_SB_ADDR >> sdp->sd_fsb2bb_shift, silent);
if (error)
return error;
if (!proto[0])
proto = sdp->sd_sb.sb_lockproto;
if (!table[0])
table = sdp->sd_sb.sb_locktable;
}
if (!table[0])
table = sdp->sd_vfs->s_id;
BUILD_BUG_ON(GFS2_LOCKNAME_LEN > GFS2_FSNAME_LEN);
strscpy(sdp->sd_proto_name, proto, GFS2_LOCKNAME_LEN);
strscpy(sdp->sd_table_name, table, GFS2_LOCKNAME_LEN);
table = sdp->sd_table_name;
while ((table = strchr(table, '/')))
*table = '_';
return error;
}
static int init_locking(struct gfs2_sbd *sdp, struct gfs2_holder *mount_gh,
int undo)
{
int error = 0;
if (undo)
goto fail_trans;
error = gfs2_glock_nq_num(sdp,
GFS2_MOUNT_LOCK, &gfs2_nondisk_glops,
LM_ST_EXCLUSIVE,
LM_FLAG_NOEXP | GL_NOCACHE | GL_NOPID,
mount_gh);
if (error) {
fs_err(sdp, "can't acquire mount glock: %d\n", error);
goto fail;
}
error = gfs2_glock_nq_num(sdp,
GFS2_LIVE_LOCK, &gfs2_nondisk_glops,
LM_ST_SHARED,
LM_FLAG_NOEXP | GL_EXACT | GL_NOPID,
&sdp->sd_live_gh);
if (error) {
fs_err(sdp, "can't acquire live glock: %d\n", error);
goto fail_mount;
}
error = gfs2_glock_get(sdp, GFS2_RENAME_LOCK, &gfs2_nondisk_glops,
CREATE, &sdp->sd_rename_gl);
if (error) {
fs_err(sdp, "can't create rename glock: %d\n", error);
goto fail_live;
}
error = gfs2_glock_get(sdp, GFS2_FREEZE_LOCK, &gfs2_freeze_glops,
CREATE, &sdp->sd_freeze_gl);
if (error) {
fs_err(sdp, "can't create freeze glock: %d\n", error);
goto fail_rename;
}
return 0;
fail_trans:
gfs2_glock_put(sdp->sd_freeze_gl);
fail_rename:
gfs2_glock_put(sdp->sd_rename_gl);
fail_live:
gfs2_glock_dq_uninit(&sdp->sd_live_gh);
fail_mount:
gfs2_glock_dq_uninit(mount_gh);
fail:
return error;
}
static int gfs2_lookup_root(struct super_block *sb, struct dentry **dptr,
u64 no_addr, const char *name)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
struct dentry *dentry;
struct inode *inode;
inode = gfs2_inode_lookup(sb, DT_DIR, no_addr, 0,
GFS2_BLKST_FREE /* ignore */);
if (IS_ERR(inode)) {
fs_err(sdp, "can't read in %s inode: %ld\n", name, PTR_ERR(inode));
return PTR_ERR(inode);
}
dentry = d_make_root(inode);
if (!dentry) {
fs_err(sdp, "can't alloc %s dentry\n", name);
return -ENOMEM;
}
*dptr = dentry;
return 0;
}
static int init_sb(struct gfs2_sbd *sdp, int silent)
{
struct super_block *sb = sdp->sd_vfs;
struct gfs2_holder sb_gh;
u64 no_addr;
int ret;
ret = gfs2_glock_nq_num(sdp, GFS2_SB_LOCK, &gfs2_meta_glops,
LM_ST_SHARED, 0, &sb_gh);
if (ret) {
fs_err(sdp, "can't acquire superblock glock: %d\n", ret);
return ret;
}
ret = gfs2_read_sb(sdp, silent);
if (ret) {
fs_err(sdp, "can't read superblock: %d\n", ret);
goto out;
}
switch(sdp->sd_sb.sb_fs_format) {
case GFS2_FS_FORMAT_MAX:
sb->s_xattr = gfs2_xattr_handlers_max;
break;
case GFS2_FS_FORMAT_MIN:
sb->s_xattr = gfs2_xattr_handlers_min;
break;
default:
BUG();
}
/* Set up the buffer cache and SB for real */
if (sdp->sd_sb.sb_bsize < bdev_logical_block_size(sb->s_bdev)) {
ret = -EINVAL;
fs_err(sdp, "FS block size (%u) is too small for device "
"block size (%u)\n",
sdp->sd_sb.sb_bsize, bdev_logical_block_size(sb->s_bdev));
goto out;
}
if (sdp->sd_sb.sb_bsize > PAGE_SIZE) {
ret = -EINVAL;
fs_err(sdp, "FS block size (%u) is too big for machine "
"page size (%u)\n",
sdp->sd_sb.sb_bsize, (unsigned int)PAGE_SIZE);
goto out;
}
sb_set_blocksize(sb, sdp->sd_sb.sb_bsize);
/* Get the root inode */
no_addr = sdp->sd_sb.sb_root_dir.no_addr;
ret = gfs2_lookup_root(sb, &sdp->sd_root_dir, no_addr, "root");
if (ret)
goto out;
/* Get the master inode */
no_addr = sdp->sd_sb.sb_master_dir.no_addr;
ret = gfs2_lookup_root(sb, &sdp->sd_master_dir, no_addr, "master");
if (ret) {
dput(sdp->sd_root_dir);
goto out;
}
sb->s_root = dget(sdp->sd_args.ar_meta ? sdp->sd_master_dir : sdp->sd_root_dir);
out:
gfs2_glock_dq_uninit(&sb_gh);
return ret;
}
static void gfs2_others_may_mount(struct gfs2_sbd *sdp)
{
char *message = "FIRSTMOUNT=Done";
char *envp[] = { message, NULL };
fs_info(sdp, "first mount done, others may mount\n");
if (sdp->sd_lockstruct.ls_ops->lm_first_done)
sdp->sd_lockstruct.ls_ops->lm_first_done(sdp);
kobject_uevent_env(&sdp->sd_kobj, KOBJ_CHANGE, envp);
}
/**
* gfs2_jindex_hold - Grab a lock on the jindex
* @sdp: The GFS2 superblock
* @ji_gh: the holder for the jindex glock
*
* Returns: errno
*/
static int gfs2_jindex_hold(struct gfs2_sbd *sdp, struct gfs2_holder *ji_gh)
{
struct gfs2_inode *dip = GFS2_I(sdp->sd_jindex);
struct qstr name;
char buf[20];
struct gfs2_jdesc *jd;
int error;
name.name = buf;
mutex_lock(&sdp->sd_jindex_mutex);
for (;;) {
struct gfs2_inode *jip;
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, ji_gh);
if (error)
break;
name.len = sprintf(buf, "journal%u", sdp->sd_journals);
name.hash = gfs2_disk_hash(name.name, name.len);
error = gfs2_dir_check(sdp->sd_jindex, &name, NULL);
if (error == -ENOENT) {
error = 0;
break;
}
gfs2_glock_dq_uninit(ji_gh);
if (error)
break;
error = -ENOMEM;
jd = kzalloc(sizeof(struct gfs2_jdesc), GFP_KERNEL);
if (!jd)
break;
INIT_LIST_HEAD(&jd->extent_list);
INIT_LIST_HEAD(&jd->jd_revoke_list);
INIT_WORK(&jd->jd_work, gfs2_recover_func);
jd->jd_inode = gfs2_lookupi(sdp->sd_jindex, &name, 1);
if (IS_ERR_OR_NULL(jd->jd_inode)) {
if (!jd->jd_inode)
error = -ENOENT;
else
error = PTR_ERR(jd->jd_inode);
kfree(jd);
break;
}
d_mark_dontcache(jd->jd_inode);
spin_lock(&sdp->sd_jindex_spin);
jd->jd_jid = sdp->sd_journals++;
jip = GFS2_I(jd->jd_inode);
jd->jd_no_addr = jip->i_no_addr;
list_add_tail(&jd->jd_list, &sdp->sd_jindex_list);
spin_unlock(&sdp->sd_jindex_spin);
}
mutex_unlock(&sdp->sd_jindex_mutex);
return error;
}
/**
* init_statfs - look up and initialize master and local (per node) statfs inodes
* @sdp: The GFS2 superblock
*
* This should be called after the jindex is initialized in init_journal() and
* before gfs2_journal_recovery() is called because we need to be able to write
* to these inodes during recovery.
*
* Returns: errno
*/
static int init_statfs(struct gfs2_sbd *sdp)
{
int error = 0;
struct inode *master = d_inode(sdp->sd_master_dir);
struct inode *pn = NULL;
char buf[30];
struct gfs2_jdesc *jd;
struct gfs2_inode *ip;
sdp->sd_statfs_inode = gfs2_lookup_simple(master, "statfs");
if (IS_ERR(sdp->sd_statfs_inode)) {
error = PTR_ERR(sdp->sd_statfs_inode);
fs_err(sdp, "can't read in statfs inode: %d\n", error);
goto out;
}
if (sdp->sd_args.ar_spectator)
goto out;
pn = gfs2_lookup_simple(master, "per_node");
if (IS_ERR(pn)) {
error = PTR_ERR(pn);
fs_err(sdp, "can't find per_node directory: %d\n", error);
goto put_statfs;
}
/* For each jid, lookup the corresponding local statfs inode in the
* per_node metafs directory and save it in the sdp->sd_sc_inodes_list. */
list_for_each_entry(jd, &sdp->sd_jindex_list, jd_list) {
struct local_statfs_inode *lsi =
kmalloc(sizeof(struct local_statfs_inode), GFP_NOFS);
if (!lsi) {
error = -ENOMEM;
goto free_local;
}
sprintf(buf, "statfs_change%u", jd->jd_jid);
lsi->si_sc_inode = gfs2_lookup_simple(pn, buf);
if (IS_ERR(lsi->si_sc_inode)) {
error = PTR_ERR(lsi->si_sc_inode);
fs_err(sdp, "can't find local \"sc\" file#%u: %d\n",
jd->jd_jid, error);
kfree(lsi);
goto free_local;
}
lsi->si_jid = jd->jd_jid;
if (jd->jd_jid == sdp->sd_jdesc->jd_jid)
sdp->sd_sc_inode = lsi->si_sc_inode;
list_add_tail(&lsi->si_list, &sdp->sd_sc_inodes_list);
}
iput(pn);
pn = NULL;
ip = GFS2_I(sdp->sd_sc_inode);
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, GL_NOPID,
&sdp->sd_sc_gh);
if (error) {
fs_err(sdp, "can't lock local \"sc\" file: %d\n", error);
goto free_local;
}
/* read in the local statfs buffer - other nodes don't change it. */
error = gfs2_meta_inode_buffer(ip, &sdp->sd_sc_bh);
if (error) {
fs_err(sdp, "Cannot read in local statfs: %d\n", error);
goto unlock_sd_gh;
}
return 0;
unlock_sd_gh:
gfs2_glock_dq_uninit(&sdp->sd_sc_gh);
free_local:
free_local_statfs_inodes(sdp);
iput(pn);
put_statfs:
iput(sdp->sd_statfs_inode);
out:
return error;
}
/* Uninitialize and free up memory used by the list of statfs inodes */
static void uninit_statfs(struct gfs2_sbd *sdp)
{
if (!sdp->sd_args.ar_spectator) {
brelse(sdp->sd_sc_bh);
gfs2_glock_dq_uninit(&sdp->sd_sc_gh);
free_local_statfs_inodes(sdp);
}
iput(sdp->sd_statfs_inode);
}
static int init_journal(struct gfs2_sbd *sdp, int undo)
{
struct inode *master = d_inode(sdp->sd_master_dir);
struct gfs2_holder ji_gh;
struct gfs2_inode *ip;
int error = 0;
gfs2_holder_mark_uninitialized(&ji_gh);
if (undo)
goto fail_statfs;
sdp->sd_jindex = gfs2_lookup_simple(master, "jindex");
if (IS_ERR(sdp->sd_jindex)) {
fs_err(sdp, "can't lookup journal index: %d\n", error);
return PTR_ERR(sdp->sd_jindex);
}
/* Load in the journal index special file */
error = gfs2_jindex_hold(sdp, &ji_gh);
if (error) {
fs_err(sdp, "can't read journal index: %d\n", error);
goto fail;
}
error = -EUSERS;
if (!gfs2_jindex_size(sdp)) {
fs_err(sdp, "no journals!\n");
goto fail_jindex;
}
atomic_set(&sdp->sd_log_blks_needed, 0);
if (sdp->sd_args.ar_spectator) {
sdp->sd_jdesc = gfs2_jdesc_find(sdp, 0);
atomic_set(&sdp->sd_log_blks_free, sdp->sd_jdesc->jd_blocks);
atomic_set(&sdp->sd_log_thresh1, 2*sdp->sd_jdesc->jd_blocks/5);
atomic_set(&sdp->sd_log_thresh2, 4*sdp->sd_jdesc->jd_blocks/5);
} else {
if (sdp->sd_lockstruct.ls_jid >= gfs2_jindex_size(sdp)) {
fs_err(sdp, "can't mount journal #%u\n",
sdp->sd_lockstruct.ls_jid);
fs_err(sdp, "there are only %u journals (0 - %u)\n",
gfs2_jindex_size(sdp),
gfs2_jindex_size(sdp) - 1);
goto fail_jindex;
}
sdp->sd_jdesc = gfs2_jdesc_find(sdp, sdp->sd_lockstruct.ls_jid);
error = gfs2_glock_nq_num(sdp, sdp->sd_lockstruct.ls_jid,
&gfs2_journal_glops,
LM_ST_EXCLUSIVE,
LM_FLAG_NOEXP | GL_NOCACHE | GL_NOPID,
&sdp->sd_journal_gh);
if (error) {
fs_err(sdp, "can't acquire journal glock: %d\n", error);
goto fail_jindex;
}
ip = GFS2_I(sdp->sd_jdesc->jd_inode);
sdp->sd_jinode_gl = ip->i_gl;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED,
LM_FLAG_NOEXP | GL_EXACT |
GL_NOCACHE | GL_NOPID,
&sdp->sd_jinode_gh);
if (error) {
fs_err(sdp, "can't acquire journal inode glock: %d\n",
error);
goto fail_journal_gh;
}
error = gfs2_jdesc_check(sdp->sd_jdesc);
if (error) {
fs_err(sdp, "my journal (%u) is bad: %d\n",
sdp->sd_jdesc->jd_jid, error);
goto fail_jinode_gh;
}
atomic_set(&sdp->sd_log_blks_free, sdp->sd_jdesc->jd_blocks);
atomic_set(&sdp->sd_log_thresh1, 2*sdp->sd_jdesc->jd_blocks/5);
atomic_set(&sdp->sd_log_thresh2, 4*sdp->sd_jdesc->jd_blocks/5);
/* Map the extents for this journal's blocks */
gfs2_map_journal_extents(sdp, sdp->sd_jdesc);
}
trace_gfs2_log_blocks(sdp, atomic_read(&sdp->sd_log_blks_free));
/* Lookup statfs inodes here so journal recovery can use them. */
error = init_statfs(sdp);
if (error)
goto fail_jinode_gh;
if (sdp->sd_lockstruct.ls_first) {
unsigned int x;
for (x = 0; x < sdp->sd_journals; x++) {
struct gfs2_jdesc *jd = gfs2_jdesc_find(sdp, x);
if (sdp->sd_args.ar_spectator) {
error = check_journal_clean(sdp, jd, true);
if (error)
goto fail_statfs;
continue;
}
error = gfs2_recover_journal(jd, true);
if (error) {
fs_err(sdp, "error recovering journal %u: %d\n",
x, error);
goto fail_statfs;
}
}
gfs2_others_may_mount(sdp);
} else if (!sdp->sd_args.ar_spectator) {
error = gfs2_recover_journal(sdp->sd_jdesc, true);
if (error) {
fs_err(sdp, "error recovering my journal: %d\n", error);
goto fail_statfs;
}
}
sdp->sd_log_idle = 1;
set_bit(SDF_JOURNAL_CHECKED, &sdp->sd_flags);
gfs2_glock_dq_uninit(&ji_gh);
INIT_WORK(&sdp->sd_freeze_work, gfs2_freeze_func);
return 0;
fail_statfs:
uninit_statfs(sdp);
fail_jinode_gh:
/* A withdraw may have done dq/uninit so now we need to check it */
if (!sdp->sd_args.ar_spectator &&
gfs2_holder_initialized(&sdp->sd_jinode_gh))
gfs2_glock_dq_uninit(&sdp->sd_jinode_gh);
fail_journal_gh:
if (!sdp->sd_args.ar_spectator &&
gfs2_holder_initialized(&sdp->sd_journal_gh))
gfs2_glock_dq_uninit(&sdp->sd_journal_gh);
fail_jindex:
gfs2_jindex_free(sdp);
if (gfs2_holder_initialized(&ji_gh))
gfs2_glock_dq_uninit(&ji_gh);
fail:
iput(sdp->sd_jindex);
return error;
}
static struct lock_class_key gfs2_quota_imutex_key;
static int init_inodes(struct gfs2_sbd *sdp, int undo)
{
int error = 0;
struct inode *master = d_inode(sdp->sd_master_dir);
if (undo)
goto fail_qinode;
error = init_journal(sdp, undo);
complete_all(&sdp->sd_journal_ready);
if (error)
goto fail;
/* Read in the resource index inode */
sdp->sd_rindex = gfs2_lookup_simple(master, "rindex");
if (IS_ERR(sdp->sd_rindex)) {
error = PTR_ERR(sdp->sd_rindex);
fs_err(sdp, "can't get resource index inode: %d\n", error);
goto fail_journal;
}
sdp->sd_rindex_uptodate = 0;
/* Read in the quota inode */
sdp->sd_quota_inode = gfs2_lookup_simple(master, "quota");
if (IS_ERR(sdp->sd_quota_inode)) {
error = PTR_ERR(sdp->sd_quota_inode);
fs_err(sdp, "can't get quota file inode: %d\n", error);
goto fail_rindex;
}
/*
* i_rwsem on quota files is special. Since this inode is hidden system
* file, we are safe to define locking ourselves.
*/
lockdep_set_class(&sdp->sd_quota_inode->i_rwsem,
&gfs2_quota_imutex_key);
error = gfs2_rindex_update(sdp);
if (error)
goto fail_qinode;
return 0;
fail_qinode:
iput(sdp->sd_quota_inode);
fail_rindex:
gfs2_clear_rgrpd(sdp);
iput(sdp->sd_rindex);
fail_journal:
init_journal(sdp, UNDO);
fail:
return error;
}
static int init_per_node(struct gfs2_sbd *sdp, int undo)
{
struct inode *pn = NULL;
char buf[30];
int error = 0;
struct gfs2_inode *ip;
struct inode *master = d_inode(sdp->sd_master_dir);
if (sdp->sd_args.ar_spectator)
return 0;
if (undo)
goto fail_qc_gh;
pn = gfs2_lookup_simple(master, "per_node");
if (IS_ERR(pn)) {
error = PTR_ERR(pn);
fs_err(sdp, "can't find per_node directory: %d\n", error);
return error;
}
sprintf(buf, "quota_change%u", sdp->sd_jdesc->jd_jid);
sdp->sd_qc_inode = gfs2_lookup_simple(pn, buf);
if (IS_ERR(sdp->sd_qc_inode)) {
error = PTR_ERR(sdp->sd_qc_inode);
fs_err(sdp, "can't find local \"qc\" file: %d\n", error);
goto fail_ut_i;
}
iput(pn);
pn = NULL;
ip = GFS2_I(sdp->sd_qc_inode);
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, GL_NOPID,
&sdp->sd_qc_gh);
if (error) {
fs_err(sdp, "can't lock local \"qc\" file: %d\n", error);
goto fail_qc_i;
}
return 0;
fail_qc_gh:
gfs2_glock_dq_uninit(&sdp->sd_qc_gh);
fail_qc_i:
iput(sdp->sd_qc_inode);
fail_ut_i:
iput(pn);
return error;
}
static const match_table_t nolock_tokens = {
{ Opt_jid, "jid=%d", },
{ Opt_err, NULL },
};
static const struct lm_lockops nolock_ops = {
.lm_proto_name = "lock_nolock",
.lm_put_lock = gfs2_glock_free,
.lm_tokens = &nolock_tokens,
};
/**
* gfs2_lm_mount - mount a locking protocol
* @sdp: the filesystem
* @silent: if 1, don't complain if the FS isn't a GFS2 fs
*
* Returns: errno
*/
static int gfs2_lm_mount(struct gfs2_sbd *sdp, int silent)
{
const struct lm_lockops *lm;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
struct gfs2_args *args = &sdp->sd_args;
const char *proto = sdp->sd_proto_name;
const char *table = sdp->sd_table_name;
char *o, *options;
int ret;
if (!strcmp("lock_nolock", proto)) {
lm = &nolock_ops;
sdp->sd_args.ar_localflocks = 1;
#ifdef CONFIG_GFS2_FS_LOCKING_DLM
} else if (!strcmp("lock_dlm", proto)) {
lm = &gfs2_dlm_ops;
#endif
} else {
pr_info("can't find protocol %s\n", proto);
return -ENOENT;
}
fs_info(sdp, "Trying to join cluster \"%s\", \"%s\"\n", proto, table);
ls->ls_ops = lm;
ls->ls_first = 1;
for (options = args->ar_hostdata; (o = strsep(&options, ":")); ) {
substring_t tmp[MAX_OPT_ARGS];
int token, option;
if (!o || !*o)
continue;
token = match_token(o, *lm->lm_tokens, tmp);
switch (token) {
case Opt_jid:
ret = match_int(&tmp[0], &option);
if (ret || option < 0)
goto hostdata_error;
if (test_and_clear_bit(SDF_NOJOURNALID, &sdp->sd_flags))
ls->ls_jid = option;
break;
case Opt_id:
case Opt_nodir:
/* Obsolete, but left for backward compat purposes */
break;
case Opt_first:
ret = match_int(&tmp[0], &option);
if (ret || (option != 0 && option != 1))
goto hostdata_error;
ls->ls_first = option;
break;
case Opt_err:
default:
hostdata_error:
fs_info(sdp, "unknown hostdata (%s)\n", o);
return -EINVAL;
}
}
if (lm->lm_mount == NULL) {
fs_info(sdp, "Now mounting FS (format %u)...\n", sdp->sd_sb.sb_fs_format);
complete_all(&sdp->sd_locking_init);
return 0;
}
ret = lm->lm_mount(sdp, table);
if (ret == 0)
fs_info(sdp, "Joined cluster. Now mounting FS (format %u)...\n",
sdp->sd_sb.sb_fs_format);
complete_all(&sdp->sd_locking_init);
return ret;
}
void gfs2_lm_unmount(struct gfs2_sbd *sdp)
{
const struct lm_lockops *lm = sdp->sd_lockstruct.ls_ops;
if (likely(!gfs2_withdrawn(sdp)) && lm->lm_unmount)
lm->lm_unmount(sdp);
}
static int wait_on_journal(struct gfs2_sbd *sdp)
{
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
return 0;
return wait_on_bit(&sdp->sd_flags, SDF_NOJOURNALID, TASK_INTERRUPTIBLE)
? -EINTR : 0;
}
void gfs2_online_uevent(struct gfs2_sbd *sdp)
{
struct super_block *sb = sdp->sd_vfs;
char ro[20];
char spectator[20];
char *envp[] = { ro, spectator, NULL };
sprintf(ro, "RDONLY=%d", sb_rdonly(sb));
sprintf(spectator, "SPECTATOR=%d", sdp->sd_args.ar_spectator ? 1 : 0);
kobject_uevent_env(&sdp->sd_kobj, KOBJ_ONLINE, envp);
}
static int init_threads(struct gfs2_sbd *sdp)
{
struct task_struct *p;
int error = 0;
p = kthread_create(gfs2_logd, sdp, "gfs2_logd/%s", sdp->sd_fsname);
if (IS_ERR(p)) {
error = PTR_ERR(p);
fs_err(sdp, "can't create logd thread: %d\n", error);
return error;
}
get_task_struct(p);
sdp->sd_logd_process = p;
p = kthread_create(gfs2_quotad, sdp, "gfs2_quotad/%s", sdp->sd_fsname);
if (IS_ERR(p)) {
error = PTR_ERR(p);
fs_err(sdp, "can't create quotad thread: %d\n", error);
goto fail;
}
get_task_struct(p);
sdp->sd_quotad_process = p;
wake_up_process(sdp->sd_logd_process);
wake_up_process(sdp->sd_quotad_process);
return 0;
fail:
kthread_stop(sdp->sd_logd_process);
put_task_struct(sdp->sd_logd_process);
sdp->sd_logd_process = NULL;
return error;
}
void gfs2_destroy_threads(struct gfs2_sbd *sdp)
{
if (sdp->sd_logd_process) {
kthread_stop(sdp->sd_logd_process);
put_task_struct(sdp->sd_logd_process);
sdp->sd_logd_process = NULL;
}
if (sdp->sd_quotad_process) {
kthread_stop(sdp->sd_quotad_process);
put_task_struct(sdp->sd_quotad_process);
sdp->sd_quotad_process = NULL;
}
}
/**
* gfs2_fill_super - Read in superblock
* @sb: The VFS superblock
* @fc: Mount options and flags
*
* Returns: -errno
*/
static int gfs2_fill_super(struct super_block *sb, struct fs_context *fc)
{
struct gfs2_args *args = fc->fs_private;
int silent = fc->sb_flags & SB_SILENT;
struct gfs2_sbd *sdp;
struct gfs2_holder mount_gh;
int error;
sdp = init_sbd(sb);
if (!sdp) {
pr_warn("can't alloc struct gfs2_sbd\n");
return -ENOMEM;
}
sdp->sd_args = *args;
if (sdp->sd_args.ar_spectator) {
sb->s_flags |= SB_RDONLY;
set_bit(SDF_RORECOVERY, &sdp->sd_flags);
}
if (sdp->sd_args.ar_posix_acl)
sb->s_flags |= SB_POSIXACL;
if (sdp->sd_args.ar_nobarrier)
set_bit(SDF_NOBARRIERS, &sdp->sd_flags);
sb->s_flags |= SB_NOSEC;
sb->s_magic = GFS2_MAGIC;
sb->s_op = &gfs2_super_ops;
sb->s_d_op = &gfs2_dops;
sb->s_export_op = &gfs2_export_ops;
sb->s_qcop = &gfs2_quotactl_ops;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
sb->s_time_gran = 1;
sb->s_maxbytes = MAX_LFS_FILESIZE;
/* Set up the buffer cache and fill in some fake block size values
to allow us to read-in the on-disk superblock. */
sdp->sd_sb.sb_bsize = sb_min_blocksize(sb, GFS2_BASIC_BLOCK);
sdp->sd_sb.sb_bsize_shift = sb->s_blocksize_bits;
sdp->sd_fsb2bb_shift = sdp->sd_sb.sb_bsize_shift -
GFS2_BASIC_BLOCK_SHIFT;
sdp->sd_fsb2bb = BIT(sdp->sd_fsb2bb_shift);
sdp->sd_tune.gt_logd_secs = sdp->sd_args.ar_commit;
sdp->sd_tune.gt_quota_quantum = sdp->sd_args.ar_quota_quantum;
if (sdp->sd_args.ar_statfs_quantum) {
sdp->sd_tune.gt_statfs_slow = 0;
sdp->sd_tune.gt_statfs_quantum = sdp->sd_args.ar_statfs_quantum;
} else {
sdp->sd_tune.gt_statfs_slow = 1;
sdp->sd_tune.gt_statfs_quantum = 30;
}
error = init_names(sdp, silent);
if (error)
goto fail_free;
snprintf(sdp->sd_fsname, sizeof(sdp->sd_fsname), "%s", sdp->sd_table_name);
sdp->sd_delete_wq = alloc_workqueue("gfs2-delete/%s",
WQ_MEM_RECLAIM | WQ_FREEZABLE, 0, sdp->sd_fsname);
error = -ENOMEM;
if (!sdp->sd_delete_wq)
goto fail_free;
error = gfs2_sys_fs_add(sdp);
if (error)
goto fail_delete_wq;
gfs2_create_debugfs_file(sdp);
error = gfs2_lm_mount(sdp, silent);
if (error)
goto fail_debug;
error = init_locking(sdp, &mount_gh, DO);
if (error)
goto fail_lm;
error = init_sb(sdp, silent);
if (error)
goto fail_locking;
/* Turn rgrplvb on by default if fs format is recent enough */
if (!sdp->sd_args.ar_got_rgrplvb && sdp->sd_sb.sb_fs_format > 1801)
sdp->sd_args.ar_rgrplvb = 1;
error = wait_on_journal(sdp);
if (error)
goto fail_sb;
/*
* If user space has failed to join the cluster or some similar
* failure has occurred, then the journal id will contain a
* negative (error) number. This will then be returned to the
* caller (of the mount syscall). We do this even for spectator
* mounts (which just write a jid of 0 to indicate "ok" even though
* the jid is unused in the spectator case)
*/
if (sdp->sd_lockstruct.ls_jid < 0) {
error = sdp->sd_lockstruct.ls_jid;
sdp->sd_lockstruct.ls_jid = 0;
goto fail_sb;
}
if (sdp->sd_args.ar_spectator)
snprintf(sdp->sd_fsname, sizeof(sdp->sd_fsname), "%s.s",
sdp->sd_table_name);
else
snprintf(sdp->sd_fsname, sizeof(sdp->sd_fsname), "%s.%u",
sdp->sd_table_name, sdp->sd_lockstruct.ls_jid);
error = init_inodes(sdp, DO);
if (error)
goto fail_sb;
error = init_per_node(sdp, DO);
if (error)
goto fail_inodes;
error = gfs2_statfs_init(sdp);
if (error) {
fs_err(sdp, "can't initialize statfs subsystem: %d\n", error);
goto fail_per_node;
}
if (!sb_rdonly(sb)) {
error = init_threads(sdp);
if (error) {
gfs2_withdraw_delayed(sdp);
goto fail_per_node;
}
}
error = gfs2_freeze_lock_shared(sdp);
if (error)
goto fail_per_node;
if (!sb_rdonly(sb))
error = gfs2_make_fs_rw(sdp);
if (error) {
gfs2_freeze_unlock(&sdp->sd_freeze_gh);
gfs2_destroy_threads(sdp);
fs_err(sdp, "can't make FS RW: %d\n", error);
goto fail_per_node;
}
gfs2_glock_dq_uninit(&mount_gh);
gfs2_online_uevent(sdp);
return 0;
fail_per_node:
init_per_node(sdp, UNDO);
fail_inodes:
init_inodes(sdp, UNDO);
fail_sb:
if (sdp->sd_root_dir)
dput(sdp->sd_root_dir);
if (sdp->sd_master_dir)
dput(sdp->sd_master_dir);
if (sb->s_root)
dput(sb->s_root);
sb->s_root = NULL;
fail_locking:
init_locking(sdp, &mount_gh, UNDO);
fail_lm:
complete_all(&sdp->sd_journal_ready);
gfs2_gl_hash_clear(sdp);
gfs2_lm_unmount(sdp);
fail_debug:
gfs2_delete_debugfs_file(sdp);
gfs2_sys_fs_del(sdp);
fail_delete_wq:
destroy_workqueue(sdp->sd_delete_wq);
fail_free:
free_sbd(sdp);
sb->s_fs_info = NULL;
return error;
}
/**
* gfs2_get_tree - Get the GFS2 superblock and root directory
* @fc: The filesystem context
*
* Returns: 0 or -errno on error
*/
static int gfs2_get_tree(struct fs_context *fc)
{
struct gfs2_args *args = fc->fs_private;
struct gfs2_sbd *sdp;
int error;
error = get_tree_bdev(fc, gfs2_fill_super);
if (error)
return error;
sdp = fc->root->d_sb->s_fs_info;
dput(fc->root);
if (args->ar_meta)
fc->root = dget(sdp->sd_master_dir);
else
fc->root = dget(sdp->sd_root_dir);
return 0;
}
static void gfs2_fc_free(struct fs_context *fc)
{
struct gfs2_args *args = fc->fs_private;
kfree(args);
}
enum gfs2_param {
Opt_lockproto,
Opt_locktable,
Opt_hostdata,
Opt_spectator,
Opt_ignore_local_fs,
Opt_localflocks,
Opt_localcaching,
Opt_debug,
Opt_upgrade,
Opt_acl,
Opt_quota,
Opt_quota_flag,
Opt_suiddir,
Opt_data,
Opt_meta,
Opt_discard,
Opt_commit,
Opt_errors,
Opt_statfs_quantum,
Opt_statfs_percent,
Opt_quota_quantum,
Opt_barrier,
Opt_rgrplvb,
Opt_loccookie,
};
static const struct constant_table gfs2_param_quota[] = {
{"off", GFS2_QUOTA_OFF},
{"account", GFS2_QUOTA_ACCOUNT},
{"on", GFS2_QUOTA_ON},
{"quiet", GFS2_QUOTA_QUIET},
{}
};
enum opt_data {
Opt_data_writeback = GFS2_DATA_WRITEBACK,
Opt_data_ordered = GFS2_DATA_ORDERED,
};
static const struct constant_table gfs2_param_data[] = {
{"writeback", Opt_data_writeback },
{"ordered", Opt_data_ordered },
{}
};
enum opt_errors {
Opt_errors_withdraw = GFS2_ERRORS_WITHDRAW,
Opt_errors_panic = GFS2_ERRORS_PANIC,
};
static const struct constant_table gfs2_param_errors[] = {
{"withdraw", Opt_errors_withdraw },
{"panic", Opt_errors_panic },
{}
};
static const struct fs_parameter_spec gfs2_fs_parameters[] = {
fsparam_string ("lockproto", Opt_lockproto),
fsparam_string ("locktable", Opt_locktable),
fsparam_string ("hostdata", Opt_hostdata),
fsparam_flag ("spectator", Opt_spectator),
fsparam_flag ("norecovery", Opt_spectator),
fsparam_flag ("ignore_local_fs", Opt_ignore_local_fs),
fsparam_flag ("localflocks", Opt_localflocks),
fsparam_flag ("localcaching", Opt_localcaching),
fsparam_flag_no("debug", Opt_debug),
fsparam_flag ("upgrade", Opt_upgrade),
fsparam_flag_no("acl", Opt_acl),
fsparam_flag_no("suiddir", Opt_suiddir),
fsparam_enum ("data", Opt_data, gfs2_param_data),
fsparam_flag ("meta", Opt_meta),
fsparam_flag_no("discard", Opt_discard),
fsparam_s32 ("commit", Opt_commit),
fsparam_enum ("errors", Opt_errors, gfs2_param_errors),
fsparam_s32 ("statfs_quantum", Opt_statfs_quantum),
fsparam_s32 ("statfs_percent", Opt_statfs_percent),
fsparam_s32 ("quota_quantum", Opt_quota_quantum),
fsparam_flag_no("barrier", Opt_barrier),
fsparam_flag_no("rgrplvb", Opt_rgrplvb),
fsparam_flag_no("loccookie", Opt_loccookie),
/* quota can be a flag or an enum so it gets special treatment */
fsparam_flag_no("quota", Opt_quota_flag),
fsparam_enum("quota", Opt_quota, gfs2_param_quota),
{}
};
/* Parse a single mount parameter */
static int gfs2_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
struct gfs2_args *args = fc->fs_private;
struct fs_parse_result result;
int o;
o = fs_parse(fc, gfs2_fs_parameters, param, &result);
if (o < 0)
return o;
switch (o) {
case Opt_lockproto:
strscpy(args->ar_lockproto, param->string, GFS2_LOCKNAME_LEN);
break;
case Opt_locktable:
strscpy(args->ar_locktable, param->string, GFS2_LOCKNAME_LEN);
break;
case Opt_hostdata:
strscpy(args->ar_hostdata, param->string, GFS2_LOCKNAME_LEN);
break;
case Opt_spectator:
args->ar_spectator = 1;
break;
case Opt_ignore_local_fs:
/* Retained for backwards compat only */
break;
case Opt_localflocks:
args->ar_localflocks = 1;
break;
case Opt_localcaching:
/* Retained for backwards compat only */
break;
case Opt_debug:
if (result.boolean && args->ar_errors == GFS2_ERRORS_PANIC)
return invalfc(fc, "-o debug and -o errors=panic are mutually exclusive");
args->ar_debug = result.boolean;
break;
case Opt_upgrade:
/* Retained for backwards compat only */
break;
case Opt_acl:
args->ar_posix_acl = result.boolean;
break;
case Opt_quota_flag:
args->ar_quota = result.negated ? GFS2_QUOTA_OFF : GFS2_QUOTA_ON;
break;
case Opt_quota:
args->ar_quota = result.int_32;
break;
case Opt_suiddir:
args->ar_suiddir = result.boolean;
break;
case Opt_data:
/* The uint_32 result maps directly to GFS2_DATA_* */
args->ar_data = result.uint_32;
break;
case Opt_meta:
args->ar_meta = 1;
break;
case Opt_discard:
args->ar_discard = result.boolean;
break;
case Opt_commit:
if (result.int_32 <= 0)
return invalfc(fc, "commit mount option requires a positive numeric argument");
args->ar_commit = result.int_32;
break;
case Opt_statfs_quantum:
if (result.int_32 < 0)
return invalfc(fc, "statfs_quantum mount option requires a non-negative numeric argument");
args->ar_statfs_quantum = result.int_32;
break;
case Opt_quota_quantum:
if (result.int_32 <= 0)
return invalfc(fc, "quota_quantum mount option requires a positive numeric argument");
args->ar_quota_quantum = result.int_32;
break;
case Opt_statfs_percent:
if (result.int_32 < 0 || result.int_32 > 100)
return invalfc(fc, "statfs_percent mount option requires a numeric argument between 0 and 100");
args->ar_statfs_percent = result.int_32;
break;
case Opt_errors:
if (args->ar_debug && result.uint_32 == GFS2_ERRORS_PANIC)
return invalfc(fc, "-o debug and -o errors=panic are mutually exclusive");
args->ar_errors = result.uint_32;
break;
case Opt_barrier:
args->ar_nobarrier = result.boolean;
break;
case Opt_rgrplvb:
args->ar_rgrplvb = result.boolean;
args->ar_got_rgrplvb = 1;
break;
case Opt_loccookie:
args->ar_loccookie = result.boolean;
break;
default:
return invalfc(fc, "invalid mount option: %s", param->key);
}
return 0;
}
static int gfs2_reconfigure(struct fs_context *fc)
{
struct super_block *sb = fc->root->d_sb;
struct gfs2_sbd *sdp = sb->s_fs_info;
struct gfs2_args *oldargs = &sdp->sd_args;
struct gfs2_args *newargs = fc->fs_private;
struct gfs2_tune *gt = &sdp->sd_tune;
int error = 0;
sync_filesystem(sb);
spin_lock(>->gt_spin);
oldargs->ar_commit = gt->gt_logd_secs;
oldargs->ar_quota_quantum = gt->gt_quota_quantum;
if (gt->gt_statfs_slow)
oldargs->ar_statfs_quantum = 0;
else
oldargs->ar_statfs_quantum = gt->gt_statfs_quantum;
spin_unlock(>->gt_spin);
if (strcmp(newargs->ar_lockproto, oldargs->ar_lockproto)) {
errorfc(fc, "reconfiguration of locking protocol not allowed");
return -EINVAL;
}
if (strcmp(newargs->ar_locktable, oldargs->ar_locktable)) {
errorfc(fc, "reconfiguration of lock table not allowed");
return -EINVAL;
}
if (strcmp(newargs->ar_hostdata, oldargs->ar_hostdata)) {
errorfc(fc, "reconfiguration of host data not allowed");
return -EINVAL;
}
if (newargs->ar_spectator != oldargs->ar_spectator) {
errorfc(fc, "reconfiguration of spectator mode not allowed");
return -EINVAL;
}
if (newargs->ar_localflocks != oldargs->ar_localflocks) {
errorfc(fc, "reconfiguration of localflocks not allowed");
return -EINVAL;
}
if (newargs->ar_meta != oldargs->ar_meta) {
errorfc(fc, "switching between gfs2 and gfs2meta not allowed");
return -EINVAL;
}
if (oldargs->ar_spectator)
fc->sb_flags |= SB_RDONLY;
if ((sb->s_flags ^ fc->sb_flags) & SB_RDONLY) {
if (fc->sb_flags & SB_RDONLY) {
gfs2_make_fs_ro(sdp);
} else {
error = gfs2_make_fs_rw(sdp);
if (error)
errorfc(fc, "unable to remount read-write");
}
}
sdp->sd_args = *newargs;
if (sdp->sd_args.ar_posix_acl)
sb->s_flags |= SB_POSIXACL;
else
sb->s_flags &= ~SB_POSIXACL;
if (sdp->sd_args.ar_nobarrier)
set_bit(SDF_NOBARRIERS, &sdp->sd_flags);
else
clear_bit(SDF_NOBARRIERS, &sdp->sd_flags);
spin_lock(>->gt_spin);
gt->gt_logd_secs = newargs->ar_commit;
gt->gt_quota_quantum = newargs->ar_quota_quantum;
if (newargs->ar_statfs_quantum) {
gt->gt_statfs_slow = 0;
gt->gt_statfs_quantum = newargs->ar_statfs_quantum;
}
else {
gt->gt_statfs_slow = 1;
gt->gt_statfs_quantum = 30;
}
spin_unlock(>->gt_spin);
gfs2_online_uevent(sdp);
return error;
}
static const struct fs_context_operations gfs2_context_ops = {
.free = gfs2_fc_free,
.parse_param = gfs2_parse_param,
.get_tree = gfs2_get_tree,
.reconfigure = gfs2_reconfigure,
};
/* Set up the filesystem mount context */
static int gfs2_init_fs_context(struct fs_context *fc)
{
struct gfs2_args *args;
args = kmalloc(sizeof(*args), GFP_KERNEL);
if (args == NULL)
return -ENOMEM;
if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
struct gfs2_sbd *sdp = fc->root->d_sb->s_fs_info;
*args = sdp->sd_args;
} else {
memset(args, 0, sizeof(*args));
args->ar_quota = GFS2_QUOTA_DEFAULT;
args->ar_data = GFS2_DATA_DEFAULT;
args->ar_commit = 30;
args->ar_statfs_quantum = 30;
args->ar_quota_quantum = 60;
args->ar_errors = GFS2_ERRORS_DEFAULT;
}
fc->fs_private = args;
fc->ops = &gfs2_context_ops;
return 0;
}
static int set_meta_super(struct super_block *s, struct fs_context *fc)
{
return -EINVAL;
}
static int test_meta_super(struct super_block *s, struct fs_context *fc)
{
return (fc->sget_key == s->s_bdev);
}
static int gfs2_meta_get_tree(struct fs_context *fc)
{
struct super_block *s;
struct gfs2_sbd *sdp;
struct path path;
int error;
if (!fc->source || !*fc->source)
return -EINVAL;
error = kern_path(fc->source, LOOKUP_FOLLOW, &path);
if (error) {
pr_warn("path_lookup on %s returned error %d\n",
fc->source, error);
return error;
}
fc->fs_type = &gfs2_fs_type;
fc->sget_key = path.dentry->d_sb->s_bdev;
s = sget_fc(fc, test_meta_super, set_meta_super);
path_put(&path);
if (IS_ERR(s)) {
pr_warn("gfs2 mount does not exist\n");
return PTR_ERR(s);
}
if ((fc->sb_flags ^ s->s_flags) & SB_RDONLY) {
deactivate_locked_super(s);
return -EBUSY;
}
sdp = s->s_fs_info;
fc->root = dget(sdp->sd_master_dir);
return 0;
}
static const struct fs_context_operations gfs2_meta_context_ops = {
.free = gfs2_fc_free,
.get_tree = gfs2_meta_get_tree,
};
static int gfs2_meta_init_fs_context(struct fs_context *fc)
{
int ret = gfs2_init_fs_context(fc);
if (ret)
return ret;
fc->ops = &gfs2_meta_context_ops;
return 0;
}
/**
* gfs2_evict_inodes - evict inodes cooperatively
* @sb: the superblock
*
* When evicting an inode with a zero link count, we are trying to upgrade the
* inode's iopen glock from SH to EX mode in order to determine if we can
* delete the inode. The other nodes are supposed to evict the inode from
* their caches if they can, and to poke the inode's inode glock if they cannot
* do so. Either behavior allows gfs2_upgrade_iopen_glock() to proceed
* quickly, but if the other nodes are not cooperating, the lock upgrading
* attempt will time out. Since inodes are evicted sequentially, this can add
* up quickly.
*
* Function evict_inodes() tries to keep the s_inode_list_lock list locked over
* a long time, which prevents other inodes from being evicted concurrently.
* This precludes the cooperative behavior we are looking for. This special
* version of evict_inodes() avoids that.
*
* Modeled after drop_pagecache_sb().
*/
static void gfs2_evict_inodes(struct super_block *sb)
{
struct inode *inode, *toput_inode = NULL;
struct gfs2_sbd *sdp = sb->s_fs_info;
set_bit(SDF_EVICTING, &sdp->sd_flags);
spin_lock(&sb->s_inode_list_lock);
list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
spin_lock(&inode->i_lock);
if ((inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) &&
!need_resched()) {
spin_unlock(&inode->i_lock);
continue;
}
atomic_inc(&inode->i_count);
spin_unlock(&inode->i_lock);
spin_unlock(&sb->s_inode_list_lock);
iput(toput_inode);
toput_inode = inode;
cond_resched();
spin_lock(&sb->s_inode_list_lock);
}
spin_unlock(&sb->s_inode_list_lock);
iput(toput_inode);
}
static void gfs2_kill_sb(struct super_block *sb)
{
struct gfs2_sbd *sdp = sb->s_fs_info;
if (sdp == NULL) {
kill_block_super(sb);
return;
}
gfs2_log_flush(sdp, NULL, GFS2_LOG_HEAD_FLUSH_SYNC | GFS2_LFC_KILL_SB);
dput(sdp->sd_root_dir);
dput(sdp->sd_master_dir);
sdp->sd_root_dir = NULL;
sdp->sd_master_dir = NULL;
shrink_dcache_sb(sb);
gfs2_evict_inodes(sb);
/*
* Flush and then drain the delete workqueue here (via
* destroy_workqueue()) to ensure that any delete work that
* may be running will also see the SDF_KILL flag.
*/
set_bit(SDF_KILL, &sdp->sd_flags);
gfs2_flush_delete_work(sdp);
destroy_workqueue(sdp->sd_delete_wq);
kill_block_super(sb);
}
struct file_system_type gfs2_fs_type = {
.name = "gfs2",
.fs_flags = FS_REQUIRES_DEV,
.init_fs_context = gfs2_init_fs_context,
.parameters = gfs2_fs_parameters,
.kill_sb = gfs2_kill_sb,
.owner = THIS_MODULE,
};
MODULE_ALIAS_FS("gfs2");
struct file_system_type gfs2meta_fs_type = {
.name = "gfs2meta",
.fs_flags = FS_REQUIRES_DEV,
.init_fs_context = gfs2_meta_init_fs_context,
.owner = THIS_MODULE,
};
MODULE_ALIAS_FS("gfs2meta");
| linux-master | fs/gfs2/ops_fstype.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/namei.h>
#include <linux/crc32.h>
#include "gfs2.h"
#include "incore.h"
#include "dir.h"
#include "glock.h"
#include "super.h"
#include "util.h"
#include "inode.h"
/**
* gfs2_drevalidate - Check directory lookup consistency
* @dentry: the mapping to check
* @flags: lookup flags
*
* Check to make sure the lookup necessary to arrive at this inode from its
* parent is still good.
*
* Returns: 1 if the dentry is ok, 0 if it isn't
*/
static int gfs2_drevalidate(struct dentry *dentry, unsigned int flags)
{
struct dentry *parent;
struct gfs2_sbd *sdp;
struct gfs2_inode *dip;
struct inode *inode;
struct gfs2_holder d_gh;
struct gfs2_inode *ip = NULL;
int error, valid = 0;
int had_lock = 0;
if (flags & LOOKUP_RCU)
return -ECHILD;
parent = dget_parent(dentry);
sdp = GFS2_SB(d_inode(parent));
dip = GFS2_I(d_inode(parent));
inode = d_inode(dentry);
if (inode) {
if (is_bad_inode(inode))
goto out;
ip = GFS2_I(inode);
}
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL) {
valid = 1;
goto out;
}
had_lock = (gfs2_glock_is_locked_by_me(dip->i_gl) != NULL);
if (!had_lock) {
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
if (error)
goto out;
}
error = gfs2_dir_check(d_inode(parent), &dentry->d_name, ip);
valid = inode ? !error : (error == -ENOENT);
if (!had_lock)
gfs2_glock_dq_uninit(&d_gh);
out:
dput(parent);
return valid;
}
static int gfs2_dhash(const struct dentry *dentry, struct qstr *str)
{
str->hash = gfs2_disk_hash(str->name, str->len);
return 0;
}
static int gfs2_dentry_delete(const struct dentry *dentry)
{
struct gfs2_inode *ginode;
if (d_really_is_negative(dentry))
return 0;
ginode = GFS2_I(d_inode(dentry));
if (!gfs2_holder_initialized(&ginode->i_iopen_gh))
return 0;
if (test_bit(GLF_DEMOTE, &ginode->i_iopen_gh.gh_gl->gl_flags))
return 1;
return 0;
}
const struct dentry_operations gfs2_dops = {
.d_revalidate = gfs2_drevalidate,
.d_hash = gfs2_dhash,
.d_delete = gfs2_dentry_delete,
};
| linux-master | fs/gfs2/dentry.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/dax.h>
#include <linux/uaccess.h>
#include <linux/iversion.h>
#include <linux/unicode.h>
#include <linux/part_stat.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/fsnotify.h>
#include <linux/fs_context.h>
#include <linux/fs_parser.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#include "fsmap.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct ext4_lazy_init *ext4_li_info;
static DEFINE_MUTEX(ext4_li_mtx);
static struct ratelimit_state ext4_mount_msg_ratelimit;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static void ext4_update_super(struct super_block *sb);
static int ext4_commit_super(struct super_block *sb);
static int ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
static struct inode *ext4_get_journal_inode(struct super_block *sb,
unsigned int journal_inum);
static int ext4_validate_options(struct fs_context *fc);
static int ext4_check_opt_consistency(struct fs_context *fc,
struct super_block *sb);
static void ext4_apply_options(struct fs_context *fc, struct super_block *sb);
static int ext4_parse_param(struct fs_context *fc, struct fs_parameter *param);
static int ext4_get_tree(struct fs_context *fc);
static int ext4_reconfigure(struct fs_context *fc);
static void ext4_fc_free(struct fs_context *fc);
static int ext4_init_fs_context(struct fs_context *fc);
static void ext4_kill_sb(struct super_block *sb);
static const struct fs_parameter_spec ext4_param_specs[];
/*
* Lock ordering
*
* page fault path:
* mmap_lock -> sb_start_pagefault -> invalidate_lock (r) -> transaction start
* -> page lock -> i_data_sem (rw)
*
* buffered write path:
* sb_start_write -> i_mutex -> mmap_lock
* sb_start_write -> i_mutex -> transaction start -> page lock ->
* i_data_sem (rw)
*
* truncate:
* sb_start_write -> i_mutex -> invalidate_lock (w) -> i_mmap_rwsem (w) ->
* page lock
* sb_start_write -> i_mutex -> invalidate_lock (w) -> transaction start ->
* i_data_sem (rw)
*
* direct IO:
* sb_start_write -> i_mutex -> mmap_lock
* sb_start_write -> i_mutex -> transaction start -> i_data_sem (rw)
*
* writepages:
* transaction start -> page lock(s) -> i_data_sem (rw)
*/
static const struct fs_context_operations ext4_context_ops = {
.parse_param = ext4_parse_param,
.get_tree = ext4_get_tree,
.reconfigure = ext4_reconfigure,
.free = ext4_fc_free,
};
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.init_fs_context = ext4_init_fs_context,
.parameters = ext4_param_specs,
.kill_sb = ext4_kill_sb,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_type == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.init_fs_context = ext4_init_fs_context,
.parameters = ext4_param_specs,
.kill_sb = ext4_kill_sb,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_type == &ext3_fs_type)
static inline void __ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags,
bh_end_io_t *end_io)
{
/*
* buffer's verified bit is no longer valid after reading from
* disk again due to write out error, clear it to make sure we
* recheck the buffer contents.
*/
clear_buffer_verified(bh);
bh->b_end_io = end_io ? end_io : end_buffer_read_sync;
get_bh(bh);
submit_bh(REQ_OP_READ | op_flags, bh);
}
void ext4_read_bh_nowait(struct buffer_head *bh, blk_opf_t op_flags,
bh_end_io_t *end_io)
{
BUG_ON(!buffer_locked(bh));
if (ext4_buffer_uptodate(bh)) {
unlock_buffer(bh);
return;
}
__ext4_read_bh(bh, op_flags, end_io);
}
int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags, bh_end_io_t *end_io)
{
BUG_ON(!buffer_locked(bh));
if (ext4_buffer_uptodate(bh)) {
unlock_buffer(bh);
return 0;
}
__ext4_read_bh(bh, op_flags, end_io);
wait_on_buffer(bh);
if (buffer_uptodate(bh))
return 0;
return -EIO;
}
int ext4_read_bh_lock(struct buffer_head *bh, blk_opf_t op_flags, bool wait)
{
lock_buffer(bh);
if (!wait) {
ext4_read_bh_nowait(bh, op_flags, NULL);
return 0;
}
return ext4_read_bh(bh, op_flags, NULL);
}
/*
* This works like __bread_gfp() except it uses ERR_PTR for error
* returns. Currently with sb_bread it's impossible to distinguish
* between ENOMEM and EIO situations (since both result in a NULL
* return.
*/
static struct buffer_head *__ext4_sb_bread_gfp(struct super_block *sb,
sector_t block,
blk_opf_t op_flags, gfp_t gfp)
{
struct buffer_head *bh;
int ret;
bh = sb_getblk_gfp(sb, block, gfp);
if (bh == NULL)
return ERR_PTR(-ENOMEM);
if (ext4_buffer_uptodate(bh))
return bh;
ret = ext4_read_bh_lock(bh, REQ_META | op_flags, true);
if (ret) {
put_bh(bh);
return ERR_PTR(ret);
}
return bh;
}
struct buffer_head *ext4_sb_bread(struct super_block *sb, sector_t block,
blk_opf_t op_flags)
{
return __ext4_sb_bread_gfp(sb, block, op_flags, __GFP_MOVABLE);
}
struct buffer_head *ext4_sb_bread_unmovable(struct super_block *sb,
sector_t block)
{
return __ext4_sb_bread_gfp(sb, block, 0, 0);
}
void ext4_sb_breadahead_unmovable(struct super_block *sb, sector_t block)
{
struct buffer_head *bh = sb_getblk_gfp(sb, block, 0);
if (likely(bh)) {
if (trylock_buffer(bh))
ext4_read_bh_nowait(bh, REQ_RAHEAD, NULL);
brelse(bh);
}
}
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_feature_metadata_csum(sb))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
__le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
static int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!ext4_has_metadata_csum(sb))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __ext4_update_tstamp(__le32 *lo, __u8 *hi, time64_t now)
{
now = clamp_val(now, 0, (1ull << 40) - 1);
*lo = cpu_to_le32(lower_32_bits(now));
*hi = upper_32_bits(now);
}
static time64_t __ext4_get_tstamp(__le32 *lo, __u8 *hi)
{
return ((time64_t)(*hi) << 32) + le32_to_cpu(*lo);
}
#define ext4_update_tstamp(es, tstamp) \
__ext4_update_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi, \
ktime_get_real_seconds())
#define ext4_get_tstamp(es, tstamp) \
__ext4_get_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
#define EXT4_SB_REFRESH_INTERVAL_SEC (3600) /* seconds (1 hour) */
#define EXT4_SB_REFRESH_INTERVAL_KB (16384) /* kilobytes (16MB) */
/*
* The ext4_maybe_update_superblock() function checks and updates the
* superblock if needed.
*
* This function is designed to update the on-disk superblock only under
* certain conditions to prevent excessive disk writes and unnecessary
* waking of the disk from sleep. The superblock will be updated if:
* 1. More than an hour has passed since the last superblock update, and
* 2. More than 16MB have been written since the last superblock update.
*
* @sb: The superblock
*/
static void ext4_maybe_update_superblock(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
journal_t *journal = sbi->s_journal;
time64_t now;
__u64 last_update;
__u64 lifetime_write_kbytes;
__u64 diff_size;
if (sb_rdonly(sb) || !(sb->s_flags & SB_ACTIVE) ||
!journal || (journal->j_flags & JBD2_UNMOUNT))
return;
now = ktime_get_real_seconds();
last_update = ext4_get_tstamp(es, s_wtime);
if (likely(now - last_update < EXT4_SB_REFRESH_INTERVAL_SEC))
return;
lifetime_write_kbytes = sbi->s_kbytes_written +
((part_stat_read(sb->s_bdev, sectors[STAT_WRITE]) -
sbi->s_sectors_written_start) >> 1);
/* Get the number of kilobytes not written to disk to account
* for statistics and compare with a multiple of 16 MB. This
* is used to determine when the next superblock commit should
* occur (i.e. not more often than once per 16MB if there was
* less written in an hour).
*/
diff_size = lifetime_write_kbytes - le64_to_cpu(es->s_kbytes_written);
if (diff_size > EXT4_SB_REFRESH_INTERVAL_KB)
schedule_work(&EXT4_SB(sb)->s_sb_upd_work);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
ext4_process_freed_data(sb, txn->t_tid);
ext4_maybe_update_superblock(sb);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/*
* This writepage callback for write_cache_pages()
* takes care of a few cases after page cleaning.
*
* write_cache_pages() already checks for dirty pages
* and calls clear_page_dirty_for_io(), which we want,
* to write protect the pages.
*
* However, we may have to redirty a page (see below.)
*/
static int ext4_journalled_writepage_callback(struct folio *folio,
struct writeback_control *wbc,
void *data)
{
transaction_t *transaction = (transaction_t *) data;
struct buffer_head *bh, *head;
struct journal_head *jh;
bh = head = folio_buffers(folio);
do {
/*
* We have to redirty a page in these cases:
* 1) If buffer is dirty, it means the page was dirty because it
* contains a buffer that needs checkpointing. So the dirty bit
* needs to be preserved so that checkpointing writes the buffer
* properly.
* 2) If buffer is not part of the committing transaction
* (we may have just accidentally come across this buffer because
* inode range tracking is not exact) or if the currently running
* transaction already contains this buffer as well, dirty bit
* needs to be preserved so that the buffer gets writeprotected
* properly on running transaction's commit.
*/
jh = bh2jh(bh);
if (buffer_dirty(bh) ||
(jh && (jh->b_transaction != transaction ||
jh->b_next_transaction))) {
folio_redirty_for_writepage(wbc, folio);
goto out;
}
} while ((bh = bh->b_this_page) != head);
out:
return AOP_WRITEPAGE_ACTIVATE;
}
static int ext4_journalled_submit_inode_data_buffers(struct jbd2_inode *jinode)
{
struct address_space *mapping = jinode->i_vfs_inode->i_mapping;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = LONG_MAX,
.range_start = jinode->i_dirty_start,
.range_end = jinode->i_dirty_end,
};
return write_cache_pages(mapping, &wbc,
ext4_journalled_writepage_callback,
jinode->i_transaction);
}
static int ext4_journal_submit_inode_data_buffers(struct jbd2_inode *jinode)
{
int ret;
if (ext4_should_journal_data(jinode->i_vfs_inode))
ret = ext4_journalled_submit_inode_data_buffers(jinode);
else
ret = ext4_normal_submit_inode_data_buffers(jinode);
return ret;
}
static int ext4_journal_finish_inode_data_buffers(struct jbd2_inode *jinode)
{
int ret = 0;
if (!ext4_should_journal_data(jinode->i_vfs_inode))
ret = jbd2_journal_finish_inode_data_buffers(jinode);
return ret;
}
static bool system_going_down(void)
{
return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
|| system_state == SYSTEM_RESTART;
}
struct ext4_err_translation {
int code;
int errno;
};
#define EXT4_ERR_TRANSLATE(err) { .code = EXT4_ERR_##err, .errno = err }
static struct ext4_err_translation err_translation[] = {
EXT4_ERR_TRANSLATE(EIO),
EXT4_ERR_TRANSLATE(ENOMEM),
EXT4_ERR_TRANSLATE(EFSBADCRC),
EXT4_ERR_TRANSLATE(EFSCORRUPTED),
EXT4_ERR_TRANSLATE(ENOSPC),
EXT4_ERR_TRANSLATE(ENOKEY),
EXT4_ERR_TRANSLATE(EROFS),
EXT4_ERR_TRANSLATE(EFBIG),
EXT4_ERR_TRANSLATE(EEXIST),
EXT4_ERR_TRANSLATE(ERANGE),
EXT4_ERR_TRANSLATE(EOVERFLOW),
EXT4_ERR_TRANSLATE(EBUSY),
EXT4_ERR_TRANSLATE(ENOTDIR),
EXT4_ERR_TRANSLATE(ENOTEMPTY),
EXT4_ERR_TRANSLATE(ESHUTDOWN),
EXT4_ERR_TRANSLATE(EFAULT),
};
static int ext4_errno_to_code(int errno)
{
int i;
for (i = 0; i < ARRAY_SIZE(err_translation); i++)
if (err_translation[i].errno == errno)
return err_translation[i].code;
return EXT4_ERR_UNKNOWN;
}
static void save_error_info(struct super_block *sb, int error,
__u32 ino, __u64 block,
const char *func, unsigned int line)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* We default to EFSCORRUPTED error... */
if (error == 0)
error = EFSCORRUPTED;
spin_lock(&sbi->s_error_lock);
sbi->s_add_error_count++;
sbi->s_last_error_code = error;
sbi->s_last_error_line = line;
sbi->s_last_error_ino = ino;
sbi->s_last_error_block = block;
sbi->s_last_error_func = func;
sbi->s_last_error_time = ktime_get_real_seconds();
if (!sbi->s_first_error_time) {
sbi->s_first_error_code = error;
sbi->s_first_error_line = line;
sbi->s_first_error_ino = ino;
sbi->s_first_error_block = block;
sbi->s_first_error_func = func;
sbi->s_first_error_time = sbi->s_last_error_time;
}
spin_unlock(&sbi->s_error_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*
* If force_ro is set, we unconditionally force the filesystem into an
* ABORT|READONLY state, unless the error response on the fs has been set to
* panic in which case we take the easy way out and panic immediately. This is
* used to deal with unrecoverable failures such as journal IO errors or ENOMEM
* at a critical moment in log management.
*/
static void ext4_handle_error(struct super_block *sb, bool force_ro, int error,
__u32 ino, __u64 block,
const char *func, unsigned int line)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
bool continue_fs = !force_ro && test_opt(sb, ERRORS_CONT);
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
if (test_opt(sb, WARN_ON_ERROR))
WARN_ON_ONCE(1);
if (!continue_fs && !sb_rdonly(sb)) {
set_bit(EXT4_FLAGS_SHUTDOWN, &EXT4_SB(sb)->s_ext4_flags);
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (!bdev_read_only(sb->s_bdev)) {
save_error_info(sb, error, ino, block, func, line);
/*
* In case the fs should keep running, we need to writeout
* superblock through the journal. Due to lock ordering
* constraints, it may not be safe to do it right here so we
* defer superblock flushing to a workqueue.
*/
if (continue_fs && journal)
schedule_work(&EXT4_SB(sb)->s_sb_upd_work);
else
ext4_commit_super(sb);
}
/*
* We force ERRORS_RO behavior when system is rebooting. Otherwise we
* could panic during 'reboot -f' as the underlying device got already
* disabled.
*/
if (test_opt(sb, ERRORS_PANIC) && !system_going_down()) {
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
if (sb_rdonly(sb) || continue_fs)
return;
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible before
* ->s_flags update
*/
smp_wmb();
sb->s_flags |= SB_RDONLY;
}
static void update_super_work(struct work_struct *work)
{
struct ext4_sb_info *sbi = container_of(work, struct ext4_sb_info,
s_sb_upd_work);
journal_t *journal = sbi->s_journal;
handle_t *handle;
/*
* If the journal is still running, we have to write out superblock
* through the journal to avoid collisions of other journalled sb
* updates.
*
* We use directly jbd2 functions here to avoid recursing back into
* ext4 error handling code during handling of previous errors.
*/
if (!sb_rdonly(sbi->s_sb) && journal) {
struct buffer_head *sbh = sbi->s_sbh;
bool call_notify_err;
handle = jbd2_journal_start(journal, 1);
if (IS_ERR(handle))
goto write_directly;
if (jbd2_journal_get_write_access(handle, sbh)) {
jbd2_journal_stop(handle);
goto write_directly;
}
if (sbi->s_add_error_count > 0)
call_notify_err = true;
ext4_update_super(sbi->s_sb);
if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
ext4_msg(sbi->s_sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
if (jbd2_journal_dirty_metadata(handle, sbh)) {
jbd2_journal_stop(handle);
goto write_directly;
}
jbd2_journal_stop(handle);
if (call_notify_err)
ext4_notify_error_sysfs(sbi);
return;
}
write_directly:
/*
* Write through journal failed. Write sb directly to get error info
* out and hope for the best.
*/
ext4_commit_super(sbi->s_sb);
ext4_notify_error_sysfs(sbi);
}
#define ext4_error_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state), \
"EXT4-fs error")
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, bool force_ro, int error, __u64 block,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (unlikely(ext4_forced_shutdown(sb)))
return;
trace_ext4_error(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
}
fsnotify_sb_error(sb, NULL, error ? error : EFSCORRUPTED);
ext4_handle_error(sb, force_ro, error, 0, block, function, line);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block, int error,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return;
trace_ext4_error(inode->i_sb, function, line);
if (ext4_error_ratelimit(inode->i_sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
}
fsnotify_sb_error(inode->i_sb, inode, error ? error : EFSCORRUPTED);
ext4_handle_error(inode->i_sb, false, error, inode->i_ino, block,
function, line);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct inode *inode = file_inode(file);
char pathname[80], *path;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return;
trace_ext4_error(inode->i_sb, function, line);
if (ext4_error_ratelimit(inode->i_sb)) {
path = file_path(file, pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
}
fsnotify_sb_error(inode->i_sb, inode, EFSCORRUPTED);
ext4_handle_error(inode->i_sb, false, EFSCORRUPTED, inode->i_ino, block,
function, line);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EFSCORRUPTED:
errstr = "Corrupt filesystem";
break;
case -EFSBADCRC:
errstr = "Filesystem failed CRC";
break;
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
if (unlikely(ext4_forced_shutdown(sb)))
return;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL && sb_rdonly(sb))
return;
if (ext4_error_ratelimit(sb)) {
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
}
fsnotify_sb_error(sb, NULL, errno ? errno : EFSCORRUPTED);
ext4_handle_error(sb, false, -errno, 0, 0, function, line);
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (sb) {
atomic_inc(&EXT4_SB(sb)->s_msg_count);
if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state),
"EXT4-fs"))
return;
}
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (sb)
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
else
printk("%sEXT4-fs: %pV\n", prefix, &vaf);
va_end(args);
}
static int ext4_warning_ratelimit(struct super_block *sb)
{
atomic_inc(&EXT4_SB(sb)->s_warning_count);
return ___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state),
"EXT4-fs warning");
}
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_warning_inode(const struct inode *inode, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(inode->i_sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
function, line, inode->i_ino, current->comm, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
if (unlikely(ext4_forced_shutdown(sb)))
return;
trace_ext4_error(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:",
(unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
}
if (test_opt(sb, ERRORS_CONT)) {
if (test_opt(sb, WARN_ON_ERROR))
WARN_ON_ONCE(1);
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
if (!bdev_read_only(sb->s_bdev)) {
save_error_info(sb, EFSCORRUPTED, ino, block, function,
line);
schedule_work(&EXT4_SB(sb)->s_sb_upd_work);
}
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb, false, EFSCORRUPTED, ino, block, function, line);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_mark_group_bitmap_corrupted(struct super_block *sb,
ext4_group_t group,
unsigned int flags)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
int ret;
if (!grp || !gdp)
return;
if (flags & EXT4_GROUP_INFO_BBITMAP_CORRUPT) {
ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
&grp->bb_state);
if (!ret)
percpu_counter_sub(&sbi->s_freeclusters_counter,
grp->bb_free);
}
if (flags & EXT4_GROUP_INFO_IBITMAP_CORRUPT) {
ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT,
&grp->bb_state);
if (!ret && gdp) {
int count;
count = ext4_free_inodes_count(sb, gdp);
percpu_counter_sub(&sbi->s_freeinodes_counter,
count);
}
}
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
#ifdef CONFIG_QUOTA
static int ext4_quota_off(struct super_block *sb, int type);
static inline void ext4_quotas_off(struct super_block *sb, int type)
{
BUG_ON(type > EXT4_MAXQUOTAS);
/* Use our quota_off function to clear inode flags etc. */
for (type--; type >= 0; type--)
ext4_quota_off(sb, type);
}
/*
* This is a helper function which is used in the mount/remount
* codepaths (which holds s_umount) to fetch the quota file name.
*/
static inline char *get_qf_name(struct super_block *sb,
struct ext4_sb_info *sbi,
int type)
{
return rcu_dereference_protected(sbi->s_qf_names[type],
lockdep_is_held(&sb->s_umount));
}
#else
static inline void ext4_quotas_off(struct super_block *sb, int type)
{
}
#endif
static int ext4_percpu_param_init(struct ext4_sb_info *sbi)
{
ext4_fsblk_t block;
int err;
block = ext4_count_free_clusters(sbi->s_sb);
ext4_free_blocks_count_set(sbi->s_es, EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sbi->s_sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sbi->s_sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_sra_exceeded_retry_limit, 0,
GFP_KERNEL);
if (!err)
err = percpu_init_rwsem(&sbi->s_writepages_rwsem);
if (err)
ext4_msg(sbi->s_sb, KERN_ERR, "insufficient memory");
return err;
}
static void ext4_percpu_param_destroy(struct ext4_sb_info *sbi)
{
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
percpu_counter_destroy(&sbi->s_sra_exceeded_retry_limit);
percpu_free_rwsem(&sbi->s_writepages_rwsem);
}
static void ext4_group_desc_free(struct ext4_sb_info *sbi)
{
struct buffer_head **group_desc;
int i;
rcu_read_lock();
group_desc = rcu_dereference(sbi->s_group_desc);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(group_desc[i]);
kvfree(group_desc);
rcu_read_unlock();
}
static void ext4_flex_groups_free(struct ext4_sb_info *sbi)
{
struct flex_groups **flex_groups;
int i;
rcu_read_lock();
flex_groups = rcu_dereference(sbi->s_flex_groups);
if (flex_groups) {
for (i = 0; i < sbi->s_flex_groups_allocated; i++)
kvfree(flex_groups[i]);
kvfree(flex_groups);
}
rcu_read_unlock();
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int aborted = 0;
int err;
/*
* Unregister sysfs before destroying jbd2 journal.
* Since we could still access attr_journal_task attribute via sysfs
* path which could have sbi->s_journal->j_task as NULL
* Unregister sysfs before flush sbi->s_sb_upd_work.
* Since user may read /proc/fs/ext4/xx/mb_groups during umount, If
* read metadata verify failed then will queue error work.
* update_super_work will call start_this_handle may trigger
* BUG_ON.
*/
ext4_unregister_sysfs(sb);
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs unmount"))
ext4_msg(sb, KERN_INFO, "unmounting filesystem %pU.",
&sb->s_uuid);
ext4_unregister_li_request(sb);
ext4_quotas_off(sb, EXT4_MAXQUOTAS);
flush_work(&sbi->s_sb_upd_work);
destroy_workqueue(sbi->rsv_conversion_wq);
ext4_release_orphan_info(sb);
if (sbi->s_journal) {
aborted = is_journal_aborted(sbi->s_journal);
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if ((err < 0) && !aborted) {
ext4_abort(sb, -err, "Couldn't clean up the journal");
}
}
ext4_es_unregister_shrinker(sbi);
timer_shutdown_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
if (!sb_rdonly(sb) && !aborted) {
ext4_clear_feature_journal_needs_recovery(sb);
ext4_clear_feature_orphan_present(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!sb_rdonly(sb))
ext4_commit_super(sb);
ext4_group_desc_free(sbi);
ext4_flex_groups_free(sbi);
ext4_percpu_param_destroy(sbi);
#ifdef CONFIG_QUOTA
for (int i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(get_qf_name(sb, sbi, i));
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->s_journal_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->s_journal_bdev);
invalidate_bdev(sbi->s_journal_bdev);
}
ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
sbi->s_ea_inode_cache = NULL;
ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
sbi->s_ea_block_cache = NULL;
ext4_stop_mmpd(sbi);
brelse(sbi->s_sbh);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
fs_put_dax(sbi->s_daxdev, NULL);
fscrypt_free_dummy_policy(&sbi->s_dummy_enc_policy);
#if IS_ENABLED(CONFIG_UNICODE)
utf8_unload(sb->s_encoding);
#endif
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = alloc_inode_sb(sb, ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
inode_set_iversion(&ei->vfs_inode, 1);
ei->i_flags = 0;
spin_lock_init(&ei->i_raw_lock);
ei->i_prealloc_node = RB_ROOT;
atomic_set(&ei->i_prealloc_active, 0);
rwlock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_list);
ei->i_es_all_nr = 0;
ei->i_es_shk_nr = 0;
ei->i_es_shrink_lblk = 0;
ei->i_reserved_data_blocks = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
ext4_init_pending_tree(&ei->i_pending_tree);
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
ext4_fc_init_inode(&ei->vfs_inode);
mutex_init(&ei->i_fc_lock);
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
if (!drop)
drop = fscrypt_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_free_in_core_inode(struct inode *inode)
{
fscrypt_free_inode(inode);
if (!list_empty(&(EXT4_I(inode)->i_fc_list))) {
pr_warn("%s: inode %ld still in fc list",
__func__, inode->i_ino);
}
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
if (EXT4_I(inode)->i_reserved_data_blocks)
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): i_reserved_data_blocks (%u) not cleared!",
inode->i_ino, EXT4_I(inode),
EXT4_I(inode)->i_reserved_data_blocks);
}
static void ext4_shutdown(struct super_block *sb)
{
ext4_force_shutdown(sb, EXT4_GOING_FLAGS_NOLOGFLUSH);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
inode_init_once(&ei->vfs_inode);
ext4_fc_init_inode(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create_usercopy("ext4_inode_cache",
sizeof(struct ext4_inode_info), 0,
(SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
SLAB_ACCOUNT),
offsetof(struct ext4_inode_info, i_data),
sizeof_field(struct ext4_inode_info, i_data),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
ext4_fc_del(inode);
invalidate_inode_buffers(inode);
clear_inode(inode);
ext4_discard_preallocations(inode, 0);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
dquot_drop(inode);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
fscrypt_put_encryption_info(inode);
fsverity_cleanup_inode(inode);
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
/*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget(sb, ino, EXT4_IGET_HANDLE);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static int ext4_nfs_commit_metadata(struct inode *inode)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL
};
trace_ext4_nfs_commit_metadata(inode);
return ext4_write_inode(inode, &wbc);
}
#ifdef CONFIG_QUOTA
static const char * const quotatypes[] = INITQFNAMES;
#define QTYPE2NAME(t) (quotatypes[t])
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
const struct path *path);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static struct dquot **ext4_get_dquots(struct inode *inode)
{
return EXT4_I(inode)->i_dquot;
}
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
.get_projid = ext4_get_projid,
.get_inode_usage = ext4_get_inode_usage,
.get_next_id = dquot_get_next_id,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_state = dquot_get_state,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk,
.get_nextdqblk = dquot_get_next_dqblk,
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.free_inode = ext4_free_in_core_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.show_options = ext4_show_options,
.shutdown = ext4_shutdown,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
.get_dquots = ext4_get_dquots,
#endif
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
.commit_metadata = ext4_nfs_commit_metadata,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_acl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
Opt_inlinecrypt,
Opt_usrjquota, Opt_grpjquota, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_prjquota,
Opt_dax, Opt_dax_always, Opt_dax_inode, Opt_dax_never,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_warn_on_error,
Opt_nowarn_on_error, Opt_mblk_io_submit, Opt_debug_want_extra_isize,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb, Opt_nojournal_checksum, Opt_nombcache,
Opt_no_prefetch_block_bitmaps, Opt_mb_optimize_scan,
Opt_errors, Opt_data, Opt_data_err, Opt_jqfmt, Opt_dax_type,
#ifdef CONFIG_EXT4_DEBUG
Opt_fc_debug_max_replay, Opt_fc_debug_force
#endif
};
static const struct constant_table ext4_param_errors[] = {
{"continue", EXT4_MOUNT_ERRORS_CONT},
{"panic", EXT4_MOUNT_ERRORS_PANIC},
{"remount-ro", EXT4_MOUNT_ERRORS_RO},
{}
};
static const struct constant_table ext4_param_data[] = {
{"journal", EXT4_MOUNT_JOURNAL_DATA},
{"ordered", EXT4_MOUNT_ORDERED_DATA},
{"writeback", EXT4_MOUNT_WRITEBACK_DATA},
{}
};
static const struct constant_table ext4_param_data_err[] = {
{"abort", Opt_data_err_abort},
{"ignore", Opt_data_err_ignore},
{}
};
static const struct constant_table ext4_param_jqfmt[] = {
{"vfsold", QFMT_VFS_OLD},
{"vfsv0", QFMT_VFS_V0},
{"vfsv1", QFMT_VFS_V1},
{}
};
static const struct constant_table ext4_param_dax[] = {
{"always", Opt_dax_always},
{"inode", Opt_dax_inode},
{"never", Opt_dax_never},
{}
};
/* String parameter that allows empty argument */
#define fsparam_string_empty(NAME, OPT) \
__fsparam(fs_param_is_string, NAME, OPT, fs_param_can_be_empty, NULL)
/*
* Mount option specification
* We don't use fsparam_flag_no because of the way we set the
* options and the way we show them in _ext4_show_options(). To
* keep the changes to a minimum, let's keep the negative options
* separate for now.
*/
static const struct fs_parameter_spec ext4_param_specs[] = {
fsparam_flag ("bsddf", Opt_bsd_df),
fsparam_flag ("minixdf", Opt_minix_df),
fsparam_flag ("grpid", Opt_grpid),
fsparam_flag ("bsdgroups", Opt_grpid),
fsparam_flag ("nogrpid", Opt_nogrpid),
fsparam_flag ("sysvgroups", Opt_nogrpid),
fsparam_u32 ("resgid", Opt_resgid),
fsparam_u32 ("resuid", Opt_resuid),
fsparam_u32 ("sb", Opt_sb),
fsparam_enum ("errors", Opt_errors, ext4_param_errors),
fsparam_flag ("nouid32", Opt_nouid32),
fsparam_flag ("debug", Opt_debug),
fsparam_flag ("oldalloc", Opt_removed),
fsparam_flag ("orlov", Opt_removed),
fsparam_flag ("user_xattr", Opt_user_xattr),
fsparam_flag ("acl", Opt_acl),
fsparam_flag ("norecovery", Opt_noload),
fsparam_flag ("noload", Opt_noload),
fsparam_flag ("bh", Opt_removed),
fsparam_flag ("nobh", Opt_removed),
fsparam_u32 ("commit", Opt_commit),
fsparam_u32 ("min_batch_time", Opt_min_batch_time),
fsparam_u32 ("max_batch_time", Opt_max_batch_time),
fsparam_u32 ("journal_dev", Opt_journal_dev),
fsparam_bdev ("journal_path", Opt_journal_path),
fsparam_flag ("journal_checksum", Opt_journal_checksum),
fsparam_flag ("nojournal_checksum", Opt_nojournal_checksum),
fsparam_flag ("journal_async_commit",Opt_journal_async_commit),
fsparam_flag ("abort", Opt_abort),
fsparam_enum ("data", Opt_data, ext4_param_data),
fsparam_enum ("data_err", Opt_data_err,
ext4_param_data_err),
fsparam_string_empty
("usrjquota", Opt_usrjquota),
fsparam_string_empty
("grpjquota", Opt_grpjquota),
fsparam_enum ("jqfmt", Opt_jqfmt, ext4_param_jqfmt),
fsparam_flag ("grpquota", Opt_grpquota),
fsparam_flag ("quota", Opt_quota),
fsparam_flag ("noquota", Opt_noquota),
fsparam_flag ("usrquota", Opt_usrquota),
fsparam_flag ("prjquota", Opt_prjquota),
fsparam_flag ("barrier", Opt_barrier),
fsparam_u32 ("barrier", Opt_barrier),
fsparam_flag ("nobarrier", Opt_nobarrier),
fsparam_flag ("i_version", Opt_removed),
fsparam_flag ("dax", Opt_dax),
fsparam_enum ("dax", Opt_dax_type, ext4_param_dax),
fsparam_u32 ("stripe", Opt_stripe),
fsparam_flag ("delalloc", Opt_delalloc),
fsparam_flag ("nodelalloc", Opt_nodelalloc),
fsparam_flag ("warn_on_error", Opt_warn_on_error),
fsparam_flag ("nowarn_on_error", Opt_nowarn_on_error),
fsparam_u32 ("debug_want_extra_isize",
Opt_debug_want_extra_isize),
fsparam_flag ("mblk_io_submit", Opt_removed),
fsparam_flag ("nomblk_io_submit", Opt_removed),
fsparam_flag ("block_validity", Opt_block_validity),
fsparam_flag ("noblock_validity", Opt_noblock_validity),
fsparam_u32 ("inode_readahead_blks",
Opt_inode_readahead_blks),
fsparam_u32 ("journal_ioprio", Opt_journal_ioprio),
fsparam_u32 ("auto_da_alloc", Opt_auto_da_alloc),
fsparam_flag ("auto_da_alloc", Opt_auto_da_alloc),
fsparam_flag ("noauto_da_alloc", Opt_noauto_da_alloc),
fsparam_flag ("dioread_nolock", Opt_dioread_nolock),
fsparam_flag ("nodioread_nolock", Opt_dioread_lock),
fsparam_flag ("dioread_lock", Opt_dioread_lock),
fsparam_flag ("discard", Opt_discard),
fsparam_flag ("nodiscard", Opt_nodiscard),
fsparam_u32 ("init_itable", Opt_init_itable),
fsparam_flag ("init_itable", Opt_init_itable),
fsparam_flag ("noinit_itable", Opt_noinit_itable),
#ifdef CONFIG_EXT4_DEBUG
fsparam_flag ("fc_debug_force", Opt_fc_debug_force),
fsparam_u32 ("fc_debug_max_replay", Opt_fc_debug_max_replay),
#endif
fsparam_u32 ("max_dir_size_kb", Opt_max_dir_size_kb),
fsparam_flag ("test_dummy_encryption",
Opt_test_dummy_encryption),
fsparam_string ("test_dummy_encryption",
Opt_test_dummy_encryption),
fsparam_flag ("inlinecrypt", Opt_inlinecrypt),
fsparam_flag ("nombcache", Opt_nombcache),
fsparam_flag ("no_mbcache", Opt_nombcache), /* for backward compatibility */
fsparam_flag ("prefetch_block_bitmaps",
Opt_removed),
fsparam_flag ("no_prefetch_block_bitmaps",
Opt_no_prefetch_block_bitmaps),
fsparam_s32 ("mb_optimize_scan", Opt_mb_optimize_scan),
fsparam_string ("check", Opt_removed), /* mount option from ext2/3 */
fsparam_flag ("nocheck", Opt_removed), /* mount option from ext2/3 */
fsparam_flag ("reservation", Opt_removed), /* mount option from ext2/3 */
fsparam_flag ("noreservation", Opt_removed), /* mount option from ext2/3 */
fsparam_u32 ("journal", Opt_removed), /* mount option from ext2/3 */
{}
};
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0010
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_NO_EXT2 0x0020
#define MOPT_NO_EXT3 0x0040
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
#define MOPT_SKIP 0x0080
#define MOPT_2 0x0100
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_warn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_SET},
{Opt_nowarn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_CLEAR},
{Opt_commit, 0, MOPT_NO_EXT2},
{Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_data_err, EXT4_MOUNT_DATA_ERR_ABORT, MOPT_NO_EXT2},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_dax_type, 0, MOPT_EXT4_ONLY},
{Opt_journal_dev, 0, MOPT_NO_EXT2},
{Opt_journal_path, 0, MOPT_NO_EXT2},
{Opt_journal_ioprio, 0, MOPT_NO_EXT2},
{Opt_data, 0, MOPT_NO_EXT2},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_jqfmt, 0, MOPT_QFMT},
{Opt_nombcache, EXT4_MOUNT_NO_MBCACHE, MOPT_SET},
{Opt_no_prefetch_block_bitmaps, EXT4_MOUNT_NO_PREFETCH_BLOCK_BITMAPS,
MOPT_SET},
#ifdef CONFIG_EXT4_DEBUG
{Opt_fc_debug_force, EXT4_MOUNT2_JOURNAL_FAST_COMMIT,
MOPT_SET | MOPT_2 | MOPT_EXT4_ONLY},
#endif
{Opt_abort, EXT4_MOUNT2_ABORT, MOPT_SET | MOPT_2},
{Opt_err, 0, 0}
};
#if IS_ENABLED(CONFIG_UNICODE)
static const struct ext4_sb_encodings {
__u16 magic;
char *name;
unsigned int version;
} ext4_sb_encoding_map[] = {
{EXT4_ENC_UTF8_12_1, "utf8", UNICODE_AGE(12, 1, 0)},
};
static const struct ext4_sb_encodings *
ext4_sb_read_encoding(const struct ext4_super_block *es)
{
__u16 magic = le16_to_cpu(es->s_encoding);
int i;
for (i = 0; i < ARRAY_SIZE(ext4_sb_encoding_map); i++)
if (magic == ext4_sb_encoding_map[i].magic)
return &ext4_sb_encoding_map[i];
return NULL;
}
#endif
#define EXT4_SPEC_JQUOTA (1 << 0)
#define EXT4_SPEC_JQFMT (1 << 1)
#define EXT4_SPEC_DATAJ (1 << 2)
#define EXT4_SPEC_SB_BLOCK (1 << 3)
#define EXT4_SPEC_JOURNAL_DEV (1 << 4)
#define EXT4_SPEC_JOURNAL_IOPRIO (1 << 5)
#define EXT4_SPEC_s_want_extra_isize (1 << 7)
#define EXT4_SPEC_s_max_batch_time (1 << 8)
#define EXT4_SPEC_s_min_batch_time (1 << 9)
#define EXT4_SPEC_s_inode_readahead_blks (1 << 10)
#define EXT4_SPEC_s_li_wait_mult (1 << 11)
#define EXT4_SPEC_s_max_dir_size_kb (1 << 12)
#define EXT4_SPEC_s_stripe (1 << 13)
#define EXT4_SPEC_s_resuid (1 << 14)
#define EXT4_SPEC_s_resgid (1 << 15)
#define EXT4_SPEC_s_commit_interval (1 << 16)
#define EXT4_SPEC_s_fc_debug_max_replay (1 << 17)
#define EXT4_SPEC_s_sb_block (1 << 18)
#define EXT4_SPEC_mb_optimize_scan (1 << 19)
struct ext4_fs_context {
char *s_qf_names[EXT4_MAXQUOTAS];
struct fscrypt_dummy_policy dummy_enc_policy;
int s_jquota_fmt; /* Format of quota to use */
#ifdef CONFIG_EXT4_DEBUG
int s_fc_debug_max_replay;
#endif
unsigned short qname_spec;
unsigned long vals_s_flags; /* Bits to set in s_flags */
unsigned long mask_s_flags; /* Bits changed in s_flags */
unsigned long journal_devnum;
unsigned long s_commit_interval;
unsigned long s_stripe;
unsigned int s_inode_readahead_blks;
unsigned int s_want_extra_isize;
unsigned int s_li_wait_mult;
unsigned int s_max_dir_size_kb;
unsigned int journal_ioprio;
unsigned int vals_s_mount_opt;
unsigned int mask_s_mount_opt;
unsigned int vals_s_mount_opt2;
unsigned int mask_s_mount_opt2;
unsigned int opt_flags; /* MOPT flags */
unsigned int spec;
u32 s_max_batch_time;
u32 s_min_batch_time;
kuid_t s_resuid;
kgid_t s_resgid;
ext4_fsblk_t s_sb_block;
};
static void ext4_fc_free(struct fs_context *fc)
{
struct ext4_fs_context *ctx = fc->fs_private;
int i;
if (!ctx)
return;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(ctx->s_qf_names[i]);
fscrypt_free_dummy_policy(&ctx->dummy_enc_policy);
kfree(ctx);
}
int ext4_init_fs_context(struct fs_context *fc)
{
struct ext4_fs_context *ctx;
ctx = kzalloc(sizeof(struct ext4_fs_context), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
fc->fs_private = ctx;
fc->ops = &ext4_context_ops;
return 0;
}
#ifdef CONFIG_QUOTA
/*
* Note the name of the specified quota file.
*/
static int note_qf_name(struct fs_context *fc, int qtype,
struct fs_parameter *param)
{
struct ext4_fs_context *ctx = fc->fs_private;
char *qname;
if (param->size < 1) {
ext4_msg(NULL, KERN_ERR, "Missing quota name");
return -EINVAL;
}
if (strchr(param->string, '/')) {
ext4_msg(NULL, KERN_ERR,
"quotafile must be on filesystem root");
return -EINVAL;
}
if (ctx->s_qf_names[qtype]) {
if (strcmp(ctx->s_qf_names[qtype], param->string) != 0) {
ext4_msg(NULL, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
return -EINVAL;
}
return 0;
}
qname = kmemdup_nul(param->string, param->size, GFP_KERNEL);
if (!qname) {
ext4_msg(NULL, KERN_ERR,
"Not enough memory for storing quotafile name");
return -ENOMEM;
}
ctx->s_qf_names[qtype] = qname;
ctx->qname_spec |= 1 << qtype;
ctx->spec |= EXT4_SPEC_JQUOTA;
return 0;
}
/*
* Clear the name of the specified quota file.
*/
static int unnote_qf_name(struct fs_context *fc, int qtype)
{
struct ext4_fs_context *ctx = fc->fs_private;
if (ctx->s_qf_names[qtype])
kfree(ctx->s_qf_names[qtype]);
ctx->s_qf_names[qtype] = NULL;
ctx->qname_spec |= 1 << qtype;
ctx->spec |= EXT4_SPEC_JQUOTA;
return 0;
}
#endif
static int ext4_parse_test_dummy_encryption(const struct fs_parameter *param,
struct ext4_fs_context *ctx)
{
int err;
if (!IS_ENABLED(CONFIG_FS_ENCRYPTION)) {
ext4_msg(NULL, KERN_WARNING,
"test_dummy_encryption option not supported");
return -EINVAL;
}
err = fscrypt_parse_test_dummy_encryption(param,
&ctx->dummy_enc_policy);
if (err == -EINVAL) {
ext4_msg(NULL, KERN_WARNING,
"Value of option \"%s\" is unrecognized", param->key);
} else if (err == -EEXIST) {
ext4_msg(NULL, KERN_WARNING,
"Conflicting test_dummy_encryption options");
return -EINVAL;
}
return err;
}
#define EXT4_SET_CTX(name) \
static inline void ctx_set_##name(struct ext4_fs_context *ctx, \
unsigned long flag) \
{ \
ctx->mask_s_##name |= flag; \
ctx->vals_s_##name |= flag; \
}
#define EXT4_CLEAR_CTX(name) \
static inline void ctx_clear_##name(struct ext4_fs_context *ctx, \
unsigned long flag) \
{ \
ctx->mask_s_##name |= flag; \
ctx->vals_s_##name &= ~flag; \
}
#define EXT4_TEST_CTX(name) \
static inline unsigned long \
ctx_test_##name(struct ext4_fs_context *ctx, unsigned long flag) \
{ \
return (ctx->vals_s_##name & flag); \
}
EXT4_SET_CTX(flags); /* set only */
EXT4_SET_CTX(mount_opt);
EXT4_CLEAR_CTX(mount_opt);
EXT4_TEST_CTX(mount_opt);
EXT4_SET_CTX(mount_opt2);
EXT4_CLEAR_CTX(mount_opt2);
EXT4_TEST_CTX(mount_opt2);
static int ext4_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
struct ext4_fs_context *ctx = fc->fs_private;
struct fs_parse_result result;
const struct mount_opts *m;
int is_remount;
kuid_t uid;
kgid_t gid;
int token;
token = fs_parse(fc, ext4_param_specs, param, &result);
if (token < 0)
return token;
is_remount = fc->purpose == FS_CONTEXT_FOR_RECONFIGURE;
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
ctx->opt_flags |= m->flags;
if (m->flags & MOPT_EXPLICIT) {
if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
ctx_set_mount_opt2(ctx, EXT4_MOUNT2_EXPLICIT_DELALLOC);
} else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
ctx_set_mount_opt2(ctx,
EXT4_MOUNT2_EXPLICIT_JOURNAL_CHECKSUM);
} else
return -EINVAL;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(NULL, KERN_ERR, "%s option not supported",
param->key);
return 0;
}
switch (token) {
#ifdef CONFIG_QUOTA
case Opt_usrjquota:
if (!*param->string)
return unnote_qf_name(fc, USRQUOTA);
else
return note_qf_name(fc, USRQUOTA, param);
case Opt_grpjquota:
if (!*param->string)
return unnote_qf_name(fc, GRPQUOTA);
else
return note_qf_name(fc, GRPQUOTA, param);
#endif
case Opt_sb:
if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
ext4_msg(NULL, KERN_WARNING,
"Ignoring %s option on remount", param->key);
} else {
ctx->s_sb_block = result.uint_32;
ctx->spec |= EXT4_SPEC_s_sb_block;
}
return 0;
case Opt_removed:
ext4_msg(NULL, KERN_WARNING, "Ignoring removed %s option",
param->key);
return 0;
case Opt_inlinecrypt:
#ifdef CONFIG_FS_ENCRYPTION_INLINE_CRYPT
ctx_set_flags(ctx, SB_INLINECRYPT);
#else
ext4_msg(NULL, KERN_ERR, "inline encryption not supported");
#endif
return 0;
case Opt_errors:
ctx_clear_mount_opt(ctx, EXT4_MOUNT_ERRORS_MASK);
ctx_set_mount_opt(ctx, result.uint_32);
return 0;
#ifdef CONFIG_QUOTA
case Opt_jqfmt:
ctx->s_jquota_fmt = result.uint_32;
ctx->spec |= EXT4_SPEC_JQFMT;
return 0;
#endif
case Opt_data:
ctx_clear_mount_opt(ctx, EXT4_MOUNT_DATA_FLAGS);
ctx_set_mount_opt(ctx, result.uint_32);
ctx->spec |= EXT4_SPEC_DATAJ;
return 0;
case Opt_commit:
if (result.uint_32 == 0)
result.uint_32 = JBD2_DEFAULT_MAX_COMMIT_AGE;
else if (result.uint_32 > INT_MAX / HZ) {
ext4_msg(NULL, KERN_ERR,
"Invalid commit interval %d, "
"must be smaller than %d",
result.uint_32, INT_MAX / HZ);
return -EINVAL;
}
ctx->s_commit_interval = HZ * result.uint_32;
ctx->spec |= EXT4_SPEC_s_commit_interval;
return 0;
case Opt_debug_want_extra_isize:
if ((result.uint_32 & 1) || (result.uint_32 < 4)) {
ext4_msg(NULL, KERN_ERR,
"Invalid want_extra_isize %d", result.uint_32);
return -EINVAL;
}
ctx->s_want_extra_isize = result.uint_32;
ctx->spec |= EXT4_SPEC_s_want_extra_isize;
return 0;
case Opt_max_batch_time:
ctx->s_max_batch_time = result.uint_32;
ctx->spec |= EXT4_SPEC_s_max_batch_time;
return 0;
case Opt_min_batch_time:
ctx->s_min_batch_time = result.uint_32;
ctx->spec |= EXT4_SPEC_s_min_batch_time;
return 0;
case Opt_inode_readahead_blks:
if (result.uint_32 &&
(result.uint_32 > (1 << 30) ||
!is_power_of_2(result.uint_32))) {
ext4_msg(NULL, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -EINVAL;
}
ctx->s_inode_readahead_blks = result.uint_32;
ctx->spec |= EXT4_SPEC_s_inode_readahead_blks;
return 0;
case Opt_init_itable:
ctx_set_mount_opt(ctx, EXT4_MOUNT_INIT_INODE_TABLE);
ctx->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (param->type == fs_value_is_string)
ctx->s_li_wait_mult = result.uint_32;
ctx->spec |= EXT4_SPEC_s_li_wait_mult;
return 0;
case Opt_max_dir_size_kb:
ctx->s_max_dir_size_kb = result.uint_32;
ctx->spec |= EXT4_SPEC_s_max_dir_size_kb;
return 0;
#ifdef CONFIG_EXT4_DEBUG
case Opt_fc_debug_max_replay:
ctx->s_fc_debug_max_replay = result.uint_32;
ctx->spec |= EXT4_SPEC_s_fc_debug_max_replay;
return 0;
#endif
case Opt_stripe:
ctx->s_stripe = result.uint_32;
ctx->spec |= EXT4_SPEC_s_stripe;
return 0;
case Opt_resuid:
uid = make_kuid(current_user_ns(), result.uint_32);
if (!uid_valid(uid)) {
ext4_msg(NULL, KERN_ERR, "Invalid uid value %d",
result.uint_32);
return -EINVAL;
}
ctx->s_resuid = uid;
ctx->spec |= EXT4_SPEC_s_resuid;
return 0;
case Opt_resgid:
gid = make_kgid(current_user_ns(), result.uint_32);
if (!gid_valid(gid)) {
ext4_msg(NULL, KERN_ERR, "Invalid gid value %d",
result.uint_32);
return -EINVAL;
}
ctx->s_resgid = gid;
ctx->spec |= EXT4_SPEC_s_resgid;
return 0;
case Opt_journal_dev:
if (is_remount) {
ext4_msg(NULL, KERN_ERR,
"Cannot specify journal on remount");
return -EINVAL;
}
ctx->journal_devnum = result.uint_32;
ctx->spec |= EXT4_SPEC_JOURNAL_DEV;
return 0;
case Opt_journal_path:
{
struct inode *journal_inode;
struct path path;
int error;
if (is_remount) {
ext4_msg(NULL, KERN_ERR,
"Cannot specify journal on remount");
return -EINVAL;
}
error = fs_lookup_param(fc, param, 1, LOOKUP_FOLLOW, &path);
if (error) {
ext4_msg(NULL, KERN_ERR, "error: could not find "
"journal device path");
return -EINVAL;
}
journal_inode = d_inode(path.dentry);
ctx->journal_devnum = new_encode_dev(journal_inode->i_rdev);
ctx->spec |= EXT4_SPEC_JOURNAL_DEV;
path_put(&path);
return 0;
}
case Opt_journal_ioprio:
if (result.uint_32 > 7) {
ext4_msg(NULL, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -EINVAL;
}
ctx->journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, result.uint_32);
ctx->spec |= EXT4_SPEC_JOURNAL_IOPRIO;
return 0;
case Opt_test_dummy_encryption:
return ext4_parse_test_dummy_encryption(param, ctx);
case Opt_dax:
case Opt_dax_type:
#ifdef CONFIG_FS_DAX
{
int type = (token == Opt_dax) ?
Opt_dax : result.uint_32;
switch (type) {
case Opt_dax:
case Opt_dax_always:
ctx_set_mount_opt(ctx, EXT4_MOUNT_DAX_ALWAYS);
ctx_clear_mount_opt2(ctx, EXT4_MOUNT2_DAX_NEVER);
break;
case Opt_dax_never:
ctx_set_mount_opt2(ctx, EXT4_MOUNT2_DAX_NEVER);
ctx_clear_mount_opt(ctx, EXT4_MOUNT_DAX_ALWAYS);
break;
case Opt_dax_inode:
ctx_clear_mount_opt(ctx, EXT4_MOUNT_DAX_ALWAYS);
ctx_clear_mount_opt2(ctx, EXT4_MOUNT2_DAX_NEVER);
/* Strictly for printing options */
ctx_set_mount_opt2(ctx, EXT4_MOUNT2_DAX_INODE);
break;
}
return 0;
}
#else
ext4_msg(NULL, KERN_INFO, "dax option not supported");
return -EINVAL;
#endif
case Opt_data_err:
if (result.uint_32 == Opt_data_err_abort)
ctx_set_mount_opt(ctx, m->mount_opt);
else if (result.uint_32 == Opt_data_err_ignore)
ctx_clear_mount_opt(ctx, m->mount_opt);
return 0;
case Opt_mb_optimize_scan:
if (result.int_32 == 1) {
ctx_set_mount_opt2(ctx, EXT4_MOUNT2_MB_OPTIMIZE_SCAN);
ctx->spec |= EXT4_SPEC_mb_optimize_scan;
} else if (result.int_32 == 0) {
ctx_clear_mount_opt2(ctx, EXT4_MOUNT2_MB_OPTIMIZE_SCAN);
ctx->spec |= EXT4_SPEC_mb_optimize_scan;
} else {
ext4_msg(NULL, KERN_WARNING,
"mb_optimize_scan should be set to 0 or 1.");
return -EINVAL;
}
return 0;
}
/*
* At this point we should only be getting options requiring MOPT_SET,
* or MOPT_CLEAR. Anything else is a bug
*/
if (m->token == Opt_err) {
ext4_msg(NULL, KERN_WARNING, "buggy handling of option %s",
param->key);
WARN_ON(1);
return -EINVAL;
}
else {
unsigned int set = 0;
if ((param->type == fs_value_is_flag) ||
result.uint_32 > 0)
set = 1;
if (m->flags & MOPT_CLEAR)
set = !set;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(NULL, KERN_WARNING,
"buggy handling of option %s",
param->key);
WARN_ON(1);
return -EINVAL;
}
if (m->flags & MOPT_2) {
if (set != 0)
ctx_set_mount_opt2(ctx, m->mount_opt);
else
ctx_clear_mount_opt2(ctx, m->mount_opt);
} else {
if (set != 0)
ctx_set_mount_opt(ctx, m->mount_opt);
else
ctx_clear_mount_opt(ctx, m->mount_opt);
}
}
return 0;
}
static int parse_options(struct fs_context *fc, char *options)
{
struct fs_parameter param;
int ret;
char *key;
if (!options)
return 0;
while ((key = strsep(&options, ",")) != NULL) {
if (*key) {
size_t v_len = 0;
char *value = strchr(key, '=');
param.type = fs_value_is_flag;
param.string = NULL;
if (value) {
if (value == key)
continue;
*value++ = 0;
v_len = strlen(value);
param.string = kmemdup_nul(value, v_len,
GFP_KERNEL);
if (!param.string)
return -ENOMEM;
param.type = fs_value_is_string;
}
param.key = key;
param.size = v_len;
ret = ext4_parse_param(fc, ¶m);
if (param.string)
kfree(param.string);
if (ret < 0)
return ret;
}
}
ret = ext4_validate_options(fc);
if (ret < 0)
return ret;
return 0;
}
static int parse_apply_sb_mount_options(struct super_block *sb,
struct ext4_fs_context *m_ctx)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *s_mount_opts = NULL;
struct ext4_fs_context *s_ctx = NULL;
struct fs_context *fc = NULL;
int ret = -ENOMEM;
if (!sbi->s_es->s_mount_opts[0])
return 0;
s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
sizeof(sbi->s_es->s_mount_opts),
GFP_KERNEL);
if (!s_mount_opts)
return ret;
fc = kzalloc(sizeof(struct fs_context), GFP_KERNEL);
if (!fc)
goto out_free;
s_ctx = kzalloc(sizeof(struct ext4_fs_context), GFP_KERNEL);
if (!s_ctx)
goto out_free;
fc->fs_private = s_ctx;
fc->s_fs_info = sbi;
ret = parse_options(fc, s_mount_opts);
if (ret < 0)
goto parse_failed;
ret = ext4_check_opt_consistency(fc, sb);
if (ret < 0) {
parse_failed:
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
s_mount_opts);
ret = 0;
goto out_free;
}
if (s_ctx->spec & EXT4_SPEC_JOURNAL_DEV)
m_ctx->journal_devnum = s_ctx->journal_devnum;
if (s_ctx->spec & EXT4_SPEC_JOURNAL_IOPRIO)
m_ctx->journal_ioprio = s_ctx->journal_ioprio;
ext4_apply_options(fc, sb);
ret = 0;
out_free:
if (fc) {
ext4_fc_free(fc);
kfree(fc);
}
kfree(s_mount_opts);
return ret;
}
static void ext4_apply_quota_options(struct fs_context *fc,
struct super_block *sb)
{
#ifdef CONFIG_QUOTA
bool quota_feature = ext4_has_feature_quota(sb);
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int i;
if (quota_feature)
return;
if (ctx->spec & EXT4_SPEC_JQUOTA) {
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (!(ctx->qname_spec & (1 << i)))
continue;
qname = ctx->s_qf_names[i]; /* May be NULL */
if (qname)
set_opt(sb, QUOTA);
ctx->s_qf_names[i] = NULL;
qname = rcu_replace_pointer(sbi->s_qf_names[i], qname,
lockdep_is_held(&sb->s_umount));
if (qname)
kfree_rcu_mightsleep(qname);
}
}
if (ctx->spec & EXT4_SPEC_JQFMT)
sbi->s_jquota_fmt = ctx->s_jquota_fmt;
#endif
}
/*
* Check quota settings consistency.
*/
static int ext4_check_quota_consistency(struct fs_context *fc,
struct super_block *sb)
{
#ifdef CONFIG_QUOTA
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
bool quota_feature = ext4_has_feature_quota(sb);
bool quota_loaded = sb_any_quota_loaded(sb);
bool usr_qf_name, grp_qf_name, usrquota, grpquota;
int quota_flags, i;
/*
* We do the test below only for project quotas. 'usrquota' and
* 'grpquota' mount options are allowed even without quota feature
* to support legacy quotas in quota files.
*/
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_PRJQUOTA) &&
!ext4_has_feature_project(sb)) {
ext4_msg(NULL, KERN_ERR, "Project quota feature not enabled. "
"Cannot enable project quota enforcement.");
return -EINVAL;
}
quota_flags = EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA;
if (quota_loaded &&
ctx->mask_s_mount_opt & quota_flags &&
!ctx_test_mount_opt(ctx, quota_flags))
goto err_quota_change;
if (ctx->spec & EXT4_SPEC_JQUOTA) {
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (!(ctx->qname_spec & (1 << i)))
continue;
if (quota_loaded &&
!!sbi->s_qf_names[i] != !!ctx->s_qf_names[i])
goto err_jquota_change;
if (sbi->s_qf_names[i] && ctx->s_qf_names[i] &&
strcmp(get_qf_name(sb, sbi, i),
ctx->s_qf_names[i]) != 0)
goto err_jquota_specified;
}
if (quota_feature) {
ext4_msg(NULL, KERN_INFO,
"Journaled quota options ignored when "
"QUOTA feature is enabled");
return 0;
}
}
if (ctx->spec & EXT4_SPEC_JQFMT) {
if (sbi->s_jquota_fmt != ctx->s_jquota_fmt && quota_loaded)
goto err_jquota_change;
if (quota_feature) {
ext4_msg(NULL, KERN_INFO, "Quota format mount options "
"ignored when QUOTA feature is enabled");
return 0;
}
}
/* Make sure we don't mix old and new quota format */
usr_qf_name = (get_qf_name(sb, sbi, USRQUOTA) ||
ctx->s_qf_names[USRQUOTA]);
grp_qf_name = (get_qf_name(sb, sbi, GRPQUOTA) ||
ctx->s_qf_names[GRPQUOTA]);
usrquota = (ctx_test_mount_opt(ctx, EXT4_MOUNT_USRQUOTA) ||
test_opt(sb, USRQUOTA));
grpquota = (ctx_test_mount_opt(ctx, EXT4_MOUNT_GRPQUOTA) ||
test_opt(sb, GRPQUOTA));
if (usr_qf_name) {
ctx_clear_mount_opt(ctx, EXT4_MOUNT_USRQUOTA);
usrquota = false;
}
if (grp_qf_name) {
ctx_clear_mount_opt(ctx, EXT4_MOUNT_GRPQUOTA);
grpquota = false;
}
if (usr_qf_name || grp_qf_name) {
if (usrquota || grpquota) {
ext4_msg(NULL, KERN_ERR, "old and new quota "
"format mixing");
return -EINVAL;
}
if (!(ctx->spec & EXT4_SPEC_JQFMT || sbi->s_jquota_fmt)) {
ext4_msg(NULL, KERN_ERR, "journaled quota format "
"not specified");
return -EINVAL;
}
}
return 0;
err_quota_change:
ext4_msg(NULL, KERN_ERR,
"Cannot change quota options when quota turned on");
return -EINVAL;
err_jquota_change:
ext4_msg(NULL, KERN_ERR, "Cannot change journaled quota "
"options when quota turned on");
return -EINVAL;
err_jquota_specified:
ext4_msg(NULL, KERN_ERR, "%s quota file already specified",
QTYPE2NAME(i));
return -EINVAL;
#else
return 0;
#endif
}
static int ext4_check_test_dummy_encryption(const struct fs_context *fc,
struct super_block *sb)
{
const struct ext4_fs_context *ctx = fc->fs_private;
const struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!fscrypt_is_dummy_policy_set(&ctx->dummy_enc_policy))
return 0;
if (!ext4_has_feature_encrypt(sb)) {
ext4_msg(NULL, KERN_WARNING,
"test_dummy_encryption requires encrypt feature");
return -EINVAL;
}
/*
* This mount option is just for testing, and it's not worthwhile to
* implement the extra complexity (e.g. RCU protection) that would be
* needed to allow it to be set or changed during remount. We do allow
* it to be specified during remount, but only if there is no change.
*/
if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
if (fscrypt_dummy_policies_equal(&sbi->s_dummy_enc_policy,
&ctx->dummy_enc_policy))
return 0;
ext4_msg(NULL, KERN_WARNING,
"Can't set or change test_dummy_encryption on remount");
return -EINVAL;
}
/* Also make sure s_mount_opts didn't contain a conflicting value. */
if (fscrypt_is_dummy_policy_set(&sbi->s_dummy_enc_policy)) {
if (fscrypt_dummy_policies_equal(&sbi->s_dummy_enc_policy,
&ctx->dummy_enc_policy))
return 0;
ext4_msg(NULL, KERN_WARNING,
"Conflicting test_dummy_encryption options");
return -EINVAL;
}
return 0;
}
static void ext4_apply_test_dummy_encryption(struct ext4_fs_context *ctx,
struct super_block *sb)
{
if (!fscrypt_is_dummy_policy_set(&ctx->dummy_enc_policy) ||
/* if already set, it was already verified to be the same */
fscrypt_is_dummy_policy_set(&EXT4_SB(sb)->s_dummy_enc_policy))
return;
EXT4_SB(sb)->s_dummy_enc_policy = ctx->dummy_enc_policy;
memset(&ctx->dummy_enc_policy, 0, sizeof(ctx->dummy_enc_policy));
ext4_msg(sb, KERN_WARNING, "Test dummy encryption mode enabled");
}
static int ext4_check_opt_consistency(struct fs_context *fc,
struct super_block *sb)
{
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_sb_info *sbi = fc->s_fs_info;
int is_remount = fc->purpose == FS_CONTEXT_FOR_RECONFIGURE;
int err;
if ((ctx->opt_flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(NULL, KERN_ERR,
"Mount option(s) incompatible with ext2");
return -EINVAL;
}
if ((ctx->opt_flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(NULL, KERN_ERR,
"Mount option(s) incompatible with ext3");
return -EINVAL;
}
if (ctx->s_want_extra_isize >
(sbi->s_inode_size - EXT4_GOOD_OLD_INODE_SIZE)) {
ext4_msg(NULL, KERN_ERR,
"Invalid want_extra_isize %d",
ctx->s_want_extra_isize);
return -EINVAL;
}
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_SIZE)
ext4_msg(NULL, KERN_WARNING, "Warning: mounting with an "
"experimental mount option 'dioread_nolock' "
"for blocksize < PAGE_SIZE");
}
err = ext4_check_test_dummy_encryption(fc, sb);
if (err)
return err;
if ((ctx->spec & EXT4_SPEC_DATAJ) && is_remount) {
if (!sbi->s_journal) {
ext4_msg(NULL, KERN_WARNING,
"Remounting file system with no journal "
"so ignoring journalled data option");
ctx_clear_mount_opt(ctx, EXT4_MOUNT_DATA_FLAGS);
} else if (ctx_test_mount_opt(ctx, EXT4_MOUNT_DATA_FLAGS) !=
test_opt(sb, DATA_FLAGS)) {
ext4_msg(NULL, KERN_ERR, "Cannot change data mode "
"on remount");
return -EINVAL;
}
}
if (is_remount) {
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_DAX_ALWAYS) &&
(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) {
ext4_msg(NULL, KERN_ERR, "can't mount with "
"both data=journal and dax");
return -EINVAL;
}
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_DAX_ALWAYS) &&
(!(sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER))) {
fail_dax_change_remount:
ext4_msg(NULL, KERN_ERR, "can't change "
"dax mount option while remounting");
return -EINVAL;
} else if (ctx_test_mount_opt2(ctx, EXT4_MOUNT2_DAX_NEVER) &&
(!(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
(sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS))) {
goto fail_dax_change_remount;
} else if (ctx_test_mount_opt2(ctx, EXT4_MOUNT2_DAX_INODE) &&
((sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
!(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_INODE))) {
goto fail_dax_change_remount;
}
}
return ext4_check_quota_consistency(fc, sb);
}
static void ext4_apply_options(struct fs_context *fc, struct super_block *sb)
{
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_sb_info *sbi = fc->s_fs_info;
sbi->s_mount_opt &= ~ctx->mask_s_mount_opt;
sbi->s_mount_opt |= ctx->vals_s_mount_opt;
sbi->s_mount_opt2 &= ~ctx->mask_s_mount_opt2;
sbi->s_mount_opt2 |= ctx->vals_s_mount_opt2;
sb->s_flags &= ~ctx->mask_s_flags;
sb->s_flags |= ctx->vals_s_flags;
#define APPLY(X) ({ if (ctx->spec & EXT4_SPEC_##X) sbi->X = ctx->X; })
APPLY(s_commit_interval);
APPLY(s_stripe);
APPLY(s_max_batch_time);
APPLY(s_min_batch_time);
APPLY(s_want_extra_isize);
APPLY(s_inode_readahead_blks);
APPLY(s_max_dir_size_kb);
APPLY(s_li_wait_mult);
APPLY(s_resgid);
APPLY(s_resuid);
#ifdef CONFIG_EXT4_DEBUG
APPLY(s_fc_debug_max_replay);
#endif
ext4_apply_quota_options(fc, sb);
ext4_apply_test_dummy_encryption(ctx, sb);
}
static int ext4_validate_options(struct fs_context *fc)
{
#ifdef CONFIG_QUOTA
struct ext4_fs_context *ctx = fc->fs_private;
char *usr_qf_name, *grp_qf_name;
usr_qf_name = ctx->s_qf_names[USRQUOTA];
grp_qf_name = ctx->s_qf_names[GRPQUOTA];
if (usr_qf_name || grp_qf_name) {
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_USRQUOTA) && usr_qf_name)
ctx_clear_mount_opt(ctx, EXT4_MOUNT_USRQUOTA);
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_GRPQUOTA) && grp_qf_name)
ctx_clear_mount_opt(ctx, EXT4_MOUNT_GRPQUOTA);
if (ctx_test_mount_opt(ctx, EXT4_MOUNT_USRQUOTA) ||
ctx_test_mount_opt(ctx, EXT4_MOUNT_GRPQUOTA)) {
ext4_msg(NULL, KERN_ERR, "old and new quota "
"format mixing");
return -EINVAL;
}
}
#endif
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *usr_qf_name, *grp_qf_name;
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
rcu_read_lock();
usr_qf_name = rcu_dereference(sbi->s_qf_names[USRQUOTA]);
grp_qf_name = rcu_dereference(sbi->s_qf_names[GRPQUOTA]);
if (usr_qf_name)
seq_show_option(seq, "usrjquota", usr_qf_name);
if (grp_qf_name)
seq_show_option(seq, "grpjquota", grp_qf_name);
rcu_read_unlock();
#endif
}
static const char *token2str(int token)
{
const struct fs_parameter_spec *spec;
for (spec = ext4_param_specs; spec->name != NULL; spec++)
if (spec->opt == token && !spec->type)
break;
return spec->name;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
int opt_2 = m->flags & MOPT_2;
unsigned int mount_opt, def_mount_opt;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
m->flags & MOPT_SKIP)
continue;
if (opt_2) {
mount_opt = sbi->s_mount_opt2;
def_mount_opt = sbi->s_def_mount_opt2;
} else {
mount_opt = sbi->s_mount_opt;
def_mount_opt = sbi->s_def_mount_opt;
}
/* skip if same as the default */
if (!nodefs && !(m->mount_opt & (mount_opt ^ def_mount_opt)))
continue;
/* select Opt_noFoo vs Opt_Foo */
if ((want_set &&
(mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (mount_opt & m->mount_opt)))
continue;
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (nodefs || EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (test_opt(sb, INIT_INODE_TABLE) && (nodefs ||
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
if (test_opt(sb, DATA_ERR_ABORT))
SEQ_OPTS_PUTS("data_err=abort");
fscrypt_show_test_dummy_encryption(seq, sep, sb);
if (sb->s_flags & SB_INLINECRYPT)
SEQ_OPTS_PUTS("inlinecrypt");
if (test_opt(sb, DAX_ALWAYS)) {
if (IS_EXT2_SB(sb))
SEQ_OPTS_PUTS("dax");
else
SEQ_OPTS_PUTS("dax=always");
} else if (test_opt2(sb, DAX_NEVER)) {
SEQ_OPTS_PUTS("dax=never");
} else if (test_opt2(sb, DAX_INODE)) {
SEQ_OPTS_PUTS("dax=inode");
}
if (sbi->s_groups_count >= MB_DEFAULT_LINEAR_SCAN_THRESHOLD &&
!test_opt2(sb, MB_OPTIMIZE_SCAN)) {
SEQ_OPTS_PUTS("mb_optimize_scan=0");
} else if (sbi->s_groups_count < MB_DEFAULT_LINEAR_SCAN_THRESHOLD &&
test_opt2(sb, MB_OPTIMIZE_SCAN)) {
SEQ_OPTS_PUTS("mb_optimize_scan=1");
}
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
int ext4_seq_options_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, sb_rdonly(sb) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
err = -EROFS;
goto done;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if (sbi->s_mount_state & EXT4_ERROR_FS)
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(ext4_get_tstamp(es, s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= ktime_get_real_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
ext4_update_tstamp(es, s_mtime);
if (sbi->s_journal) {
ext4_set_feature_journal_needs_recovery(sb);
if (ext4_has_feature_orphan_file(sb))
ext4_set_feature_orphan_present(sb);
}
err = ext4_commit_super(sb);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
return err;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups **old_groups, **new_groups;
int size, i, j;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
new_groups = kvzalloc(roundup_pow_of_two(size *
sizeof(*sbi->s_flex_groups)), GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR,
"not enough memory for %d flex group pointers", size);
return -ENOMEM;
}
for (i = sbi->s_flex_groups_allocated; i < size; i++) {
new_groups[i] = kvzalloc(roundup_pow_of_two(
sizeof(struct flex_groups)),
GFP_KERNEL);
if (!new_groups[i]) {
for (j = sbi->s_flex_groups_allocated; j < i; j++)
kvfree(new_groups[j]);
kvfree(new_groups);
ext4_msg(sb, KERN_ERR,
"not enough memory for %d flex groups", size);
return -ENOMEM;
}
}
rcu_read_lock();
old_groups = rcu_dereference(sbi->s_flex_groups);
if (old_groups)
memcpy(new_groups, old_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups *)));
rcu_read_unlock();
rcu_assign_pointer(sbi->s_flex_groups, new_groups);
sbi->s_flex_groups_allocated = size;
if (old_groups)
ext4_kvfree_array_rcu(old_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
struct flex_groups *fg;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
atomic_add(ext4_free_inodes_count(sb, gdp), &fg->free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&fg->free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp), &fg->used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset = offsetof(struct ext4_group_desc, bg_checksum);
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sbi->s_sb)) {
/* Use new metadata_csum algorithm */
__u32 csum32;
__u16 dummy_csum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
sizeof(dummy_csum));
offset += sizeof(dummy_csum);
if (offset < sbi->s_desc_size)
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
sbi->s_desc_size - offset);
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
if (!ext4_has_feature_gdt_csum(sb))
return 0;
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if (ext4_has_feature_64bit(sb) && offset < sbi->s_desc_size)
crc = crc16(crc, (__u8 *)gdp + offset,
sbi->s_desc_size - offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_fsblk_t sb_block,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t last_bg_block = sb_block + ext4_bg_num_gdb(sb, 0);
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (ext4_has_feature_flex_bg(sb))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u overlaps "
"superblock", i);
if (!sb_rdonly(sb))
return 0;
}
if (block_bitmap >= sb_block + 1 &&
block_bitmap <= last_bg_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u overlaps "
"block group descriptors", i);
if (!sb_rdonly(sb))
return 0;
}
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u overlaps "
"superblock", i);
if (!sb_rdonly(sb))
return 0;
}
if (inode_bitmap >= sb_block + 1 &&
inode_bitmap <= last_bg_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u overlaps "
"block group descriptors", i);
if (!sb_rdonly(sb))
return 0;
}
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u overlaps "
"superblock", i);
if (!sb_rdonly(sb))
return 0;
}
if (inode_table >= sb_block + 1 &&
inode_table <= last_bg_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u overlaps "
"block group descriptors", i);
if (!sb_rdonly(sb))
return 0;
}
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sb, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!sb_rdonly(sb)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
return 1;
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
BUILD_BUG_ON(sizeof(blkcnt_t) < sizeof(u64));
if (!has_huge_files) {
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t upper_limit, res = EXT4_NDIR_BLOCKS;
int meta_blocks;
unsigned int ppb = 1 << (bits - 2);
/*
* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files) {
/*
* !has_huge_files or implies that the inode i_block field
* represents total file blocks in 2^32 512-byte sectors ==
* size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* Compute how many blocks we can address by block tree */
res += ppb;
res += ppb * ppb;
res += ((loff_t)ppb) * ppb * ppb;
/* Compute how many metadata blocks are needed */
meta_blocks = 1;
meta_blocks += 1 + ppb;
meta_blocks += 1 + ppb + ppb * ppb;
/* Does block tree limit file size? */
if (res + meta_blocks <= upper_limit)
goto check_lfs;
res = upper_limit;
/* How many metadata blocks are needed for addressing upper_limit? */
upper_limit -= EXT4_NDIR_BLOCKS;
/* indirect blocks */
meta_blocks = 1;
upper_limit -= ppb;
/* double indirect blocks */
if (upper_limit < ppb * ppb) {
meta_blocks += 1 + DIV_ROUND_UP_ULL(upper_limit, ppb);
res -= meta_blocks;
goto check_lfs;
}
meta_blocks += 1 + ppb;
upper_limit -= ppb * ppb;
/* tripple indirect blocks for the rest */
meta_blocks += 1 + DIV_ROUND_UP_ULL(upper_limit, ppb) +
DIV_ROUND_UP_ULL(upper_limit, ppb*ppb);
res -= meta_blocks;
check_lfs:
res <<= bits;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
/*
* If we have a meta_bg fs with 1k blocks, group 0's GDT is at
* block 2, not 1. If s_first_data_block == 0 (bigalloc is enabled
* on modern mke2fs or blksize > 1k on older mke2fs) then we must
* compensate.
*/
if (sb->s_blocksize == 1024 && nr == 0 &&
le32_to_cpu(sbi->s_es->s_first_data_block) == 0)
has_super++;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width && stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride && stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (ext4_has_unknown_ext4_incompat_features(sb)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
#if !IS_ENABLED(CONFIG_UNICODE)
if (ext4_has_feature_casefold(sb)) {
ext4_msg(sb, KERN_ERR,
"Filesystem with casefold feature cannot be "
"mounted without CONFIG_UNICODE");
return 0;
}
#endif
if (readonly)
return 1;
if (ext4_has_feature_readonly(sb)) {
ext4_msg(sb, KERN_INFO, "filesystem is read-only");
sb->s_flags |= SB_RDONLY;
return 1;
}
/* Check that feature set is OK for a read-write mount */
if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#if !IS_ENABLED(CONFIG_QUOTA) || !IS_ENABLED(CONFIG_QFMT_V2)
if (!readonly && (ext4_has_feature_quota(sb) ||
ext4_has_feature_project(sb))) {
ext4_msg(sb, KERN_ERR,
"The kernel was not built with CONFIG_QUOTA and CONFIG_QFMT_V2");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(struct timer_list *t)
{
struct ext4_sb_info *sbi = from_timer(sbi, t, s_err_report);
struct super_block *sb = sbi->s_sb;
struct ext4_super_block *es = sbi->s_es;
if (es->s_error_count)
/* fsck newer than v1.41.13 is needed to clean this condition. */
ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %llu: %.*s:%d",
sb->s_id,
ext4_get_tstamp(es, s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(KERN_CONT ": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(KERN_CONT ": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk(KERN_CONT "\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at time %llu: %.*s:%d",
sb->s_id,
ext4_get_tstamp(es, s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(KERN_CONT ": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(KERN_CONT ": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk(KERN_CONT "\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
struct super_block *sb = elr->lr_super;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
ext4_group_t group = elr->lr_next_group;
unsigned int prefetch_ios = 0;
int ret = 0;
int nr = EXT4_SB(sb)->s_mb_prefetch;
u64 start_time;
if (elr->lr_mode == EXT4_LI_MODE_PREFETCH_BBITMAP) {
elr->lr_next_group = ext4_mb_prefetch(sb, group, nr, &prefetch_ios);
ext4_mb_prefetch_fini(sb, elr->lr_next_group, nr);
trace_ext4_prefetch_bitmaps(sb, group, elr->lr_next_group, nr);
if (group >= elr->lr_next_group) {
ret = 1;
if (elr->lr_first_not_zeroed != ngroups &&
!sb_rdonly(sb) && test_opt(sb, INIT_INODE_TABLE)) {
elr->lr_next_group = elr->lr_first_not_zeroed;
elr->lr_mode = EXT4_LI_MODE_ITABLE;
ret = 0;
}
}
return ret;
}
for (; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
start_time = ktime_get_real_ns();
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
trace_ext4_lazy_itable_init(sb, group);
if (elr->lr_timeout == 0) {
elr->lr_timeout = nsecs_to_jiffies((ktime_get_real_ns() - start_time) *
EXT4_SB(elr->lr_super)->s_li_wait_mult);
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
if (!elr)
return;
list_del(&elr->lr_request);
EXT4_SB(elr->lr_super)->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
set_freezable();
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
int err = 0;
int progress = 0;
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_before(jiffies, elr->lr_next_sched)) {
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
continue;
}
if (down_read_trylock(&elr->lr_super->s_umount)) {
if (sb_start_write_trylock(elr->lr_super)) {
progress = 1;
/*
* We hold sb->s_umount, sb can not
* be removed from the list, it is
* now safe to drop li_list_mtx
*/
mutex_unlock(&eli->li_list_mtx);
err = ext4_run_li_request(elr);
sb_end_write(elr->lr_super);
mutex_lock(&eli->li_list_mtx);
n = pos->next;
}
up_read((&elr->lr_super->s_umount));
}
/* error, remove the lazy_init job */
if (err) {
ext4_remove_li_request(elr);
continue;
}
if (!progress) {
elr->lr_next_sched = jiffies +
get_random_u32_below(EXT4_DEF_LI_MAX_START_DELAY * HZ);
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
if (!ext4_has_group_desc_csum(sb))
return ngroups;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_li_request *elr;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_first_not_zeroed = start;
if (test_opt(sb, NO_PREFETCH_BLOCK_BITMAPS)) {
elr->lr_mode = EXT4_LI_MODE_ITABLE;
elr->lr_next_group = start;
} else {
elr->lr_mode = EXT4_LI_MODE_PREFETCH_BBITMAP;
}
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
elr->lr_next_sched = jiffies + get_random_u32_below(EXT4_DEF_LI_MAX_START_DELAY * HZ);
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = sbi->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (sb_rdonly(sb) ||
(test_opt(sb, NO_PREFETCH_BLOCK_BITMAPS) &&
(first_not_zeroed == ngroups || !test_opt(sb, INIT_INODE_TABLE))))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sb)) {
/* journal checksum v3 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_CSUM_V3 |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
int has_super = ext4_bg_has_super(sb, grp);
if (!ext4_has_feature_bigalloc(sb))
return (has_super + ext4_bg_num_gdb(sb, grp) +
(has_super ? le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) : 0) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
j = ext4_bg_num_gdb(sb, grp);
if (s + j > EXT4_BLOCKS_PER_GROUP(sb)) {
ext4_error(sb, "Invalid number of block group "
"descriptor blocks: %d", j);
j = EXT4_BLOCKS_PER_GROUP(sb) - s;
}
count += j;
for (; j > 0; j--)
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct inode *j_inode;
unsigned int j_blocks, j_inum = le32_to_cpu(es->s_journal_inum);
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_NOFS);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/*
* Add the internal journal blocks whether the journal has been
* loaded or not
*/
if (sbi->s_journal && !sbi->s_journal_bdev)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_total_len);
else if (ext4_has_feature_journal(sb) && !sbi->s_journal && j_inum) {
/* j_inum for internal journal is non-zero */
j_inode = ext4_get_journal_inode(sb, j_inum);
if (!IS_ERR(j_inode)) {
j_blocks = j_inode->i_size >> sb->s_blocksize_bits;
overhead += EXT4_NUM_B2C(sbi, j_blocks);
iput(j_inode);
} else {
ext4_msg(sb, KERN_ERR, "can't get journal size");
}
}
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static void ext4_set_resv_clusters(struct super_block *sb)
{
ext4_fsblk_t resv_clusters;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* There's no need to reserve anything when we aren't using extents.
* The space estimates are exact, there are no unwritten extents,
* hole punching doesn't need new metadata... This is needed especially
* to keep ext2/3 backward compatibility.
*/
if (!ext4_has_feature_extents(sb))
return;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* unwritten extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = (ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits);
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
atomic64_set(&sbi->s_resv_clusters, resv_clusters);
}
static const char *ext4_quota_mode(struct super_block *sb)
{
#ifdef CONFIG_QUOTA
if (!ext4_quota_capable(sb))
return "none";
if (EXT4_SB(sb)->s_journal && ext4_is_quota_journalled(sb))
return "journalled";
else
return "writeback";
#else
return "disabled";
#endif
}
static void ext4_setup_csum_trigger(struct super_block *sb,
enum ext4_journal_trigger_type type,
void (*trigger)(
struct jbd2_buffer_trigger_type *type,
struct buffer_head *bh,
void *mapped_data,
size_t size))
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
sbi->s_journal_triggers[type].sb = sb;
sbi->s_journal_triggers[type].tr_triggers.t_frozen = trigger;
}
static void ext4_free_sbi(struct ext4_sb_info *sbi)
{
if (!sbi)
return;
kfree(sbi->s_blockgroup_lock);
fs_put_dax(sbi->s_daxdev, NULL);
kfree(sbi);
}
static struct ext4_sb_info *ext4_alloc_sbi(struct super_block *sb)
{
struct ext4_sb_info *sbi;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
return NULL;
sbi->s_daxdev = fs_dax_get_by_bdev(sb->s_bdev, &sbi->s_dax_part_off,
NULL, NULL);
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock)
goto err_out;
sb->s_fs_info = sbi;
sbi->s_sb = sb;
return sbi;
err_out:
fs_put_dax(sbi->s_daxdev, NULL);
kfree(sbi);
return NULL;
}
static void ext4_set_def_opts(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned long def_mount_opts;
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
if (ext4_has_feature_fast_commit(sb))
set_opt2(sb, JOURNAL_FAST_COMMIT);
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
if (sb->s_blocksize == PAGE_SIZE)
set_opt(sb, DIOREAD_NOLOCK);
}
static int ext4_handle_clustersize(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int clustersize;
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
if (ext4_has_feature_bigalloc(sb)) {
if (clustersize < sb->s_blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%lu)", clustersize, sb->s_blocksize);
return -EINVAL;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > sb->s_blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
return -EINVAL;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / sb->s_blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
return -EINVAL;
}
} else {
if (clustersize != sb->s_blocksize) {
ext4_msg(sb, KERN_ERR,
"fragment/cluster size (%d) != "
"block size (%lu)", clustersize, sb->s_blocksize);
return -EINVAL;
}
if (sbi->s_blocks_per_group > sb->s_blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
return -EINVAL;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / sb->s_blocksize;
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
return 0;
}
static void ext4_fast_commit_init(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Initialize fast commit stuff */
atomic_set(&sbi->s_fc_subtid, 0);
INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_MAIN]);
INIT_LIST_HEAD(&sbi->s_fc_q[FC_Q_STAGING]);
INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_MAIN]);
INIT_LIST_HEAD(&sbi->s_fc_dentry_q[FC_Q_STAGING]);
sbi->s_fc_bytes = 0;
ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
sbi->s_fc_ineligible_tid = 0;
spin_lock_init(&sbi->s_fc_lock);
memset(&sbi->s_fc_stats, 0, sizeof(sbi->s_fc_stats));
sbi->s_fc_replay_state.fc_regions = NULL;
sbi->s_fc_replay_state.fc_regions_size = 0;
sbi->s_fc_replay_state.fc_regions_used = 0;
sbi->s_fc_replay_state.fc_regions_valid = 0;
sbi->s_fc_replay_state.fc_modified_inodes = NULL;
sbi->s_fc_replay_state.fc_modified_inodes_size = 0;
sbi->s_fc_replay_state.fc_modified_inodes_used = 0;
}
static int ext4_inode_info_init(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if (sbi->s_first_ino < EXT4_GOOD_OLD_FIRST_INO) {
ext4_msg(sb, KERN_ERR, "invalid first ino: %u",
sbi->s_first_ino);
return -EINVAL;
}
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > sb->s_blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
ext4_msg(sb, KERN_ERR, "blocksize: %lu", sb->s_blocksize);
return -EINVAL;
}
/*
* i_atime_extra is the last extra field available for
* [acm]times in struct ext4_inode. Checking for that
* field should suffice to ensure we have extra space
* for all three.
*/
if (sbi->s_inode_size >= offsetof(struct ext4_inode, i_atime_extra) +
sizeof(((struct ext4_inode *)0)->i_atime_extra)) {
sb->s_time_gran = 1;
sb->s_time_max = EXT4_EXTRA_TIMESTAMP_MAX;
} else {
sb->s_time_gran = NSEC_PER_SEC;
sb->s_time_max = EXT4_NON_EXTRA_TIMESTAMP_MAX;
}
sb->s_time_min = EXT4_TIMESTAMP_MIN;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
unsigned v, max = (sbi->s_inode_size -
EXT4_GOOD_OLD_INODE_SIZE);
v = le16_to_cpu(es->s_want_extra_isize);
if (v > max) {
ext4_msg(sb, KERN_ERR,
"bad s_want_extra_isize: %d", v);
return -EINVAL;
}
if (sbi->s_want_extra_isize < v)
sbi->s_want_extra_isize = v;
v = le16_to_cpu(es->s_min_extra_isize);
if (v > max) {
ext4_msg(sb, KERN_ERR,
"bad s_min_extra_isize: %d", v);
return -EINVAL;
}
if (sbi->s_want_extra_isize < v)
sbi->s_want_extra_isize = v;
}
}
return 0;
}
#if IS_ENABLED(CONFIG_UNICODE)
static int ext4_encoding_init(struct super_block *sb, struct ext4_super_block *es)
{
const struct ext4_sb_encodings *encoding_info;
struct unicode_map *encoding;
__u16 encoding_flags = le16_to_cpu(es->s_encoding_flags);
if (!ext4_has_feature_casefold(sb) || sb->s_encoding)
return 0;
encoding_info = ext4_sb_read_encoding(es);
if (!encoding_info) {
ext4_msg(sb, KERN_ERR,
"Encoding requested by superblock is unknown");
return -EINVAL;
}
encoding = utf8_load(encoding_info->version);
if (IS_ERR(encoding)) {
ext4_msg(sb, KERN_ERR,
"can't mount with superblock charset: %s-%u.%u.%u "
"not supported by the kernel. flags: 0x%x.",
encoding_info->name,
unicode_major(encoding_info->version),
unicode_minor(encoding_info->version),
unicode_rev(encoding_info->version),
encoding_flags);
return -EINVAL;
}
ext4_msg(sb, KERN_INFO,"Using encoding defined by superblock: "
"%s-%u.%u.%u with flags 0x%hx", encoding_info->name,
unicode_major(encoding_info->version),
unicode_minor(encoding_info->version),
unicode_rev(encoding_info->version),
encoding_flags);
sb->s_encoding = encoding;
sb->s_encoding_flags = encoding_flags;
return 0;
}
#else
static inline int ext4_encoding_init(struct super_block *sb, struct ext4_super_block *es)
{
return 0;
}
#endif
static int ext4_init_metadata_csum(struct super_block *sb, struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
return -EINVAL;
}
ext4_setup_csum_trigger(sb, EXT4_JTR_ORPHAN_FILE,
ext4_orphan_file_block_trigger);
/* Load the checksum driver */
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
int ret = PTR_ERR(sbi->s_chksum_driver);
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
sbi->s_chksum_driver = NULL;
return ret;
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
return -EFSBADCRC;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb) || ext4_has_feature_ea_inode(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
return 0;
}
static int ext4_check_feature_compatibility(struct super_block *sb,
struct ext4_super_block *es,
int silent)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
return -EINVAL;
}
/*
* ea_inode feature uses l_i_version field which is not
* available in HURD_COMPAT mode.
*/
if (ext4_has_feature_ea_inode(sb)) {
ext4_msg(sb, KERN_ERR,
"ea_inode feature is not supported for Hurd");
return -EINVAL;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
/*
* If we're probing be silent, if this looks like
* it's actually an ext[34] filesystem.
*/
if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
return -EINVAL;
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
return -EINVAL;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
/*
* If we're probing be silent, if this looks like
* it's actually an ext4 filesystem.
*/
if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
return -EINVAL;
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
return -EINVAL;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb_rdonly(sb))))
return -EINVAL;
if (sbi->s_daxdev) {
if (sb->s_blocksize == PAGE_SIZE)
set_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags);
else
ext4_msg(sb, KERN_ERR, "unsupported blocksize for DAX\n");
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) {
if (ext4_has_feature_inline_data(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot use DAX on a filesystem"
" that may contain inline data");
return -EINVAL;
}
if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags)) {
ext4_msg(sb, KERN_ERR,
"DAX unsupported by block device.");
return -EINVAL;
}
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
return -EINVAL;
}
return 0;
}
static int ext4_check_geometry(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
__u64 blocks_count;
int err;
if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (sb->s_blocksize / 4)) {
ext4_msg(sb, KERN_ERR,
"Number of reserved GDT blocks insanely large: %d",
le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
return -EINVAL;
}
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
return err;
}
/* check blocks count against device size */
blocks_count = sb_bdev_nr_blocks(sb);
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
return -EINVAL;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
return -EINVAL;
}
if ((es->s_first_data_block == 0) && (es->s_log_block_size == 0) &&
(sbi->s_cluster_ratio == 1)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block is 0 with a 1k block and cluster size");
return -EINVAL;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %llu "
"(block count %llu, first data block %u, "
"blocks per group %lu)", blocks_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
return -EINVAL;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
if (((u64)sbi->s_groups_count * sbi->s_inodes_per_group) !=
le32_to_cpu(es->s_inodes_count)) {
ext4_msg(sb, KERN_ERR, "inodes count not valid: %u vs %llu",
le32_to_cpu(es->s_inodes_count),
((u64)sbi->s_groups_count * sbi->s_inodes_per_group));
return -EINVAL;
}
return 0;
}
static int ext4_group_desc_init(struct super_block *sb,
struct ext4_super_block *es,
ext4_fsblk_t logical_sb_block,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned int db_count;
ext4_fsblk_t block;
int i;
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
if (ext4_has_feature_meta_bg(sb)) {
if (le32_to_cpu(es->s_first_meta_bg) > db_count) {
ext4_msg(sb, KERN_WARNING,
"first meta block group too large: %u "
"(group descriptor block count %u)",
le32_to_cpu(es->s_first_meta_bg), db_count);
return -EINVAL;
}
}
rcu_assign_pointer(sbi->s_group_desc,
kvmalloc_array(db_count,
sizeof(struct buffer_head *),
GFP_KERNEL));
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
return -ENOMEM;
}
bgl_lock_init(sbi->s_blockgroup_lock);
/* Pre-read the descriptors into the buffer cache */
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
ext4_sb_breadahead_unmovable(sb, block);
}
for (i = 0; i < db_count; i++) {
struct buffer_head *bh;
block = descriptor_loc(sb, logical_sb_block, i);
bh = ext4_sb_bread_unmovable(sb, block);
if (IS_ERR(bh)) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
sbi->s_gdb_count = i;
return PTR_ERR(bh);
}
rcu_read_lock();
rcu_dereference(sbi->s_group_desc)[i] = bh;
rcu_read_unlock();
}
sbi->s_gdb_count = db_count;
if (!ext4_check_descriptors(sb, logical_sb_block, first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
return -EFSCORRUPTED;
}
return 0;
}
static int ext4_load_and_init_journal(struct super_block *sb,
struct ext4_super_block *es,
struct ext4_fs_context *ctx)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err;
err = ext4_load_journal(sb, es, ctx->journal_devnum);
if (err)
return err;
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto out;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto out;
}
if (test_opt2(sb, JOURNAL_FAST_COMMIT) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_FAST_COMMIT)) {
ext4_msg(sb, KERN_ERR,
"Failed to set fast commit journal feature");
goto out;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
set_opt(sb, ORDERED_DATA);
sbi->s_def_mount_opt |= EXT4_MOUNT_ORDERED_DATA;
} else {
set_opt(sb, JOURNAL_DATA);
sbi->s_def_mount_opt |= EXT4_MOUNT_JOURNAL_DATA;
}
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto out;
}
break;
default:
break;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit in data=ordered mode");
goto out;
}
set_task_ioprio(sbi->s_journal->j_task, ctx->journal_ioprio);
sbi->s_journal->j_submit_inode_data_buffers =
ext4_journal_submit_inode_data_buffers;
sbi->s_journal->j_finish_inode_data_buffers =
ext4_journal_finish_inode_data_buffers;
return 0;
out:
/* flush s_sb_upd_work before destroying the journal. */
flush_work(&sbi->s_sb_upd_work);
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
return -EINVAL;
}
static int ext4_check_journal_data_mode(struct super_block *sb)
{
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting with "
"data=journal disables delayed allocation, "
"dioread_nolock, O_DIRECT and fast_commit support!\n");
/* can't mount with both data=journal and dioread_nolock. */
clear_opt(sb, DIOREAD_NOLOCK);
clear_opt2(sb, JOURNAL_FAST_COMMIT);
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
return -EINVAL;
}
if (test_opt(sb, DAX_ALWAYS)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
return -EINVAL;
}
if (ext4_has_feature_encrypt(sb)) {
ext4_msg(sb, KERN_WARNING,
"encrypted files will use data=ordered "
"instead of data journaling mode");
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
return 0;
}
static int ext4_load_super(struct super_block *sb, ext4_fsblk_t *lsb,
int silent)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es;
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
struct buffer_head *bh;
int ret = -EINVAL;
int blocksize;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
return -EINVAL;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sbi->s_sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sbi->s_sb_block;
}
bh = ext4_sb_bread_unmovable(sb, logical_sb_block);
if (IS_ERR(bh)) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
return PTR_ERR(bh);
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC) {
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto out;
}
if (le32_to_cpu(es->s_log_block_size) >
(EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log block size: %u",
le32_to_cpu(es->s_log_block_size));
goto out;
}
if (le32_to_cpu(es->s_log_cluster_size) >
(EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log cluster size: %u",
le32_to_cpu(es->s_log_cluster_size));
goto out;
}
blocksize = EXT4_MIN_BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
/*
* If the default block size is not the same as the real block size,
* we need to reload it.
*/
if (sb->s_blocksize == blocksize) {
*lsb = logical_sb_block;
sbi->s_sbh = bh;
return 0;
}
/*
* bh must be released before kill_bdev(), otherwise
* it won't be freed and its page also. kill_bdev()
* is called by sb_set_blocksize().
*/
brelse(bh);
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
bh = NULL;
goto out;
}
logical_sb_block = sbi->s_sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = ext4_sb_bread_unmovable(sb, logical_sb_block);
if (IS_ERR(bh)) {
ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try");
ret = PTR_ERR(bh);
bh = NULL;
goto out;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!");
goto out;
}
*lsb = logical_sb_block;
sbi->s_sbh = bh;
return 0;
out:
brelse(bh);
return ret;
}
static void ext4_hash_info_init(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
unsigned int i;
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!sb_rdonly(sb))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!sb_rdonly(sb))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
}
static int ext4_block_group_meta_init(struct super_block *sb, int silent)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int has_huge_files;
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
return -EINVAL;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
sbi->s_inodes_per_block = sb->s_blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0 || sbi->s_blocks_per_group == 0) {
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
return -EINVAL;
}
if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
sbi->s_inodes_per_group > sb->s_blocksize * 8) {
ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
sbi->s_inodes_per_group);
return -EINVAL;
}
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = sb->s_blocksize / EXT4_DESC_SIZE(sb);
sbi->s_mount_state = le16_to_cpu(es->s_state) & ~EXT4_FC_REPLAY;
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
return 0;
}
static int __ext4_fill_super(struct fs_context *fc, struct super_block *sb)
{
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t logical_sb_block;
struct inode *root;
int needs_recovery;
int err;
ext4_group_t first_not_zeroed;
struct ext4_fs_context *ctx = fc->fs_private;
int silent = fc->sb_flags & SB_SILENT;
/* Set defaults for the variables that will be set during parsing */
if (!(ctx->spec & EXT4_SPEC_JOURNAL_IOPRIO))
ctx->journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev, sectors[STAT_WRITE]);
err = ext4_load_super(sb, &logical_sb_block, silent);
if (err)
goto out_fail;
es = sbi->s_es;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
err = ext4_init_metadata_csum(sb, es);
if (err)
goto failed_mount;
ext4_set_def_opts(sb, es);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
err = ext4_inode_info_init(sb, es);
if (err)
goto failed_mount;
err = parse_apply_sb_mount_options(sb, ctx);
if (err < 0)
goto failed_mount;
sbi->s_def_mount_opt = sbi->s_mount_opt;
sbi->s_def_mount_opt2 = sbi->s_mount_opt2;
err = ext4_check_opt_consistency(fc, sb);
if (err < 0)
goto failed_mount;
ext4_apply_options(fc, sb);
err = ext4_encoding_init(sb, es);
if (err)
goto failed_mount;
err = ext4_check_journal_data_mode(sb);
if (err)
goto failed_mount;
sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
/* i_version is always enabled now */
sb->s_flags |= SB_I_VERSION;
err = ext4_check_feature_compatibility(sb, es, silent);
if (err)
goto failed_mount;
err = ext4_block_group_meta_init(sb, silent);
if (err)
goto failed_mount;
ext4_hash_info_init(sb);
err = ext4_handle_clustersize(sb);
if (err)
goto failed_mount;
err = ext4_check_geometry(sb, es);
if (err)
goto failed_mount;
timer_setup(&sbi->s_err_report, print_daily_error_info, 0);
spin_lock_init(&sbi->s_error_lock);
INIT_WORK(&sbi->s_sb_upd_work, update_super_work);
err = ext4_group_desc_init(sb, es, logical_sb_block, &first_not_zeroed);
if (err)
goto failed_mount3;
err = ext4_es_register_shrinker(sbi);
if (err)
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
/*
* It's hard to get stripe aligned blocks if stripe is not aligned with
* cluster, just disable stripe and alert user to simpfy code and avoid
* stripe aligned allocation which will rarely successes.
*/
if (sbi->s_stripe > 0 && sbi->s_cluster_ratio > 1 &&
sbi->s_stripe % sbi->s_cluster_ratio != 0) {
ext4_msg(sb, KERN_WARNING,
"stripe (%lu) is not aligned with cluster size (%u), "
"stripe is disabled",
sbi->s_stripe, sbi->s_cluster_ratio);
sbi->s_stripe = 0;
}
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
#ifdef CONFIG_FS_ENCRYPTION
sb->s_cop = &ext4_cryptops;
#endif
#ifdef CONFIG_FS_VERITY
sb->s_vop = &ext4_verityops;
#endif
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(&sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
ext4_fast_commit_init(sb);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_orphan_present(sb) ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !sb_rdonly(sb)) {
err = ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block));
if (err)
goto failed_mount3a;
}
err = -EINVAL;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
err = ext4_load_and_init_journal(sb, es, ctx);
if (err)
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !sb_rdonly(sb) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount3a;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount3a;
}
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount3a;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount3a;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount3a;
}
sbi->s_def_mount_opt &= ~EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
clear_opt2(sb, JOURNAL_FAST_COMMIT);
sbi->s_journal = NULL;
needs_recovery = 0;
}
if (!test_opt(sb, NO_MBCACHE)) {
sbi->s_ea_block_cache = ext4_xattr_create_cache();
if (!sbi->s_ea_block_cache) {
ext4_msg(sb, KERN_ERR,
"Failed to create ea_block_cache");
err = -EINVAL;
goto failed_mount_wq;
}
if (ext4_has_feature_ea_inode(sb)) {
sbi->s_ea_inode_cache = ext4_xattr_create_cache();
if (!sbi->s_ea_inode_cache) {
ext4_msg(sb, KERN_ERR,
"Failed to create ea_inode_cache");
err = -EINVAL;
goto failed_mount_wq;
}
}
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
/* ignore the precalculated value if it is ridiculous */
if (sbi->s_overhead > ext4_blocks_count(es))
sbi->s_overhead = 0;
/*
* If the bigalloc feature is not enabled recalculating the
* overhead doesn't take long, so we might as well just redo
* it to make sure we are using the correct value.
*/
if (!ext4_has_feature_bigalloc(sb))
sbi->s_overhead = 0;
if (sbi->s_overhead == 0) {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
err = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO, EXT4_IGET_SPECIAL);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
err = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
err = -EFSCORRUPTED;
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
err = -ENOMEM;
goto failed_mount4;
}
err = ext4_setup_super(sb, es, sb_rdonly(sb));
if (err == -EROFS) {
sb->s_flags |= SB_RDONLY;
} else if (err)
goto failed_mount4a;
ext4_set_resv_clusters(sb);
if (test_opt(sb, BLOCK_VALIDITY)) {
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
}
ext4_fc_replay_cleanup(sb);
ext4_ext_init(sb);
/*
* Enable optimize_scan if number of groups is > threshold. This can be
* turned off by passing "mb_optimize_scan=0". This can also be
* turned on forcefully by passing "mb_optimize_scan=1".
*/
if (!(ctx->spec & EXT4_SPEC_mb_optimize_scan)) {
if (sbi->s_groups_count >= MB_DEFAULT_LINEAR_SCAN_THRESHOLD)
set_opt2(sb, MB_OPTIMIZE_SCAN);
else
clear_opt2(sb, MB_OPTIMIZE_SCAN);
}
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
/*
* We can only set up the journal commit callback once
* mballoc is initialized
*/
if (sbi->s_journal)
sbi->s_journal->j_commit_callback =
ext4_journal_commit_callback;
err = ext4_percpu_param_init(sbi);
if (err)
goto failed_mount6;
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
err = -ENOMEM;
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
err = ext4_init_orphan_info(sb);
if (err)
goto failed_mount8;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !sb_rdonly(sb)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount9;
}
#endif /* CONFIG_QUOTA */
/*
* Save the original bdev mapping's wb_err value which could be
* used to detect the metadata async write error.
*/
spin_lock_init(&sbi->s_bdev_wb_lock);
errseq_check_and_advance(&sb->s_bdev->bd_inode->i_mapping->wb_err,
&sbi->s_bdev_wb_err);
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
/*
* Update the checksum after updating free space/inode counters and
* ext4_orphan_cleanup. Otherwise the superblock can have an incorrect
* checksum in the buffer cache until it is written out and
* e2fsprogs programs trying to open a file system immediately
* after it is mounted can fail.
*/
ext4_superblock_csum_set(sb);
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
err = ext4_mark_recovery_complete(sb, es);
if (err)
goto failed_mount10;
}
if (test_opt(sb, DISCARD) && !bdev_max_discard_sectors(sb->s_bdev))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but the device does not support discard");
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
atomic_set(&sbi->s_warning_count, 0);
atomic_set(&sbi->s_msg_count, 0);
return 0;
failed_mount10:
ext4_quotas_off(sb, EXT4_MAXQUOTAS);
failed_mount9: __maybe_unused
ext4_release_orphan_info(sb);
failed_mount8:
ext4_unregister_sysfs(sb);
kobject_put(&sbi->s_kobj);
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
ext4_flex_groups_free(sbi);
ext4_percpu_param_destroy(sbi);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
sbi->s_ea_inode_cache = NULL;
ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
sbi->s_ea_block_cache = NULL;
if (sbi->s_journal) {
/* flush s_sb_upd_work before journal destroy. */
flush_work(&sbi->s_sb_upd_work);
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
/* flush s_sb_upd_work before sbi destroy */
flush_work(&sbi->s_sb_upd_work);
del_timer_sync(&sbi->s_err_report);
ext4_stop_mmpd(sbi);
ext4_group_desc_free(sbi);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#if IS_ENABLED(CONFIG_UNICODE)
utf8_unload(sb->s_encoding);
#endif
#ifdef CONFIG_QUOTA
for (unsigned int i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(get_qf_name(sb, sbi, i));
#endif
fscrypt_free_dummy_policy(&sbi->s_dummy_enc_policy);
brelse(sbi->s_sbh);
if (sbi->s_journal_bdev) {
invalidate_bdev(sbi->s_journal_bdev);
blkdev_put(sbi->s_journal_bdev, sb);
}
out_fail:
invalidate_bdev(sb->s_bdev);
sb->s_fs_info = NULL;
return err;
}
static int ext4_fill_super(struct super_block *sb, struct fs_context *fc)
{
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_sb_info *sbi;
const char *descr;
int ret;
sbi = ext4_alloc_sbi(sb);
if (!sbi)
return -ENOMEM;
fc->s_fs_info = sbi;
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
sbi->s_sb_block = 1; /* Default super block location */
if (ctx->spec & EXT4_SPEC_s_sb_block)
sbi->s_sb_block = ctx->s_sb_block;
ret = __ext4_fill_super(fc, sb);
if (ret < 0)
goto free_sbi;
if (sbi->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem %pU %s with%s. "
"Quota mode: %s.", &sb->s_uuid,
sb_rdonly(sb) ? "ro" : "r/w", descr,
ext4_quota_mode(sb));
/* Update the s_overhead_clusters if necessary */
ext4_update_overhead(sb, false);
return 0;
free_sbi:
ext4_free_sbi(sbi);
fc->s_fs_info = NULL;
return ret;
}
static int ext4_get_tree(struct fs_context *fc)
{
return get_tree_bdev(fc, ext4_fill_super);
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
ext4_fc_init(sb, journal);
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
/*
* Always enable journal cycle record option, letting the journal
* records log transactions continuously between each mount.
*/
journal->j_flags |= JBD2_CYCLE_RECORD;
write_unlock(&journal->j_state_lock);
}
static struct inode *ext4_get_journal_inode(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
/*
* Test for the existence of a valid inode on disk. Bad things
* happen if we iget() an unused inode, as the subsequent iput()
* will try to delete it.
*/
journal_inode = ext4_iget(sb, journal_inum, EXT4_IGET_SPECIAL);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return ERR_CAST(journal_inode);
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return ERR_PTR(-EFSCORRUPTED);
}
if (!S_ISREG(journal_inode->i_mode) || IS_ENCRYPTED(journal_inode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return ERR_PTR(-EFSCORRUPTED);
}
ext4_debug("Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
return journal_inode;
}
static int ext4_journal_bmap(journal_t *journal, sector_t *block)
{
struct ext4_map_blocks map;
int ret;
if (journal->j_inode == NULL)
return 0;
map.m_lblk = *block;
map.m_len = 1;
ret = ext4_map_blocks(NULL, journal->j_inode, &map, 0);
if (ret <= 0) {
ext4_msg(journal->j_inode->i_sb, KERN_CRIT,
"journal bmap failed: block %llu ret %d\n",
*block, ret);
jbd2_journal_abort(journal, ret ? ret : -EIO);
return ret;
}
*block = map.m_pblk;
return 0;
}
static journal_t *ext4_open_inode_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
journal_inode = ext4_get_journal_inode(sb, journal_inum);
if (IS_ERR(journal_inode))
return ERR_CAST(journal_inode);
journal = jbd2_journal_init_inode(journal_inode);
if (IS_ERR(journal)) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return ERR_CAST(journal);
}
journal->j_private = sb;
journal->j_bmap = ext4_journal_bmap;
ext4_init_journal_params(sb, journal);
return journal;
}
static struct block_device *ext4_get_journal_blkdev(struct super_block *sb,
dev_t j_dev, ext4_fsblk_t *j_start,
ext4_fsblk_t *j_len)
{
struct buffer_head *bh;
struct block_device *bdev;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
int errno;
/* see get_tree_bdev why this is needed and safe */
up_write(&sb->s_umount);
bdev = blkdev_get_by_dev(j_dev, BLK_OPEN_READ | BLK_OPEN_WRITE, sb,
&fs_holder_ops);
down_write(&sb->s_umount);
if (IS_ERR(bdev)) {
ext4_msg(sb, KERN_ERR,
"failed to open journal device unknown-block(%u,%u) %ld",
MAJOR(j_dev), MINOR(j_dev), PTR_ERR(bdev));
return ERR_CAST(bdev);
}
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
errno = -EINVAL;
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
bh = __bread(bdev, sb_block, blocksize);
if (!bh) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
errno = -EINVAL;
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has bad superblock");
errno = -EFSCORRUPTED;
goto out_bh;
}
if ((le32_to_cpu(es->s_feature_ro_compat) &
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "external journal has corrupt superblock");
errno = -EFSCORRUPTED;
goto out_bh;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
errno = -EFSCORRUPTED;
goto out_bh;
}
*j_start = sb_block + 1;
*j_len = ext4_blocks_count(es);
brelse(bh);
return bdev;
out_bh:
brelse(bh);
out_bdev:
blkdev_put(bdev, sb);
return ERR_PTR(errno);
}
static journal_t *ext4_open_dev_journal(struct super_block *sb,
dev_t j_dev)
{
journal_t *journal;
ext4_fsblk_t j_start;
ext4_fsblk_t j_len;
struct block_device *journal_bdev;
int errno = 0;
journal_bdev = ext4_get_journal_blkdev(sb, j_dev, &j_start, &j_len);
if (IS_ERR(journal_bdev))
return ERR_CAST(journal_bdev);
journal = jbd2_journal_init_dev(journal_bdev, sb->s_bdev, j_start,
j_len, sb->s_blocksize);
if (IS_ERR(journal)) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
errno = PTR_ERR(journal);
goto out_bdev;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
errno = -EINVAL;
goto out_journal;
}
journal->j_private = sb;
EXT4_SB(sb)->s_journal_bdev = journal_bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
blkdev_put(journal_bdev, sb);
return ERR_PTR(errno);
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
int journal_dev_ro;
if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
return -EFSCORRUPTED;
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR,
"filesystem has both journal inode and journal device!");
return -EINVAL;
}
if (journal_inum) {
journal = ext4_open_inode_journal(sb, journal_inum);
if (IS_ERR(journal))
return PTR_ERR(journal);
} else {
journal = ext4_open_dev_journal(sb, journal_dev);
if (IS_ERR(journal))
return PTR_ERR(journal);
}
journal_dev_ro = bdev_read_only(journal->j_dev);
really_read_only = bdev_read_only(sb->s_bdev) | journal_dev_ro;
if (journal_dev_ro && !sb_rdonly(sb)) {
ext4_msg(sb, KERN_ERR,
"journal device read-only, try mounting with '-o ro'");
err = -EROFS;
goto err_out;
}
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (ext4_has_feature_journal_needs_recovery(sb)) {
if (sb_rdonly(sb)) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed "
"(try mounting with noload)");
err = -EROFS;
goto err_out;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!ext4_has_feature_journal_needs_recovery(sb))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
__le16 orig_state;
bool changed = false;
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save && memcmp(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN)) {
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
changed = true;
}
kfree(save);
orig_state = es->s_state;
es->s_state |= cpu_to_le16(EXT4_SB(sb)->s_mount_state &
EXT4_ERROR_FS);
if (orig_state != es->s_state)
changed = true;
/* Write out restored error information to the superblock */
if (changed && !really_read_only) {
int err2;
err2 = ext4_commit_super(sb);
err = err ? : err2;
}
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
goto err_out;
}
EXT4_SB(sb)->s_journal = journal;
err = ext4_clear_journal_err(sb, es);
if (err) {
EXT4_SB(sb)->s_journal = NULL;
jbd2_journal_destroy(journal);
return err;
}
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
ext4_commit_super(sb);
}
if (!really_read_only && journal_inum &&
journal_inum != le32_to_cpu(es->s_journal_inum)) {
es->s_journal_inum = cpu_to_le32(journal_inum);
ext4_commit_super(sb);
}
return 0;
err_out:
jbd2_journal_destroy(journal);
return err;
}
/* Copy state of EXT4_SB(sb) into buffer for on-disk superblock */
static void ext4_update_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct buffer_head *sbh = sbi->s_sbh;
lock_buffer(sbh);
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!sb_rdonly(sb))
ext4_update_tstamp(es, s_wtime);
es->s_kbytes_written =
cpu_to_le64(sbi->s_kbytes_written +
((part_stat_read(sb->s_bdev, sectors[STAT_WRITE]) -
sbi->s_sectors_written_start) >> 1));
if (percpu_counter_initialized(&sbi->s_freeclusters_counter))
ext4_free_blocks_count_set(es,
EXT4_C2B(sbi, percpu_counter_sum_positive(
&sbi->s_freeclusters_counter)));
if (percpu_counter_initialized(&sbi->s_freeinodes_counter))
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&sbi->s_freeinodes_counter));
/* Copy error information to the on-disk superblock */
spin_lock(&sbi->s_error_lock);
if (sbi->s_add_error_count > 0) {
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
if (!es->s_first_error_time && !es->s_first_error_time_hi) {
__ext4_update_tstamp(&es->s_first_error_time,
&es->s_first_error_time_hi,
sbi->s_first_error_time);
strncpy(es->s_first_error_func, sbi->s_first_error_func,
sizeof(es->s_first_error_func));
es->s_first_error_line =
cpu_to_le32(sbi->s_first_error_line);
es->s_first_error_ino =
cpu_to_le32(sbi->s_first_error_ino);
es->s_first_error_block =
cpu_to_le64(sbi->s_first_error_block);
es->s_first_error_errcode =
ext4_errno_to_code(sbi->s_first_error_code);
}
__ext4_update_tstamp(&es->s_last_error_time,
&es->s_last_error_time_hi,
sbi->s_last_error_time);
strncpy(es->s_last_error_func, sbi->s_last_error_func,
sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(sbi->s_last_error_line);
es->s_last_error_ino = cpu_to_le32(sbi->s_last_error_ino);
es->s_last_error_block = cpu_to_le64(sbi->s_last_error_block);
es->s_last_error_errcode =
ext4_errno_to_code(sbi->s_last_error_code);
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, sbi->s_add_error_count);
sbi->s_add_error_count = 0;
}
spin_unlock(&sbi->s_error_lock);
ext4_superblock_csum_set(sb);
unlock_buffer(sbh);
}
static int ext4_commit_super(struct super_block *sb)
{
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
if (!sbh)
return -EINVAL;
if (block_device_ejected(sb))
return -ENODEV;
ext4_update_super(sb);
lock_buffer(sbh);
/* Buffer got discarded which means block device got invalidated */
if (!buffer_mapped(sbh)) {
unlock_buffer(sbh);
return -EIO;
}
if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
get_bh(sbh);
/* Clear potential dirty bit if it was journalled update */
clear_buffer_dirty(sbh);
sbh->b_end_io = end_buffer_write_sync;
submit_bh(REQ_OP_WRITE | REQ_SYNC |
(test_opt(sb, BARRIER) ? REQ_FUA : 0), sbh);
wait_on_buffer(sbh);
if (buffer_write_io_error(sbh)) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
return -EIO;
}
return 0;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static int ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
int err;
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!ext4_has_feature_journal(sb)) {
if (journal != NULL) {
ext4_error(sb, "Journal got removed while the fs was "
"mounted!");
return -EFSCORRUPTED;
}
return 0;
}
jbd2_journal_lock_updates(journal);
err = jbd2_journal_flush(journal, 0);
if (err < 0)
goto out;
if (sb_rdonly(sb) && (ext4_has_feature_journal_needs_recovery(sb) ||
ext4_has_feature_orphan_present(sb))) {
if (!ext4_orphan_file_empty(sb)) {
ext4_error(sb, "Orphan file not empty on read-only fs.");
err = -EFSCORRUPTED;
goto out;
}
ext4_clear_feature_journal_needs_recovery(sb);
ext4_clear_feature_orphan_present(sb);
ext4_commit_super(sb);
}
out:
jbd2_journal_unlock_updates(journal);
return err;
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static int ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
if (!ext4_has_feature_journal(sb)) {
ext4_error(sb, "Journal got removed while the fs was mounted!");
return -EFSCORRUPTED;
}
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
j_errno = ext4_commit_super(sb);
if (j_errno)
return j_errno;
ext4_warning(sb, "Marked fs in need of filesystem check.");
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
return 0;
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
return ext4_journal_force_commit(EXT4_SB(sb)->s_journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (unlikely(ext4_forced_shutdown(sb)))
return 0;
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
if (sbi->s_journal) {
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal,
target);
}
} else if (wait && test_opt(sb, BARRIER))
needs_barrier = true;
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev);
if (!ret)
ret = err;
}
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal = EXT4_SB(sb)->s_journal;
if (journal) {
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to
* flush the journal.
*/
error = jbd2_journal_flush(journal, 0);
if (error < 0)
goto out;
/* Journal blocked and flushed, clear needs_recovery flag. */
ext4_clear_feature_journal_needs_recovery(sb);
if (ext4_orphan_file_empty(sb))
ext4_clear_feature_orphan_present(sb);
}
error = ext4_commit_super(sb);
out:
if (journal)
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (ext4_forced_shutdown(sb))
return 0;
if (EXT4_SB(sb)->s_journal) {
/* Reset the needs_recovery flag before the fs is unlocked. */
ext4_set_feature_journal_needs_recovery(sb);
if (ext4_has_feature_orphan_file(sb))
ext4_set_feature_orphan_present(sb);
}
ext4_commit_super(sb);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[EXT4_MAXQUOTAS];
#endif
};
static int __ext4_remount(struct fs_context *fc, struct super_block *sb)
{
struct ext4_fs_context *ctx = fc->fs_private;
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
ext4_group_t g;
int err = 0;
#ifdef CONFIG_QUOTA
int enable_quota = 0;
int i, j;
char *to_free[EXT4_MAXQUOTAS];
#endif
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
char *qf_name = get_qf_name(sb, sbi, i);
old_opts.s_qf_names[i] = kstrdup(qf_name, GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (!(ctx->spec & EXT4_SPEC_JOURNAL_IOPRIO)) {
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
ctx->journal_ioprio =
sbi->s_journal->j_task->io_context->ioprio;
else
ctx->journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
}
ext4_apply_options(fc, sb);
if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
test_opt(sb, JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "changing journal_checksum "
"during remount not supported; ignoring");
sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
err = -EINVAL;
goto restore_opts;
}
} else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) {
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit in data=ordered mode");
err = -EINVAL;
goto restore_opts;
}
}
if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_NO_MBCACHE) {
ext4_msg(sb, KERN_ERR, "can't enable nombcache during remount");
err = -EINVAL;
goto restore_opts;
}
if (test_opt2(sb, ABORT))
ext4_abort(sb, ESHUTDOWN, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, ctx->journal_ioprio);
}
/* Flush outstanding errors before changing fs state */
flush_work(&sbi->s_sb_upd_work);
if ((bool)(fc->sb_flags & SB_RDONLY) != sb_rdonly(sb)) {
if (ext4_forced_shutdown(sb)) {
err = -EROFS;
goto restore_opts;
}
if (fc->sb_flags & SB_RDONLY) {
err = sync_filesystem(sb);
if (err < 0)
goto restore_opts;
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= SB_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal) {
/*
* We let remount-ro finish even if marking fs
* as clean failed...
*/
ext4_mark_recovery_complete(sb, es);
}
} else {
/* Make sure we can mount this feature set readwrite */
if (ext4_has_feature_readonly(sb) ||
!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EFSBADCRC;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan || !ext4_orphan_file_empty(sb)) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal) {
err = ext4_clear_journal_err(sb, es);
if (err)
goto restore_opts;
}
sbi->s_mount_state = (le16_to_cpu(es->s_state) &
~EXT4_FC_REPLAY);
err = ext4_setup_super(sb, es, 0);
if (err)
goto restore_opts;
sb->s_flags &= ~SB_RDONLY;
if (ext4_has_feature_mmp(sb)) {
err = ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block));
if (err)
goto restore_opts;
}
#ifdef CONFIG_QUOTA
enable_quota = 1;
#endif
}
}
/*
* Handle creation of system zone data early because it can fail.
* Releasing of existing data is done when we are sure remount will
* succeed.
*/
if (test_opt(sb, BLOCK_VALIDITY) && !sbi->s_system_blks) {
err = ext4_setup_system_zone(sb);
if (err)
goto restore_opts;
}
if (sbi->s_journal == NULL && !(old_sb_flags & SB_RDONLY)) {
err = ext4_commit_super(sb);
if (err)
goto restore_opts;
}
#ifdef CONFIG_QUOTA
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (ext4_has_feature_quota(sb)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
/* Release old quota file names */
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
#endif
if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
ext4_release_system_zone(sb);
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if (sb_rdonly(sb) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
if (!ext4_has_feature_mmp(sb) || sb_rdonly(sb))
ext4_stop_mmpd(sbi);
return 0;
restore_opts:
/*
* If there was a failing r/w to ro transition, we may need to
* re-enable quota
*/
if (sb_rdonly(sb) && !(old_sb_flags & SB_RDONLY) &&
sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
ext4_release_system_zone(sb);
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
to_free[i] = get_qf_name(sb, sbi, i);
rcu_assign_pointer(sbi->s_qf_names[i], old_opts.s_qf_names[i]);
}
synchronize_rcu();
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(to_free[i]);
#endif
if (!ext4_has_feature_mmp(sb) || sb_rdonly(sb))
ext4_stop_mmpd(sbi);
return err;
}
static int ext4_reconfigure(struct fs_context *fc)
{
struct super_block *sb = fc->root->d_sb;
int ret;
fc->s_fs_info = EXT4_SB(sb);
ret = ext4_check_opt_consistency(fc, sb);
if (ret < 0)
return ret;
ret = __ext4_remount(fc, sb);
if (ret < 0)
return ret;
ext4_msg(sb, KERN_INFO, "re-mounted %pU %s. Quota mode: %s.",
&sb->s_uuid, sb_rdonly(sb) ? "ro" : "r/w",
ext4_quota_mode(sb));
return 0;
}
#ifdef CONFIG_QUOTA
static int ext4_statfs_project(struct super_block *sb,
kprojid_t projid, struct kstatfs *buf)
{
struct kqid qid;
struct dquot *dquot;
u64 limit;
u64 curblock;
qid = make_kqid_projid(projid);
dquot = dqget(sb, qid);
if (IS_ERR(dquot))
return PTR_ERR(dquot);
spin_lock(&dquot->dq_dqb_lock);
limit = min_not_zero(dquot->dq_dqb.dqb_bsoftlimit,
dquot->dq_dqb.dqb_bhardlimit);
limit >>= sb->s_blocksize_bits;
if (limit && buf->f_blocks > limit) {
curblock = (dquot->dq_dqb.dqb_curspace +
dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
buf->f_blocks = limit;
buf->f_bfree = buf->f_bavail =
(buf->f_blocks > curblock) ?
(buf->f_blocks - curblock) : 0;
}
limit = min_not_zero(dquot->dq_dqb.dqb_isoftlimit,
dquot->dq_dqb.dqb_ihardlimit);
if (limit && buf->f_files > limit) {
buf->f_files = limit;
buf->f_ffree =
(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
(buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
}
spin_unlock(&dquot->dq_dqb_lock);
dqput(dquot);
return 0;
}
#endif
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
buf->f_fsid = uuid_to_fsid(es->s_uuid);
#ifdef CONFIG_QUOTA
if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
sb_has_quota_limits_enabled(sb, PRJQUOTA))
ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
#endif
return 0;
}
#ifdef CONFIG_QUOTA
/*
* Helper functions so that transaction is started before we acquire dqio_sem
* to keep correct lock ordering of transaction > dqio_sem
*/
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
if (ext4_is_quota_journalled(sb)) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start_sb(sb, EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static void lockdep_set_quota_inode(struct inode *inode, int subclass)
{
struct ext4_inode_info *ei = EXT4_I(inode);
/* The first argument of lockdep_set_subclass has to be
* *exactly* the same as the argument to init_rwsem() --- in
* this case, in init_once() --- or lockdep gets unhappy
* because the name of the lock is set using the
* stringification of the argument to init_rwsem().
*/
(void) ei; /* shut up clang warning if !CONFIG_LOCKDEP */
lockdep_set_subclass(&ei->i_data_sem, subclass);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
const struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Quota already enabled for this file? */
if (IS_NOQUOTA(d_inode(path->dentry)))
return -EBUSY;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
sb_dqopt(sb)->flags |= DQUOT_NOLIST_DIRTY;
} else {
/*
* Clear the flag just in case mount options changed since
* last time.
*/
sb_dqopt(sb)->flags &= ~DQUOT_NOLIST_DIRTY;
}
lockdep_set_quota_inode(path->dentry->d_inode, I_DATA_SEM_QUOTA);
err = dquot_quota_on(sb, type, format_id, path);
if (!err) {
struct inode *inode = d_inode(path->dentry);
handle_t *handle;
/*
* Set inode flags to prevent userspace from messing with quota
* files. If this fails, we return success anyway since quotas
* are already enabled and this is not a hard failure.
*/
inode_lock(inode);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto unlock_inode;
EXT4_I(inode)->i_flags |= EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL;
inode_set_flags(inode, S_NOATIME | S_IMMUTABLE,
S_NOATIME | S_IMMUTABLE);
err = ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
unlock_inode:
inode_unlock(inode);
if (err)
dquot_quota_off(sb, type);
}
if (err)
lockdep_set_quota_inode(path->dentry->d_inode,
I_DATA_SEM_NORMAL);
return err;
}
static inline bool ext4_check_quota_inum(int type, unsigned long qf_inum)
{
switch (type) {
case USRQUOTA:
return qf_inum == EXT4_USR_QUOTA_INO;
case GRPQUOTA:
return qf_inum == EXT4_GRP_QUOTA_INO;
case PRJQUOTA:
return qf_inum >= EXT4_GOOD_OLD_FIRST_INO;
default:
BUG();
}
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
BUG_ON(!ext4_has_feature_quota(sb));
if (!qf_inums[type])
return -EPERM;
if (!ext4_check_quota_inum(type, qf_inums[type])) {
ext4_error(sb, "Bad quota inum: %lu, type: %d",
qf_inums[type], type);
return -EUCLEAN;
}
qf_inode = ext4_iget(sb, qf_inums[type], EXT4_IGET_SPECIAL);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode: %lu, type: %d",
qf_inums[type], type);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA);
err = dquot_load_quota_inode(qf_inode, type, format_id, flags);
if (err)
lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL);
iput(qf_inode);
return err;
}
/* Enable usage tracking for all quota types. */
int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
bool quota_mopt[EXT4_MAXQUOTAS] = {
test_opt(sb, USRQUOTA),
test_opt(sb, GRPQUOTA),
test_opt(sb, PRJQUOTA),
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
for (type = 0; type < EXT4_MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED |
(quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d, ino=%lu). "
"Please run e2fsck to fix.", type,
err, qf_inums[type]);
ext4_quotas_off(sb, type);
return err;
}
}
}
return 0;
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
int err;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode || !igrab(inode))
goto out;
err = dquot_quota_off(sb, type);
if (err || ext4_has_feature_quota(sb))
goto out_put;
/*
* When the filesystem was remounted read-only first, we cannot cleanup
* inode flags here. Bad luck but people should be using QUOTA feature
* these days anyway.
*/
if (sb_rdonly(sb))
goto out_put;
inode_lock(inode);
/*
* Update modification times of quota files when userspace can
* start looking at them. If we fail, we return success anyway since
* this is not a hard failure and quotas are already disabled.
*/
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto out_unlock;
}
EXT4_I(inode)->i_flags &= ~(EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL);
inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
inode->i_mtime = inode_set_ctime_current(inode);
err = ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out_unlock:
inode_unlock(inode);
out_put:
lockdep_set_quota_inode(inode, I_DATA_SEM_NORMAL);
iput(inode);
return err;
out:
return dquot_quota_off(sb, type);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = min_t(unsigned long, sb->s_blocksize - offset, toread);
bh = ext4_bread(NULL, inode, blk, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err = 0, err2 = 0, offset = off & (sb->s_blocksize - 1);
int retries = 0;
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (!handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
do {
bh = ext4_bread(handle, inode, blk,
EXT4_GET_BLOCKS_CREATE |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
} while (PTR_ERR(bh) == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries));
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto out;
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, sb, bh, EXT4_JTR_NONE);
if (err) {
brelse(bh);
return err;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
err2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(err2 && !err))
err = err2;
}
return err ? err : len;
}
#endif
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext2_incompat_features(sb))
return 0;
if (sb_rdonly(sb))
return 1;
if (ext4_has_unknown_ext2_ro_compat_features(sb))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext3_incompat_features(sb))
return 0;
if (!ext4_has_feature_journal(sb))
return 0;
if (sb_rdonly(sb))
return 1;
if (ext4_has_unknown_ext3_ro_compat_features(sb))
return 0;
return 1;
}
static void ext4_kill_sb(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct block_device *journal_bdev = sbi ? sbi->s_journal_bdev : NULL;
kill_block_super(sb);
if (journal_bdev)
blkdev_put(journal_bdev, sb);
}
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.init_fs_context = ext4_init_fs_context,
.parameters = ext4_param_specs,
.kill_sb = ext4_kill_sb,
.fs_flags = FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
};
MODULE_ALIAS_FS("ext4");
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
ext4_li_info = NULL;
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++)
init_waitqueue_head(&ext4__ioend_wq[i]);
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pending();
if (err)
goto out7;
err = ext4_init_post_read_processing();
if (err)
goto out6;
err = ext4_init_pageio();
if (err)
goto out5;
err = ext4_init_system_zone();
if (err)
goto out4;
err = ext4_init_sysfs();
if (err)
goto out3;
err = ext4_init_mballoc();
if (err)
goto out2;
err = init_inodecache();
if (err)
goto out1;
err = ext4_fc_init_dentry_cache();
if (err)
goto out05;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
ext4_fc_destroy_dentry_cache();
out05:
destroy_inodecache();
out1:
ext4_exit_mballoc();
out2:
ext4_exit_sysfs();
out3:
ext4_exit_system_zone();
out4:
ext4_exit_pageio();
out5:
ext4_exit_post_read_processing();
out6:
ext4_exit_pending();
out7:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
ext4_fc_destroy_dentry_cache();
destroy_inodecache();
ext4_exit_mballoc();
ext4_exit_sysfs();
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_post_read_processing();
ext4_exit_es();
ext4_exit_pending();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
MODULE_SOFTDEP("pre: crc32c");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
| linux-master | fs/ext4/super.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2003-2006, Cluster File Systems, Inc, [email protected]
* Written by Alex Tomas <[email protected]>
*
* Architecture independence:
* Copyright (c) 2005, Bull S.A.
* Written by Pierre Peiffer <[email protected]>
*/
/*
* Extents support for EXT4
*
* TODO:
* - ext4*_error() should be used in some situations
* - analyze all BUG()/BUG_ON(), use -EIO where appropriate
* - smart tree reduction
*/
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/jbd2.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/fiemap.h>
#include <linux/iomap.h>
#include <linux/sched/mm.h>
#include "ext4_jbd2.h"
#include "ext4_extents.h"
#include "xattr.h"
#include <trace/events/ext4.h>
/*
* used by extent splitting.
*/
#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
due to ENOSPC */
#define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
#define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
#define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
#define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
static __le32 ext4_extent_block_csum(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
EXT4_EXTENT_TAIL_OFFSET(eh));
return cpu_to_le32(csum);
}
static int ext4_extent_block_csum_verify(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
et = find_ext4_extent_tail(eh);
if (et->et_checksum != ext4_extent_block_csum(inode, eh))
return 0;
return 1;
}
static void ext4_extent_block_csum_set(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent_tail *et;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
et = find_ext4_extent_tail(eh);
et->et_checksum = ext4_extent_block_csum(inode, eh);
}
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags);
static int ext4_ext_trunc_restart_fn(struct inode *inode, int *dropped)
{
/*
* Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
* moment, get_block can be called only for blocks inside i_size since
* page cache has been already dropped and writes are blocked by
* i_rwsem. So we can safely drop the i_data_sem here.
*/
BUG_ON(EXT4_JOURNAL(inode) == NULL);
ext4_discard_preallocations(inode, 0);
up_write(&EXT4_I(inode)->i_data_sem);
*dropped = 1;
return 0;
}
static void ext4_ext_drop_refs(struct ext4_ext_path *path)
{
int depth, i;
if (!path)
return;
depth = path->p_depth;
for (i = 0; i <= depth; i++, path++) {
brelse(path->p_bh);
path->p_bh = NULL;
}
}
void ext4_free_ext_path(struct ext4_ext_path *path)
{
ext4_ext_drop_refs(path);
kfree(path);
}
/*
* Make sure 'handle' has at least 'check_cred' credits. If not, restart
* transaction with 'restart_cred' credits. The function drops i_data_sem
* when restarting transaction and gets it after transaction is restarted.
*
* The function returns 0 on success, 1 if transaction had to be restarted,
* and < 0 in case of fatal error.
*/
int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,
int check_cred, int restart_cred,
int revoke_cred)
{
int ret;
int dropped = 0;
ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
if (dropped)
down_write(&EXT4_I(inode)->i_data_sem);
return ret;
}
/*
* could return:
* - EROFS
* - ENOMEM
*/
static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
int err = 0;
if (path->p_bh) {
/* path points to block */
BUFFER_TRACE(path->p_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb,
path->p_bh, EXT4_JTR_NONE);
/*
* The extent buffer's verified bit will be set again in
* __ext4_ext_dirty(). We could leave an inconsistent
* buffer if the extents updating procudure break off du
* to some error happens, force to check it again.
*/
if (!err)
clear_buffer_verified(path->p_bh);
}
/* path points to leaf/index in inode body */
/* we use in-core data, no need to protect them */
return err;
}
/*
* could return:
* - EROFS
* - ENOMEM
* - EIO
*/
static int __ext4_ext_dirty(const char *where, unsigned int line,
handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
int err;
WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
if (path->p_bh) {
ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
/* path points to block */
err = __ext4_handle_dirty_metadata(where, line, handle,
inode, path->p_bh);
/* Extents updating done, re-set verified flag */
if (!err)
set_buffer_verified(path->p_bh);
} else {
/* path points to leaf/index in inode body */
err = ext4_mark_inode_dirty(handle, inode);
}
return err;
}
#define ext4_ext_dirty(handle, inode, path) \
__ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t block)
{
if (path) {
int depth = path->p_depth;
struct ext4_extent *ex;
/*
* Try to predict block placement assuming that we are
* filling in a file which will eventually be
* non-sparse --- i.e., in the case of libbfd writing
* an ELF object sections out-of-order but in a way
* the eventually results in a contiguous object or
* executable file, or some database extending a table
* space file. However, this is actually somewhat
* non-ideal if we are writing a sparse file such as
* qemu or KVM writing a raw image file that is going
* to stay fairly sparse, since it will end up
* fragmenting the file system's free space. Maybe we
* should have some hueristics or some way to allow
* userspace to pass a hint to file system,
* especially if the latter case turns out to be
* common.
*/
ex = path[depth].p_ext;
if (ex) {
ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
if (block > ext_block)
return ext_pblk + (block - ext_block);
else
return ext_pblk - (ext_block - block);
}
/* it looks like index is empty;
* try to find starting block from index itself */
if (path[depth].p_bh)
return path[depth].p_bh->b_blocknr;
}
/* OK. use inode's group */
return ext4_inode_to_goal_block(inode);
}
/*
* Allocation for a meta data block
*/
static ext4_fsblk_t
ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex, int *err, unsigned int flags)
{
ext4_fsblk_t goal, newblock;
goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, err);
return newblock;
}
static inline int ext4_ext_space_block(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 6)
size = 6;
#endif
return size;
}
static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
{
int size;
size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 5)
size = 5;
#endif
return size;
}
static inline int ext4_ext_space_root(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent);
#ifdef AGGRESSIVE_TEST
if (!check && size > 3)
size = 3;
#endif
return size;
}
static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
{
int size;
size = sizeof(EXT4_I(inode)->i_data);
size -= sizeof(struct ext4_extent_header);
size /= sizeof(struct ext4_extent_idx);
#ifdef AGGRESSIVE_TEST
if (!check && size > 4)
size = 4;
#endif
return size;
}
static inline int
ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath, ext4_lblk_t lblk,
int nofail)
{
struct ext4_ext_path *path = *ppath;
int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
int flags = EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO;
if (nofail)
flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL | EXT4_EX_NOFAIL;
return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
flags);
}
static int
ext4_ext_max_entries(struct inode *inode, int depth)
{
int max;
if (depth == ext_depth(inode)) {
if (depth == 0)
max = ext4_ext_space_root(inode, 1);
else
max = ext4_ext_space_root_idx(inode, 1);
} else {
if (depth == 0)
max = ext4_ext_space_block(inode, 1);
else
max = ext4_ext_space_block_idx(inode, 1);
}
return max;
}
static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
{
ext4_fsblk_t block = ext4_ext_pblock(ext);
int len = ext4_ext_get_actual_len(ext);
ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
/*
* We allow neither:
* - zero length
* - overflow/wrap-around
*/
if (lblock + len <= lblock)
return 0;
return ext4_inode_block_valid(inode, block, len);
}
static int ext4_valid_extent_idx(struct inode *inode,
struct ext4_extent_idx *ext_idx)
{
ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
return ext4_inode_block_valid(inode, block, 1);
}
static int ext4_valid_extent_entries(struct inode *inode,
struct ext4_extent_header *eh,
ext4_lblk_t lblk, ext4_fsblk_t *pblk,
int depth)
{
unsigned short entries;
ext4_lblk_t lblock = 0;
ext4_lblk_t cur = 0;
if (eh->eh_entries == 0)
return 1;
entries = le16_to_cpu(eh->eh_entries);
if (depth == 0) {
/* leaf entries */
struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
/*
* The logical block in the first entry should equal to
* the number in the index block.
*/
if (depth != ext_depth(inode) &&
lblk != le32_to_cpu(ext->ee_block))
return 0;
while (entries) {
if (!ext4_valid_extent(inode, ext))
return 0;
/* Check for overlapping extents */
lblock = le32_to_cpu(ext->ee_block);
if (lblock < cur) {
*pblk = ext4_ext_pblock(ext);
return 0;
}
cur = lblock + ext4_ext_get_actual_len(ext);
ext++;
entries--;
}
} else {
struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
/*
* The logical block in the first entry should equal to
* the number in the parent index block.
*/
if (depth != ext_depth(inode) &&
lblk != le32_to_cpu(ext_idx->ei_block))
return 0;
while (entries) {
if (!ext4_valid_extent_idx(inode, ext_idx))
return 0;
/* Check for overlapping index extents */
lblock = le32_to_cpu(ext_idx->ei_block);
if (lblock < cur) {
*pblk = ext4_idx_pblock(ext_idx);
return 0;
}
ext_idx++;
entries--;
cur = lblock + 1;
}
}
return 1;
}
static int __ext4_ext_check(const char *function, unsigned int line,
struct inode *inode, struct ext4_extent_header *eh,
int depth, ext4_fsblk_t pblk, ext4_lblk_t lblk)
{
const char *error_msg;
int max = 0, err = -EFSCORRUPTED;
if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
error_msg = "invalid magic";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
error_msg = "unexpected eh_depth";
goto corrupted;
}
if (unlikely(eh->eh_max == 0)) {
error_msg = "invalid eh_max";
goto corrupted;
}
max = ext4_ext_max_entries(inode, depth);
if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
error_msg = "too large eh_max";
goto corrupted;
}
if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
error_msg = "invalid eh_entries";
goto corrupted;
}
if (unlikely((eh->eh_entries == 0) && (depth > 0))) {
error_msg = "eh_entries is 0 but eh_depth is > 0";
goto corrupted;
}
if (!ext4_valid_extent_entries(inode, eh, lblk, &pblk, depth)) {
error_msg = "invalid extent entries";
goto corrupted;
}
if (unlikely(depth > 32)) {
error_msg = "too large eh_depth";
goto corrupted;
}
/* Verify checksum on non-root extent tree nodes */
if (ext_depth(inode) != depth &&
!ext4_extent_block_csum_verify(inode, eh)) {
error_msg = "extent tree corrupted";
err = -EFSBADCRC;
goto corrupted;
}
return 0;
corrupted:
ext4_error_inode_err(inode, function, line, 0, -err,
"pblk %llu bad header/extent: %s - magic %x, "
"entries %u, max %u(%u), depth %u(%u)",
(unsigned long long) pblk, error_msg,
le16_to_cpu(eh->eh_magic),
le16_to_cpu(eh->eh_entries),
le16_to_cpu(eh->eh_max),
max, le16_to_cpu(eh->eh_depth), depth);
return err;
}
#define ext4_ext_check(inode, eh, depth, pblk) \
__ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk), 0)
int ext4_ext_check_inode(struct inode *inode)
{
return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
}
static void ext4_cache_extents(struct inode *inode,
struct ext4_extent_header *eh)
{
struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
ext4_lblk_t prev = 0;
int i;
for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
unsigned int status = EXTENT_STATUS_WRITTEN;
ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
int len = ext4_ext_get_actual_len(ex);
if (prev && (prev != lblk))
ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
EXTENT_STATUS_HOLE);
if (ext4_ext_is_unwritten(ex))
status = EXTENT_STATUS_UNWRITTEN;
ext4_es_cache_extent(inode, lblk, len,
ext4_ext_pblock(ex), status);
prev = lblk + len;
}
}
static struct buffer_head *
__read_extent_tree_block(const char *function, unsigned int line,
struct inode *inode, struct ext4_extent_idx *idx,
int depth, int flags)
{
struct buffer_head *bh;
int err;
gfp_t gfp_flags = __GFP_MOVABLE | GFP_NOFS;
ext4_fsblk_t pblk;
if (flags & EXT4_EX_NOFAIL)
gfp_flags |= __GFP_NOFAIL;
pblk = ext4_idx_pblock(idx);
bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags);
if (unlikely(!bh))
return ERR_PTR(-ENOMEM);
if (!bh_uptodate_or_lock(bh)) {
trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
err = ext4_read_bh(bh, 0, NULL);
if (err < 0)
goto errout;
}
if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
return bh;
err = __ext4_ext_check(function, line, inode, ext_block_hdr(bh),
depth, pblk, le32_to_cpu(idx->ei_block));
if (err)
goto errout;
set_buffer_verified(bh);
/*
* If this is a leaf block, cache all of its entries
*/
if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
struct ext4_extent_header *eh = ext_block_hdr(bh);
ext4_cache_extents(inode, eh);
}
return bh;
errout:
put_bh(bh);
return ERR_PTR(err);
}
#define read_extent_tree_block(inode, idx, depth, flags) \
__read_extent_tree_block(__func__, __LINE__, (inode), (idx), \
(depth), (flags))
/*
* This function is called to cache a file's extent information in the
* extent status tree
*/
int ext4_ext_precache(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_ext_path *path = NULL;
struct buffer_head *bh;
int i = 0, depth, ret = 0;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return 0; /* not an extent-mapped inode */
down_read(&ei->i_data_sem);
depth = ext_depth(inode);
/* Don't cache anything if there are no external extent blocks */
if (!depth) {
up_read(&ei->i_data_sem);
return ret;
}
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS);
if (path == NULL) {
up_read(&ei->i_data_sem);
return -ENOMEM;
}
path[0].p_hdr = ext_inode_hdr(inode);
ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
if (ret)
goto out;
path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
while (i >= 0) {
/*
* If this is a leaf block or we've reached the end of
* the index block, go up
*/
if ((i == depth) ||
path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
bh = read_extent_tree_block(inode, path[i].p_idx++,
depth - i - 1,
EXT4_EX_FORCE_CACHE);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
break;
}
i++;
path[i].p_bh = bh;
path[i].p_hdr = ext_block_hdr(bh);
path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
}
ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
out:
up_read(&ei->i_data_sem);
ext4_free_ext_path(path);
return ret;
}
#ifdef EXT_DEBUG
static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
{
int k, l = path->p_depth;
ext_debug(inode, "path:");
for (k = 0; k <= l; k++, path++) {
if (path->p_idx) {
ext_debug(inode, " %d->%llu",
le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
} else if (path->p_ext) {
ext_debug(inode, " %d:[%d]%d:%llu ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext),
ext4_ext_pblock(path->p_ext));
} else
ext_debug(inode, " []");
}
ext_debug(inode, "\n");
}
static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
{
int depth = ext_depth(inode);
struct ext4_extent_header *eh;
struct ext4_extent *ex;
int i;
if (!path)
return;
eh = path[depth].p_hdr;
ex = EXT_FIRST_EXTENT(eh);
ext_debug(inode, "Displaying leaf extents\n");
for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
ext_debug(inode, "%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
}
ext_debug(inode, "\n");
}
static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
ext4_fsblk_t newblock, int level)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
if (depth != level) {
struct ext4_extent_idx *idx;
idx = path[level].p_idx;
while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
ext_debug(inode, "%d: move %d:%llu in new index %llu\n",
level, le32_to_cpu(idx->ei_block),
ext4_idx_pblock(idx), newblock);
idx++;
}
return;
}
ex = path[depth].p_ext;
while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
ext_debug(inode, "move %d:%llu:[%d]%d in new leaf %llu\n",
le32_to_cpu(ex->ee_block),
ext4_ext_pblock(ex),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
newblock);
ex++;
}
}
#else
#define ext4_ext_show_path(inode, path)
#define ext4_ext_show_leaf(inode, path)
#define ext4_ext_show_move(inode, path, newblock, level)
#endif
/*
* ext4_ext_binsearch_idx:
* binary search for the closest index of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch_idx(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent_idx *r, *l, *m;
ext_debug(inode, "binsearch for %u(idx): ", block);
l = EXT_FIRST_INDEX(eh) + 1;
r = EXT_LAST_INDEX(eh);
while (l <= r) {
m = l + (r - l) / 2;
ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
le32_to_cpu(l->ei_block), m, le32_to_cpu(m->ei_block),
r, le32_to_cpu(r->ei_block));
if (block < le32_to_cpu(m->ei_block))
r = m - 1;
else
l = m + 1;
}
path->p_idx = l - 1;
ext_debug(inode, " -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
ext4_idx_pblock(path->p_idx));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent_idx *chix, *ix;
int k;
chix = ix = EXT_FIRST_INDEX(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
if (k != 0 && le32_to_cpu(ix->ei_block) <=
le32_to_cpu(ix[-1].ei_block)) {
printk(KERN_DEBUG "k=%d, ix=0x%p, "
"first=0x%p\n", k,
ix, EXT_FIRST_INDEX(eh));
printk(KERN_DEBUG "%u <= %u\n",
le32_to_cpu(ix->ei_block),
le32_to_cpu(ix[-1].ei_block));
}
BUG_ON(k && le32_to_cpu(ix->ei_block)
<= le32_to_cpu(ix[-1].ei_block));
if (block < le32_to_cpu(ix->ei_block))
break;
chix = ix;
}
BUG_ON(chix != path->p_idx);
}
#endif
}
/*
* ext4_ext_binsearch:
* binary search for closest extent of the given block
* the header must be checked before calling this
*/
static void
ext4_ext_binsearch(struct inode *inode,
struct ext4_ext_path *path, ext4_lblk_t block)
{
struct ext4_extent_header *eh = path->p_hdr;
struct ext4_extent *r, *l, *m;
if (eh->eh_entries == 0) {
/*
* this leaf is empty:
* we get such a leaf in split/add case
*/
return;
}
ext_debug(inode, "binsearch for %u: ", block);
l = EXT_FIRST_EXTENT(eh) + 1;
r = EXT_LAST_EXTENT(eh);
while (l <= r) {
m = l + (r - l) / 2;
ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
le32_to_cpu(l->ee_block), m, le32_to_cpu(m->ee_block),
r, le32_to_cpu(r->ee_block));
if (block < le32_to_cpu(m->ee_block))
r = m - 1;
else
l = m + 1;
}
path->p_ext = l - 1;
ext_debug(inode, " -> %d:%llu:[%d]%d ",
le32_to_cpu(path->p_ext->ee_block),
ext4_ext_pblock(path->p_ext),
ext4_ext_is_unwritten(path->p_ext),
ext4_ext_get_actual_len(path->p_ext));
#ifdef CHECK_BINSEARCH
{
struct ext4_extent *chex, *ex;
int k;
chex = ex = EXT_FIRST_EXTENT(eh);
for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
BUG_ON(k && le32_to_cpu(ex->ee_block)
<= le32_to_cpu(ex[-1].ee_block));
if (block < le32_to_cpu(ex->ee_block))
break;
chex = ex;
}
BUG_ON(chex != path->p_ext);
}
#endif
}
void ext4_ext_tree_init(handle_t *handle, struct inode *inode)
{
struct ext4_extent_header *eh;
eh = ext_inode_hdr(inode);
eh->eh_depth = 0;
eh->eh_entries = 0;
eh->eh_magic = EXT4_EXT_MAGIC;
eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
eh->eh_generation = 0;
ext4_mark_inode_dirty(handle, inode);
}
struct ext4_ext_path *
ext4_find_extent(struct inode *inode, ext4_lblk_t block,
struct ext4_ext_path **orig_path, int flags)
{
struct ext4_extent_header *eh;
struct buffer_head *bh;
struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
short int depth, i, ppos = 0;
int ret;
gfp_t gfp_flags = GFP_NOFS;
if (flags & EXT4_EX_NOFAIL)
gfp_flags |= __GFP_NOFAIL;
eh = ext_inode_hdr(inode);
depth = ext_depth(inode);
if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
depth);
ret = -EFSCORRUPTED;
goto err;
}
if (path) {
ext4_ext_drop_refs(path);
if (depth > path[0].p_maxdepth) {
kfree(path);
*orig_path = path = NULL;
}
}
if (!path) {
/* account possible depth increase */
path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
gfp_flags);
if (unlikely(!path))
return ERR_PTR(-ENOMEM);
path[0].p_maxdepth = depth + 1;
}
path[0].p_hdr = eh;
path[0].p_bh = NULL;
i = depth;
if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
ext4_cache_extents(inode, eh);
/* walk through the tree */
while (i) {
ext_debug(inode, "depth %d: num %d, max %d\n",
ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
ext4_ext_binsearch_idx(inode, path + ppos, block);
path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
bh = read_extent_tree_block(inode, path[ppos].p_idx, --i, flags);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
goto err;
}
eh = ext_block_hdr(bh);
ppos++;
path[ppos].p_bh = bh;
path[ppos].p_hdr = eh;
}
path[ppos].p_depth = i;
path[ppos].p_ext = NULL;
path[ppos].p_idx = NULL;
/* find extent */
ext4_ext_binsearch(inode, path + ppos, block);
/* if not an empty leaf */
if (path[ppos].p_ext)
path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
ext4_ext_show_path(inode, path);
return path;
err:
ext4_free_ext_path(path);
if (orig_path)
*orig_path = NULL;
return ERR_PTR(ret);
}
/*
* ext4_ext_insert_index:
* insert new index [@logical;@ptr] into the block at @curp;
* check where to insert: before @curp or after @curp
*/
static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
struct ext4_ext_path *curp,
int logical, ext4_fsblk_t ptr)
{
struct ext4_extent_idx *ix;
int len, err;
err = ext4_ext_get_access(handle, inode, curp);
if (err)
return err;
if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
EXT4_ERROR_INODE(inode,
"logical %d == ei_block %d!",
logical, le32_to_cpu(curp->p_idx->ei_block));
return -EFSCORRUPTED;
}
if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
>= le16_to_cpu(curp->p_hdr->eh_max))) {
EXT4_ERROR_INODE(inode,
"eh_entries %d >= eh_max %d!",
le16_to_cpu(curp->p_hdr->eh_entries),
le16_to_cpu(curp->p_hdr->eh_max));
return -EFSCORRUPTED;
}
if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
/* insert after */
ext_debug(inode, "insert new index %d after: %llu\n",
logical, ptr);
ix = curp->p_idx + 1;
} else {
/* insert before */
ext_debug(inode, "insert new index %d before: %llu\n",
logical, ptr);
ix = curp->p_idx;
}
len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
BUG_ON(len < 0);
if (len > 0) {
ext_debug(inode, "insert new index %d: "
"move %d indices from 0x%p to 0x%p\n",
logical, len, ix, ix + 1);
memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
}
if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
return -EFSCORRUPTED;
}
ix->ei_block = cpu_to_le32(logical);
ext4_idx_store_pblock(ix, ptr);
le16_add_cpu(&curp->p_hdr->eh_entries, 1);
if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
return -EFSCORRUPTED;
}
err = ext4_ext_dirty(handle, inode, curp);
ext4_std_error(inode->i_sb, err);
return err;
}
/*
* ext4_ext_split:
* inserts new subtree into the path, using free index entry
* at depth @at:
* - allocates all needed blocks (new leaf and all intermediate index blocks)
* - makes decision where to split
* - moves remaining extents and index entries (right to the split point)
* into the newly allocated blocks
* - initializes subtree
*/
static int ext4_ext_split(handle_t *handle, struct inode *inode,
unsigned int flags,
struct ext4_ext_path *path,
struct ext4_extent *newext, int at)
{
struct buffer_head *bh = NULL;
int depth = ext_depth(inode);
struct ext4_extent_header *neh;
struct ext4_extent_idx *fidx;
int i = at, k, m, a;
ext4_fsblk_t newblock, oldblock;
__le32 border;
ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
gfp_t gfp_flags = GFP_NOFS;
int err = 0;
size_t ext_size = 0;
if (flags & EXT4_EX_NOFAIL)
gfp_flags |= __GFP_NOFAIL;
/* make decision: where to split? */
/* FIXME: now decision is simplest: at current extent */
/* if current leaf will be split, then we should use
* border from split point */
if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
return -EFSCORRUPTED;
}
if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
border = path[depth].p_ext[1].ee_block;
ext_debug(inode, "leaf will be split."
" next leaf starts at %d\n",
le32_to_cpu(border));
} else {
border = newext->ee_block;
ext_debug(inode, "leaf will be added."
" next leaf starts at %d\n",
le32_to_cpu(border));
}
/*
* If error occurs, then we break processing
* and mark filesystem read-only. index won't
* be inserted and tree will be in consistent
* state. Next mount will repair buffers too.
*/
/*
* Get array to track all allocated blocks.
* We need this to handle errors and free blocks
* upon them.
*/
ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), gfp_flags);
if (!ablocks)
return -ENOMEM;
/* allocate all needed blocks */
ext_debug(inode, "allocate %d blocks for indexes/leaf\n", depth - at);
for (a = 0; a < depth - at; a++) {
newblock = ext4_ext_new_meta_block(handle, inode, path,
newext, &err, flags);
if (newblock == 0)
goto cleanup;
ablocks[a] = newblock;
}
/* initialize new leaf */
newblock = ablocks[--a];
if (unlikely(newblock == 0)) {
EXT4_ERROR_INODE(inode, "newblock == 0!");
err = -EFSCORRUPTED;
goto cleanup;
}
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = 0;
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_depth = 0;
neh->eh_generation = 0;
/* move remainder of path[depth] to the new leaf */
if (unlikely(path[depth].p_hdr->eh_entries !=
path[depth].p_hdr->eh_max)) {
EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
path[depth].p_hdr->eh_entries,
path[depth].p_hdr->eh_max);
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy from next extent */
m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
ext4_ext_show_move(inode, path, newblock, depth);
if (m) {
struct ext4_extent *ex;
ex = EXT_FIRST_EXTENT(neh);
memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old leaf */
if (m) {
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto cleanup;
}
/* create intermediate indexes */
k = depth - at - 1;
if (unlikely(k < 0)) {
EXT4_ERROR_INODE(inode, "k %d < 0!", k);
err = -EFSCORRUPTED;
goto cleanup;
}
if (k)
ext_debug(inode, "create %d intermediate indices\n", k);
/* insert new index into current index block */
/* current depth stored in i var */
i = depth - 1;
while (k--) {
oldblock = newblock;
newblock = ablocks[--a];
bh = sb_getblk(inode->i_sb, newblock);
if (unlikely(!bh)) {
err = -ENOMEM;
goto cleanup;
}
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (err)
goto cleanup;
neh = ext_block_hdr(bh);
neh->eh_entries = cpu_to_le16(1);
neh->eh_magic = EXT4_EXT_MAGIC;
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
neh->eh_depth = cpu_to_le16(depth - i);
neh->eh_generation = 0;
fidx = EXT_FIRST_INDEX(neh);
fidx->ei_block = border;
ext4_idx_store_pblock(fidx, oldblock);
ext_debug(inode, "int.index at %d (block %llu): %u -> %llu\n",
i, newblock, le32_to_cpu(border), oldblock);
/* move remainder of path[i] to the new index block */
if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
EXT_LAST_INDEX(path[i].p_hdr))) {
EXT4_ERROR_INODE(inode,
"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
le32_to_cpu(path[i].p_ext->ee_block));
err = -EFSCORRUPTED;
goto cleanup;
}
/* start copy indexes */
m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
ext_debug(inode, "cur 0x%p, last 0x%p\n", path[i].p_idx,
EXT_MAX_INDEX(path[i].p_hdr));
ext4_ext_show_move(inode, path, newblock, i);
if (m) {
memmove(++fidx, path[i].p_idx,
sizeof(struct ext4_extent_idx) * m);
le16_add_cpu(&neh->eh_entries, m);
}
/* zero out unused area in the extent block */
ext_size = sizeof(struct ext4_extent_header) +
(sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
memset(bh->b_data + ext_size, 0,
inode->i_sb->s_blocksize - ext_size);
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto cleanup;
brelse(bh);
bh = NULL;
/* correct old index */
if (m) {
err = ext4_ext_get_access(handle, inode, path + i);
if (err)
goto cleanup;
le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
err = ext4_ext_dirty(handle, inode, path + i);
if (err)
goto cleanup;
}
i--;
}
/* insert new index */
err = ext4_ext_insert_index(handle, inode, path + at,
le32_to_cpu(border), newblock);
cleanup:
if (bh) {
if (buffer_locked(bh))
unlock_buffer(bh);
brelse(bh);
}
if (err) {
/* free all allocated blocks in error case */
for (i = 0; i < depth; i++) {
if (!ablocks[i])
continue;
ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
EXT4_FREE_BLOCKS_METADATA);
}
}
kfree(ablocks);
return err;
}
/*
* ext4_ext_grow_indepth:
* implements tree growing procedure:
* - allocates new block
* - moves top-level data (index block or leaf) into the new block
* - initializes new top-level, creating index that points to the
* just created block
*/
static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
unsigned int flags)
{
struct ext4_extent_header *neh;
struct buffer_head *bh;
ext4_fsblk_t newblock, goal = 0;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
int err = 0;
size_t ext_size = 0;
/* Try to prepend new index to old one */
if (ext_depth(inode))
goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
if (goal > le32_to_cpu(es->s_first_data_block)) {
flags |= EXT4_MB_HINT_TRY_GOAL;
goal--;
} else
goal = ext4_inode_to_goal_block(inode);
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, &err);
if (newblock == 0)
return err;
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return -ENOMEM;
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (err) {
unlock_buffer(bh);
goto out;
}
ext_size = sizeof(EXT4_I(inode)->i_data);
/* move top-level index/leaf into new block */
memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
/* zero out unused area in the extent block */
memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
/* set size of new block */
neh = ext_block_hdr(bh);
/* old root could have indexes or leaves
* so calculate e_max right way */
if (ext_depth(inode))
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
else
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
set_buffer_verified(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto out;
/* Update top-level index: num,max,pointer */
neh = ext_inode_hdr(inode);
neh->eh_entries = cpu_to_le16(1);
ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
if (neh->eh_depth == 0) {
/* Root extent block becomes index block */
neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
EXT_FIRST_INDEX(neh)->ei_block =
EXT_FIRST_EXTENT(neh)->ee_block;
}
ext_debug(inode, "new root: num %d(%d), lblock %d, ptr %llu\n",
le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
le16_add_cpu(&neh->eh_depth, 1);
err = ext4_mark_inode_dirty(handle, inode);
out:
brelse(bh);
return err;
}
/*
* ext4_ext_create_new_leaf:
* finds empty index and adds new leaf.
* if no free index is found, then it requests in-depth growing.
*/
static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
unsigned int mb_flags,
unsigned int gb_flags,
struct ext4_ext_path **ppath,
struct ext4_extent *newext)
{
struct ext4_ext_path *path = *ppath;
struct ext4_ext_path *curp;
int depth, i, err = 0;
repeat:
i = depth = ext_depth(inode);
/* walk up to the tree and look for free index entry */
curp = path + depth;
while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
i--;
curp--;
}
/* we use already allocated block for index block,
* so subsequent data blocks should be contiguous */
if (EXT_HAS_FREE_INDEX(curp)) {
/* if we found index with free entry, then use that
* entry: create all needed subtree and add new leaf */
err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path))
err = PTR_ERR(path);
} else {
/* tree is full, time to grow in depth */
err = ext4_ext_grow_indepth(handle, inode, mb_flags);
if (err)
goto out;
/* refill path */
path = ext4_find_extent(inode,
(ext4_lblk_t)le32_to_cpu(newext->ee_block),
ppath, gb_flags);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
/*
* only first (depth 0 -> 1) produces free space;
* in all other cases we have to split the grown tree
*/
depth = ext_depth(inode);
if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
/* now we need to split */
goto repeat;
}
}
out:
return err;
}
/*
* search the closest allocated block to the left for *logical
* and returns it at @logical + it's physical address at @phys
* if *logical is the smallest allocated block, the function
* returns 0 at @phys
* return value contains 0 (success) or error code
*/
static int ext4_ext_search_left(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys)
{
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
int depth, ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
*logical, le32_to_cpu(ex->ee_block));
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block),
depth);
return -EFSCORRUPTED;
}
}
return 0;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
*phys = ext4_ext_pblock(ex) + ee_len - 1;
return 0;
}
/*
* Search the closest allocated block to the right for *logical
* and returns it at @logical + it's physical address at @phys.
* If not exists, return 0 and @phys is set to 0. We will return
* 1 which means we found an allocated block and ret_ex is valid.
* Or return a (< 0) error code.
*/
static int ext4_ext_search_right(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys,
struct ext4_extent *ret_ex)
{
struct buffer_head *bh = NULL;
struct ext4_extent_header *eh;
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
int depth; /* Note, NOT eh_depth; depth from top of tree */
int ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EFSCORRUPTED;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"first_extent(path[%d].p_hdr) != ex",
depth);
return -EFSCORRUPTED;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix != EXT_FIRST_INDEX *logical %d!",
*logical);
return -EFSCORRUPTED;
}
}
goto found_extent;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EFSCORRUPTED;
}
if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
/* next allocated block in this leaf */
ex++;
goto found_extent;
}
/* go up and search for index to the right */
while (--depth >= 0) {
ix = path[depth].p_idx;
if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
goto got_index;
}
/* we've gone up to the root and found no index to the right */
return 0;
got_index:
/* we've found index to the right, let's
* follow it and find the closest allocated
* block to the right */
ix++;
while (++depth < path->p_depth) {
/* subtract from p_depth to get proper eh_depth */
bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ix = EXT_FIRST_INDEX(eh);
put_bh(bh);
}
bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = ext_block_hdr(bh);
ex = EXT_FIRST_EXTENT(eh);
found_extent:
*logical = le32_to_cpu(ex->ee_block);
*phys = ext4_ext_pblock(ex);
if (ret_ex)
*ret_ex = *ex;
if (bh)
put_bh(bh);
return 1;
}
/*
* ext4_ext_next_allocated_block:
* returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
* NOTE: it considers block number from index entry as
* allocated block. Thus, index entries have to be consistent
* with leaves.
*/
ext4_lblk_t
ext4_ext_next_allocated_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
if (depth == 0 && path->p_ext == NULL)
return EXT_MAX_BLOCKS;
while (depth >= 0) {
struct ext4_ext_path *p = &path[depth];
if (depth == path->p_depth) {
/* leaf */
if (p->p_ext && p->p_ext != EXT_LAST_EXTENT(p->p_hdr))
return le32_to_cpu(p->p_ext[1].ee_block);
} else {
/* index */
if (p->p_idx != EXT_LAST_INDEX(p->p_hdr))
return le32_to_cpu(p->p_idx[1].ei_block);
}
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_next_leaf_block:
* returns first allocated block from next leaf or EXT_MAX_BLOCKS
*/
static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
/* zero-tree has no leaf blocks at all */
if (depth == 0)
return EXT_MAX_BLOCKS;
/* go to index block */
depth--;
while (depth >= 0) {
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return (ext4_lblk_t)
le32_to_cpu(path[depth].p_idx[1].ei_block);
depth--;
}
return EXT_MAX_BLOCKS;
}
/*
* ext4_ext_correct_indexes:
* if leaf gets modified and modified extent is first in the leaf,
* then we have to correct all indexes above.
* TODO: do we need to correct tree in all cases?
*/
static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent_header *eh;
int depth = ext_depth(inode);
struct ext4_extent *ex;
__le32 border;
int k, err = 0;
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
if (unlikely(ex == NULL || eh == NULL)) {
EXT4_ERROR_INODE(inode,
"ex %p == NULL or eh %p == NULL", ex, eh);
return -EFSCORRUPTED;
}
if (depth == 0) {
/* there is no tree at all */
return 0;
}
if (ex != EXT_FIRST_EXTENT(eh)) {
/* we correct tree if first leaf got modified only */
return 0;
}
/*
* TODO: we need correction if border is smaller than current one
*/
k = depth - 1;
border = path[depth].p_ext->ee_block;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
return err;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
return err;
while (k--) {
/* change all left-side indexes */
if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
break;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
break;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
break;
}
return err;
}
static int ext4_can_extents_be_merged(struct inode *inode,
struct ext4_extent *ex1,
struct ext4_extent *ex2)
{
unsigned short ext1_ee_len, ext2_ee_len;
if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
return 0;
ext1_ee_len = ext4_ext_get_actual_len(ex1);
ext2_ee_len = ext4_ext_get_actual_len(ex2);
if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
le32_to_cpu(ex2->ee_block))
return 0;
if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
return 0;
if (ext4_ext_is_unwritten(ex1) &&
ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
return 0;
#ifdef AGGRESSIVE_TEST
if (ext1_ee_len >= 4)
return 0;
#endif
if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
return 1;
return 0;
}
/*
* This function tries to merge the "ex" extent to the next extent in the tree.
* It always tries to merge towards right. If you want to merge towards
* left, pass "ex - 1" as argument instead of "ex".
* Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
* 1 if they got merged.
*/
static int ext4_ext_try_to_merge_right(struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex)
{
struct ext4_extent_header *eh;
unsigned int depth, len;
int merge_done = 0, unwritten;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
while (ex < EXT_LAST_EXTENT(eh)) {
if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
break;
/* merge with next extent! */
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(ex + 1));
if (unwritten)
ext4_ext_mark_unwritten(ex);
if (ex + 1 < EXT_LAST_EXTENT(eh)) {
len = (EXT_LAST_EXTENT(eh) - ex - 1)
* sizeof(struct ext4_extent);
memmove(ex + 1, ex + 2, len);
}
le16_add_cpu(&eh->eh_entries, -1);
merge_done = 1;
WARN_ON(eh->eh_entries == 0);
if (!eh->eh_entries)
EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
}
return merge_done;
}
/*
* This function does a very simple check to see if we can collapse
* an extent tree with a single extent tree leaf block into the inode.
*/
static void ext4_ext_try_to_merge_up(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path)
{
size_t s;
unsigned max_root = ext4_ext_space_root(inode, 0);
ext4_fsblk_t blk;
if ((path[0].p_depth != 1) ||
(le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
(le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
return;
/*
* We need to modify the block allocation bitmap and the block
* group descriptor to release the extent tree block. If we
* can't get the journal credits, give up.
*/
if (ext4_journal_extend(handle, 2,
ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
return;
/*
* Copy the extent data up to the inode
*/
blk = ext4_idx_pblock(path[0].p_idx);
s = le16_to_cpu(path[1].p_hdr->eh_entries) *
sizeof(struct ext4_extent_idx);
s += sizeof(struct ext4_extent_header);
path[1].p_maxdepth = path[0].p_maxdepth;
memcpy(path[0].p_hdr, path[1].p_hdr, s);
path[0].p_depth = 0;
path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
path[0].p_hdr->eh_max = cpu_to_le16(max_root);
brelse(path[1].p_bh);
ext4_free_blocks(handle, inode, NULL, blk, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
}
/*
* This function tries to merge the @ex extent to neighbours in the tree, then
* tries to collapse the extent tree into the inode.
*/
static void ext4_ext_try_to_merge(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *ex)
{
struct ext4_extent_header *eh;
unsigned int depth;
int merge_done = 0;
depth = ext_depth(inode);
BUG_ON(path[depth].p_hdr == NULL);
eh = path[depth].p_hdr;
if (ex > EXT_FIRST_EXTENT(eh))
merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
if (!merge_done)
(void) ext4_ext_try_to_merge_right(inode, path, ex);
ext4_ext_try_to_merge_up(handle, inode, path);
}
/*
* check if a portion of the "newext" extent overlaps with an
* existing extent.
*
* If there is an overlap discovered, it updates the length of the newext
* such that there will be no overlap, and then returns 1.
* If there is no overlap found, it returns 0.
*/
static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
struct inode *inode,
struct ext4_extent *newext,
struct ext4_ext_path *path)
{
ext4_lblk_t b1, b2;
unsigned int depth, len1;
unsigned int ret = 0;
b1 = le32_to_cpu(newext->ee_block);
len1 = ext4_ext_get_actual_len(newext);
depth = ext_depth(inode);
if (!path[depth].p_ext)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
/*
* get the next allocated block if the extent in the path
* is before the requested block(s)
*/
if (b2 < b1) {
b2 = ext4_ext_next_allocated_block(path);
if (b2 == EXT_MAX_BLOCKS)
goto out;
b2 = EXT4_LBLK_CMASK(sbi, b2);
}
/* check for wrap through zero on extent logical start block*/
if (b1 + len1 < b1) {
len1 = EXT_MAX_BLOCKS - b1;
newext->ee_len = cpu_to_le16(len1);
ret = 1;
}
/* check for overlap */
if (b1 + len1 > b2) {
newext->ee_len = cpu_to_le16(b2 - b1);
ret = 1;
}
out:
return ret;
}
/*
* ext4_ext_insert_extent:
* tries to merge requested extent into the existing extent or
* inserts requested extent as new one into the tree,
* creating new leaf in the no-space case.
*/
int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_extent *newext, int gb_flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
int mb_flags = 0, unwritten;
if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
mb_flags |= EXT4_MB_DELALLOC_RESERVED;
if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
return -EFSCORRUPTED;
}
depth = ext_depth(inode);
ex = path[depth].p_ext;
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* try to insert block into found extent and return */
if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
/*
* Try to see whether we should rather test the extent on
* right from ex, or from the left of ex. This is because
* ext4_find_extent() can return either extent on the
* left, or on the right from the searched position. This
* will make merging more effective.
*/
if (ex < EXT_LAST_EXTENT(eh) &&
(le32_to_cpu(ex->ee_block) +
ext4_ext_get_actual_len(ex) <
le32_to_cpu(newext->ee_block))) {
ex += 1;
goto prepend;
} else if ((ex > EXT_FIRST_EXTENT(eh)) &&
(le32_to_cpu(newext->ee_block) +
ext4_ext_get_actual_len(newext) <
le32_to_cpu(ex->ee_block)))
ex -= 1;
/* Try to append newex to the ex */
if (ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug(inode, "append [%d]%d block to %u:[%d]%d"
"(from %llu)\n",
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
nearex = ex;
goto merge;
}
prepend:
/* Try to prepend newex to the ex */
if (ext4_can_extents_be_merged(inode, newext, ex)) {
ext_debug(inode, "prepend %u[%d]%d block to %u:[%d]%d"
"(from %llu)\n",
le32_to_cpu(newext->ee_block),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_unwritten(ex),
ext4_ext_get_actual_len(ex),
ext4_ext_pblock(ex));
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
unwritten = ext4_ext_is_unwritten(ex);
ex->ee_block = newext->ee_block;
ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (unwritten)
ext4_ext_mark_unwritten(ex);
nearex = ex;
goto merge;
}
}
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = EXT_MAX_BLOCKS;
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
next = ext4_ext_next_leaf_block(path);
if (next != EXT_MAX_BLOCKS) {
ext_debug(inode, "next leaf block - %u\n", next);
BUG_ON(npath != NULL);
npath = ext4_find_extent(inode, next, NULL, gb_flags);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug(inode, "next leaf isn't full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto has_space;
}
ext_debug(inode, "next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
mb_flags |= EXT4_MB_USE_RESERVED;
err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
ppath, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug(inode, "first extent in the leaf: %u:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext));
nearex = EXT_FIRST_EXTENT(eh);
} else {
if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* Insert after */
ext_debug(inode, "insert %u:%llu:[%d]%d before: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
nearex++;
} else {
/* Insert before */
BUG_ON(newext->ee_block == nearex->ee_block);
ext_debug(inode, "insert %u:%llu:[%d]%d after: "
"nearest %p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
nearex);
}
len = EXT_LAST_EXTENT(eh) - nearex + 1;
if (len > 0) {
ext_debug(inode, "insert %u:%llu:[%d]%d: "
"move %d extents from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext4_ext_pblock(newext),
ext4_ext_is_unwritten(newext),
ext4_ext_get_actual_len(newext),
len, nearex, nearex + 1);
memmove(nearex + 1, nearex,
len * sizeof(struct ext4_extent));
}
}
le16_add_cpu(&eh->eh_entries, 1);
path[depth].p_ext = nearex;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents */
if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, nearex);
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
cleanup:
ext4_free_ext_path(npath);
return err;
}
static int ext4_fill_es_cache_info(struct inode *inode,
ext4_lblk_t block, ext4_lblk_t num,
struct fiemap_extent_info *fieinfo)
{
ext4_lblk_t next, end = block + num - 1;
struct extent_status es;
unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
unsigned int flags;
int err;
while (block <= end) {
next = 0;
flags = 0;
if (!ext4_es_lookup_extent(inode, block, &next, &es))
break;
if (ext4_es_is_unwritten(&es))
flags |= FIEMAP_EXTENT_UNWRITTEN;
if (ext4_es_is_delayed(&es))
flags |= (FIEMAP_EXTENT_DELALLOC |
FIEMAP_EXTENT_UNKNOWN);
if (ext4_es_is_hole(&es))
flags |= EXT4_FIEMAP_EXTENT_HOLE;
if (next == 0)
flags |= FIEMAP_EXTENT_LAST;
if (flags & (FIEMAP_EXTENT_DELALLOC|
EXT4_FIEMAP_EXTENT_HOLE))
es.es_pblk = 0;
else
es.es_pblk = ext4_es_pblock(&es);
err = fiemap_fill_next_extent(fieinfo,
(__u64)es.es_lblk << blksize_bits,
(__u64)es.es_pblk << blksize_bits,
(__u64)es.es_len << blksize_bits,
flags);
if (next == 0)
break;
block = next;
if (err < 0)
return err;
if (err == 1)
return 0;
}
return 0;
}
/*
* ext4_ext_determine_hole - determine hole around given block
* @inode: inode we lookup in
* @path: path in extent tree to @lblk
* @lblk: pointer to logical block around which we want to determine hole
*
* Determine hole length (and start if easily possible) around given logical
* block. We don't try too hard to find the beginning of the hole but @path
* actually points to extent before @lblk, we provide it.
*
* The function returns the length of a hole starting at @lblk. We update @lblk
* to the beginning of the hole if we managed to find it.
*/
static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *lblk)
{
int depth = ext_depth(inode);
struct ext4_extent *ex;
ext4_lblk_t len;
ex = path[depth].p_ext;
if (ex == NULL) {
/* there is no extent yet, so gap is [0;-] */
*lblk = 0;
len = EXT_MAX_BLOCKS;
} else if (*lblk < le32_to_cpu(ex->ee_block)) {
len = le32_to_cpu(ex->ee_block) - *lblk;
} else if (*lblk >= le32_to_cpu(ex->ee_block)
+ ext4_ext_get_actual_len(ex)) {
ext4_lblk_t next;
*lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
next = ext4_ext_next_allocated_block(path);
BUG_ON(next == *lblk);
len = next - *lblk;
} else {
BUG();
}
return len;
}
/*
* ext4_ext_put_gap_in_cache:
* calculate boundaries of the gap that the requested block fits into
* and cache this gap
*/
static void
ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
ext4_lblk_t hole_len)
{
struct extent_status es;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
hole_start + hole_len - 1, &es);
if (es.es_len) {
/* There's delayed extent containing lblock? */
if (es.es_lblk <= hole_start)
return;
hole_len = min(es.es_lblk - hole_start, hole_len);
}
ext_debug(inode, " -> %u:%u\n", hole_start, hole_len);
ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
EXTENT_STATUS_HOLE);
}
/*
* ext4_ext_rm_idx:
* removes index from the index block.
*/
static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path, int depth)
{
int err;
ext4_fsblk_t leaf;
/* free index block */
depth--;
path = path + depth;
leaf = ext4_idx_pblock(path->p_idx);
if (unlikely(path->p_hdr->eh_entries == 0)) {
EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
return -EFSCORRUPTED;
}
err = ext4_ext_get_access(handle, inode, path);
if (err)
return err;
if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
len *= sizeof(struct ext4_extent_idx);
memmove(path->p_idx, path->p_idx + 1, len);
}
le16_add_cpu(&path->p_hdr->eh_entries, -1);
err = ext4_ext_dirty(handle, inode, path);
if (err)
return err;
ext_debug(inode, "index is empty, remove it, free block %llu\n", leaf);
trace_ext4_ext_rm_idx(inode, leaf);
ext4_free_blocks(handle, inode, NULL, leaf, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
while (--depth >= 0) {
if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
break;
path--;
err = ext4_ext_get_access(handle, inode, path);
if (err)
break;
path->p_idx->ei_block = (path+1)->p_idx->ei_block;
err = ext4_ext_dirty(handle, inode, path);
if (err)
break;
}
return err;
}
/*
* ext4_ext_calc_credits_for_single_extent:
* This routine returns max. credits that needed to insert an extent
* to the extent tree.
* When pass the actual path, the caller should calculate credits
* under i_data_sem.
*/
int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
struct ext4_ext_path *path)
{
if (path) {
int depth = ext_depth(inode);
int ret = 0;
/* probably there is space in leaf? */
if (le16_to_cpu(path[depth].p_hdr->eh_entries)
< le16_to_cpu(path[depth].p_hdr->eh_max)) {
/*
* There are some space in the leaf tree, no
* need to account for leaf block credit
*
* bitmaps and block group descriptor blocks
* and other metadata blocks still need to be
* accounted.
*/
/* 1 bitmap, 1 block group descriptor */
ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
return ret;
}
}
return ext4_chunk_trans_blocks(inode, nrblocks);
}
/*
* How many index/leaf blocks need to change/allocate to add @extents extents?
*
* If we add a single extent, then in the worse case, each tree level
* index/leaf need to be changed in case of the tree split.
*
* If more extents are inserted, they could cause the whole tree split more
* than once, but this is really rare.
*/
int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
{
int index;
int depth;
/* If we are converting the inline data, only one is needed here. */
if (ext4_has_inline_data(inode))
return 1;
depth = ext_depth(inode);
if (extents <= 1)
index = depth * 2;
else
index = depth * 3;
return index;
}
static inline int get_default_free_blocks_flags(struct inode *inode)
{
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
else if (ext4_should_journal_data(inode))
return EXT4_FREE_BLOCKS_FORGET;
return 0;
}
/*
* ext4_rereserve_cluster - increment the reserved cluster count when
* freeing a cluster with a pending reservation
*
* @inode - file containing the cluster
* @lblk - logical block in cluster to be reserved
*
* Increments the reserved cluster count and adjusts quota in a bigalloc
* file system when freeing a partial cluster containing at least one
* delayed and unwritten block. A partial cluster meeting that
* requirement will have a pending reservation. If so, the
* RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
* defer reserved and allocated space accounting to a subsequent call
* to this function.
*/
static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
spin_lock(&ei->i_block_reservation_lock);
ei->i_reserved_data_blocks++;
percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
spin_unlock(&ei->i_block_reservation_lock);
percpu_counter_add(&sbi->s_freeclusters_counter, 1);
ext4_remove_pending(inode, lblk);
}
static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
struct ext4_extent *ex,
struct partial_cluster *partial,
ext4_lblk_t from, ext4_lblk_t to)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
ext4_fsblk_t last_pblk, pblk;
ext4_lblk_t num;
int flags;
/* only extent tail removal is allowed */
if (from < le32_to_cpu(ex->ee_block) ||
to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
ext4_error(sbi->s_sb,
"strange request: removal(2) %u-%u from %u:%u",
from, to, le32_to_cpu(ex->ee_block), ee_len);
return 0;
}
#ifdef EXTENTS_STATS
spin_lock(&sbi->s_ext_stats_lock);
sbi->s_ext_blocks += ee_len;
sbi->s_ext_extents++;
if (ee_len < sbi->s_ext_min)
sbi->s_ext_min = ee_len;
if (ee_len > sbi->s_ext_max)
sbi->s_ext_max = ee_len;
if (ext_depth(inode) > sbi->s_depth_max)
sbi->s_depth_max = ext_depth(inode);
spin_unlock(&sbi->s_ext_stats_lock);
#endif
trace_ext4_remove_blocks(inode, ex, from, to, partial);
/*
* if we have a partial cluster, and it's different from the
* cluster of the last block in the extent, we free it
*/
last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
if (partial->state != initial &&
partial->pclu != EXT4_B2C(sbi, last_pblk)) {
if (partial->state == tofree) {
flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
num = le32_to_cpu(ex->ee_block) + ee_len - from;
pblk = ext4_ext_pblock(ex) + ee_len - num;
/*
* We free the partial cluster at the end of the extent (if any),
* unless the cluster is used by another extent (partial_cluster
* state is nofree). If a partial cluster exists here, it must be
* shared with the last block in the extent.
*/
flags = get_default_free_blocks_flags(inode);
/* partial, left end cluster aligned, right end unaligned */
if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
(EXT4_LBLK_CMASK(sbi, to) >= from) &&
(partial->state != nofree)) {
if (ext4_is_pending(inode, to))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_PBLK_CMASK(sbi, last_pblk),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, to);
partial->state = initial;
flags = get_default_free_blocks_flags(inode);
}
flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
/*
* For bigalloc file systems, we never free a partial cluster
* at the beginning of the extent. Instead, we check to see if we
* need to free it on a subsequent call to ext4_remove_blocks,
* or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
*/
flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
/* reset the partial cluster if we've freed past it */
if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
partial->state = initial;
/*
* If we've freed the entire extent but the beginning is not left
* cluster aligned and is not marked as ineligible for freeing we
* record the partial cluster at the beginning of the extent. It
* wasn't freed by the preceding ext4_free_blocks() call, and we
* need to look farther to the left to determine if it's to be freed
* (not shared with another extent). Else, reset the partial
* cluster - we're either done freeing or the beginning of the
* extent is left cluster aligned.
*/
if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
if (partial->state == initial) {
partial->pclu = EXT4_B2C(sbi, pblk);
partial->lblk = from;
partial->state = tofree;
}
} else {
partial->state = initial;
}
return 0;
}
/*
* ext4_ext_rm_leaf() Removes the extents associated with the
* blocks appearing between "start" and "end". Both "start"
* and "end" must appear in the same extent or EIO is returned.
*
* @handle: The journal handle
* @inode: The files inode
* @path: The path to the leaf
* @partial_cluster: The cluster which we'll have to free if all extents
* has been released from it. However, if this value is
* negative, it's a cluster just to the right of the
* punched region and it must not be freed.
* @start: The first block to remove
* @end: The last block to remove
*/
static int
ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct partial_cluster *partial,
ext4_lblk_t start, ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int err = 0, correct_index = 0;
int depth = ext_depth(inode), credits, revoke_credits;
struct ext4_extent_header *eh;
ext4_lblk_t a, b;
unsigned num;
ext4_lblk_t ex_ee_block;
unsigned short ex_ee_len;
unsigned unwritten = 0;
struct ext4_extent *ex;
ext4_fsblk_t pblk;
/* the header must be checked already in ext4_ext_remove_space() */
ext_debug(inode, "truncate since %u in leaf to %u\n", start, end);
if (!path[depth].p_hdr)
path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
eh = path[depth].p_hdr;
if (unlikely(path[depth].p_hdr == NULL)) {
EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
return -EFSCORRUPTED;
}
/* find where to start removing */
ex = path[depth].p_ext;
if (!ex)
ex = EXT_LAST_EXTENT(eh);
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_rm_leaf(inode, start, ex, partial);
while (ex >= EXT_FIRST_EXTENT(eh) &&
ex_ee_block + ex_ee_len > start) {
if (ext4_ext_is_unwritten(ex))
unwritten = 1;
else
unwritten = 0;
ext_debug(inode, "remove ext %u:[%d]%d\n", ex_ee_block,
unwritten, ex_ee_len);
path[depth].p_ext = ex;
a = max(ex_ee_block, start);
b = min(ex_ee_block + ex_ee_len - 1, end);
ext_debug(inode, " border %u:%u\n", a, b);
/* If this extent is beyond the end of the hole, skip it */
if (end < ex_ee_block) {
/*
* We're going to skip this extent and move to another,
* so note that its first cluster is in use to avoid
* freeing it when removing blocks. Eventually, the
* right edge of the truncated/punched region will
* be just to the left.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex);
partial->pclu = EXT4_B2C(sbi, pblk);
partial->state = nofree;
}
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
continue;
} else if (b != ex_ee_block + ex_ee_len - 1) {
EXT4_ERROR_INODE(inode,
"can not handle truncate %u:%u "
"on extent %u:%u",
start, end, ex_ee_block,
ex_ee_block + ex_ee_len - 1);
err = -EFSCORRUPTED;
goto out;
} else if (a != ex_ee_block) {
/* remove tail of the extent */
num = a - ex_ee_block;
} else {
/* remove whole extent: excellent! */
num = 0;
}
/*
* 3 for leaf, sb, and inode plus 2 (bmap and group
* descriptor) for each block group; assume two block
* groups plus ex_ee_len/blocks_per_block_group for
* the worst case
*/
credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
if (ex == EXT_FIRST_EXTENT(eh)) {
correct_index = 1;
credits += (ext_depth(inode)) + 1;
}
credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
/*
* We may end up freeing some index blocks and data from the
* punched range. Note that partial clusters are accounted for
* by ext4_free_data_revoke_credits().
*/
revoke_credits =
ext4_free_metadata_revoke_credits(inode->i_sb,
ext_depth(inode)) +
ext4_free_data_revoke_credits(inode, b - a + 1);
err = ext4_datasem_ensure_credits(handle, inode, credits,
credits, revoke_credits);
if (err) {
if (err > 0)
err = -EAGAIN;
goto out;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
if (err)
goto out;
if (num == 0)
/* this extent is removed; mark slot entirely unused */
ext4_ext_store_pblock(ex, 0);
ex->ee_len = cpu_to_le16(num);
/*
* Do not mark unwritten if all the blocks in the
* extent have been removed.
*/
if (unwritten && num)
ext4_ext_mark_unwritten(ex);
/*
* If the extent was completely released,
* we need to remove it from the leaf
*/
if (num == 0) {
if (end != EXT_MAX_BLOCKS - 1) {
/*
* For hole punching, we need to scoot all the
* extents up when an extent is removed so that
* we dont have blank extents in the middle
*/
memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
sizeof(struct ext4_extent));
/* Now get rid of the one at the end */
memset(EXT_LAST_EXTENT(eh), 0,
sizeof(struct ext4_extent));
}
le16_add_cpu(&eh->eh_entries, -1);
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
ext_debug(inode, "new extent: %u:%u:%llu\n", ex_ee_block, num,
ext4_ext_pblock(ex));
ex--;
ex_ee_block = le32_to_cpu(ex->ee_block);
ex_ee_len = ext4_ext_get_actual_len(ex);
}
if (correct_index && eh->eh_entries)
err = ext4_ext_correct_indexes(handle, inode, path);
/*
* If there's a partial cluster and at least one extent remains in
* the leaf, free the partial cluster if it isn't shared with the
* current extent. If it is shared with the current extent
* we reset the partial cluster because we've reached the start of the
* truncated/punched region and we're done removing blocks.
*/
if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
if (partial->pclu != EXT4_B2C(sbi, pblk)) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial->lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial->pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial->lblk);
}
partial->state = initial;
}
/* if this leaf is free, then we should
* remove it from index block above */
if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
err = ext4_ext_rm_idx(handle, inode, path, depth);
out:
return err;
}
/*
* ext4_ext_more_to_rm:
* returns 1 if current index has to be freed (even partial)
*/
static int
ext4_ext_more_to_rm(struct ext4_ext_path *path)
{
BUG_ON(path->p_idx == NULL);
if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
return 0;
/*
* if truncate on deeper level happened, it wasn't partial,
* so we have to consider current index for truncation
*/
if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
return 0;
return 1;
}
int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
ext4_lblk_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int depth = ext_depth(inode);
struct ext4_ext_path *path = NULL;
struct partial_cluster partial;
handle_t *handle;
int i = 0, err = 0;
partial.pclu = 0;
partial.lblk = 0;
partial.state = initial;
ext_debug(inode, "truncate since %u to %u\n", start, end);
/* probably first extent we're gonna free will be last in block */
handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
depth + 1,
ext4_free_metadata_revoke_credits(inode->i_sb, depth));
if (IS_ERR(handle))
return PTR_ERR(handle);
again:
trace_ext4_ext_remove_space(inode, start, end, depth);
/*
* Check if we are removing extents inside the extent tree. If that
* is the case, we are going to punch a hole inside the extent tree
* so we have to check whether we need to split the extent covering
* the last block to remove so we can easily remove the part of it
* in ext4_ext_rm_leaf().
*/
if (end < EXT_MAX_BLOCKS - 1) {
struct ext4_extent *ex;
ext4_lblk_t ee_block, ex_end, lblk;
ext4_fsblk_t pblk;
/* find extent for or closest extent to this block */
path = ext4_find_extent(inode, end, NULL,
EXT4_EX_NOCACHE | EXT4_EX_NOFAIL);
if (IS_ERR(path)) {
ext4_journal_stop(handle);
return PTR_ERR(path);
}
depth = ext_depth(inode);
/* Leaf not may not exist only if inode has no blocks at all */
ex = path[depth].p_ext;
if (!ex) {
if (depth) {
EXT4_ERROR_INODE(inode,
"path[%d].p_hdr == NULL",
depth);
err = -EFSCORRUPTED;
}
goto out;
}
ee_block = le32_to_cpu(ex->ee_block);
ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
/*
* See if the last block is inside the extent, if so split
* the extent at 'end' block so we can easily remove the
* tail of the first part of the split extent in
* ext4_ext_rm_leaf().
*/
if (end >= ee_block && end < ex_end) {
/*
* If we're going to split the extent, note that
* the cluster containing the block after 'end' is
* in use to avoid freeing it when removing blocks.
*/
if (sbi->s_cluster_ratio > 1) {
pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
/*
* Split the extent in two so that 'end' is the last
* block in the first new extent. Also we should not
* fail removing space due to ENOSPC so try to use
* reserved block if that happens.
*/
err = ext4_force_split_extent_at(handle, inode, &path,
end + 1, 1);
if (err < 0)
goto out;
} else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
partial.state == initial) {
/*
* If we're punching, there's an extent to the right.
* If the partial cluster hasn't been set, set it to
* that extent's first cluster and its state to nofree
* so it won't be freed should it contain blocks to be
* removed. If it's already set (tofree/nofree), we're
* retrying and keep the original partial cluster info
* so a cluster marked tofree as a result of earlier
* extent removal is not lost.
*/
lblk = ex_end + 1;
err = ext4_ext_search_right(inode, path, &lblk, &pblk,
NULL);
if (err < 0)
goto out;
if (pblk) {
partial.pclu = EXT4_B2C(sbi, pblk);
partial.state = nofree;
}
}
}
/*
* We start scanning from right side, freeing all the blocks
* after i_size and walking into the tree depth-wise.
*/
depth = ext_depth(inode);
if (path) {
int k = i = depth;
while (--k > 0)
path[k].p_block =
le16_to_cpu(path[k].p_hdr->eh_entries)+1;
} else {
path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
GFP_NOFS | __GFP_NOFAIL);
if (path == NULL) {
ext4_journal_stop(handle);
return -ENOMEM;
}
path[0].p_maxdepth = path[0].p_depth = depth;
path[0].p_hdr = ext_inode_hdr(inode);
i = 0;
if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
err = -EFSCORRUPTED;
goto out;
}
}
err = 0;
while (i >= 0 && err == 0) {
if (i == depth) {
/* this is leaf block */
err = ext4_ext_rm_leaf(handle, inode, path,
&partial, start, end);
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
continue;
}
/* this is index block */
if (!path[i].p_hdr) {
ext_debug(inode, "initialize header\n");
path[i].p_hdr = ext_block_hdr(path[i].p_bh);
}
if (!path[i].p_idx) {
/* this level hasn't been touched yet */
path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
ext_debug(inode, "init index ptr: hdr 0x%p, num %d\n",
path[i].p_hdr,
le16_to_cpu(path[i].p_hdr->eh_entries));
} else {
/* we were already here, see at next index */
path[i].p_idx--;
}
ext_debug(inode, "level %d - index, first 0x%p, cur 0x%p\n",
i, EXT_FIRST_INDEX(path[i].p_hdr),
path[i].p_idx);
if (ext4_ext_more_to_rm(path + i)) {
struct buffer_head *bh;
/* go to the next level */
ext_debug(inode, "move to level %d (block %llu)\n",
i + 1, ext4_idx_pblock(path[i].p_idx));
memset(path + i + 1, 0, sizeof(*path));
bh = read_extent_tree_block(inode, path[i].p_idx,
depth - i - 1,
EXT4_EX_NOCACHE);
if (IS_ERR(bh)) {
/* should we reset i_size? */
err = PTR_ERR(bh);
break;
}
/* Yield here to deal with large extent trees.
* Should be a no-op if we did IO above. */
cond_resched();
if (WARN_ON(i + 1 > depth)) {
err = -EFSCORRUPTED;
break;
}
path[i + 1].p_bh = bh;
/* save actual number of indexes since this
* number is changed at the next iteration */
path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
i++;
} else {
/* we finished processing this index, go up */
if (path[i].p_hdr->eh_entries == 0 && i > 0) {
/* index is empty, remove it;
* handle must be already prepared by the
* truncatei_leaf() */
err = ext4_ext_rm_idx(handle, inode, path, i);
}
/* root level has p_bh == NULL, brelse() eats this */
brelse(path[i].p_bh);
path[i].p_bh = NULL;
i--;
ext_debug(inode, "return to level %d\n", i);
}
}
trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
path->p_hdr->eh_entries);
/*
* if there's a partial cluster and we have removed the first extent
* in the file, then we also free the partial cluster, if any
*/
if (partial.state == tofree && err == 0) {
int flags = get_default_free_blocks_flags(inode);
if (ext4_is_pending(inode, partial.lblk))
flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
ext4_free_blocks(handle, inode, NULL,
EXT4_C2B(sbi, partial.pclu),
sbi->s_cluster_ratio, flags);
if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
ext4_rereserve_cluster(inode, partial.lblk);
partial.state = initial;
}
/* TODO: flexible tree reduction should be here */
if (path->p_hdr->eh_entries == 0) {
/*
* truncate to zero freed all the tree,
* so we need to correct eh_depth
*/
err = ext4_ext_get_access(handle, inode, path);
if (err == 0) {
ext_inode_hdr(inode)->eh_depth = 0;
ext_inode_hdr(inode)->eh_max =
cpu_to_le16(ext4_ext_space_root(inode, 0));
err = ext4_ext_dirty(handle, inode, path);
}
}
out:
ext4_free_ext_path(path);
path = NULL;
if (err == -EAGAIN)
goto again;
ext4_journal_stop(handle);
return err;
}
/*
* called at mount time
*/
void ext4_ext_init(struct super_block *sb)
{
/*
* possible initialization would be here
*/
if (ext4_has_feature_extents(sb)) {
#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
printk(KERN_INFO "EXT4-fs: file extents enabled"
#ifdef AGGRESSIVE_TEST
", aggressive tests"
#endif
#ifdef CHECK_BINSEARCH
", check binsearch"
#endif
#ifdef EXTENTS_STATS
", stats"
#endif
"\n");
#endif
#ifdef EXTENTS_STATS
spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
EXT4_SB(sb)->s_ext_min = 1 << 30;
EXT4_SB(sb)->s_ext_max = 0;
#endif
}
}
/*
* called at umount time
*/
void ext4_ext_release(struct super_block *sb)
{
if (!ext4_has_feature_extents(sb))
return;
#ifdef EXTENTS_STATS
if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
struct ext4_sb_info *sbi = EXT4_SB(sb);
printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
sbi->s_ext_blocks, sbi->s_ext_extents,
sbi->s_ext_blocks / sbi->s_ext_extents);
printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
}
#endif
}
static void ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
{
ext4_lblk_t ee_block;
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
if (ee_len == 0)
return;
ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
EXTENT_STATUS_WRITTEN);
}
/* FIXME!! we need to try to merge to left or right after zero-out */
static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
{
ext4_fsblk_t ee_pblock;
unsigned int ee_len;
ee_len = ext4_ext_get_actual_len(ex);
ee_pblock = ext4_ext_pblock(ex);
return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
ee_len);
}
/*
* ext4_split_extent_at() splits an extent at given block.
*
* @handle: the journal handle
* @inode: the file inode
* @path: the path to the extent
* @split: the logical block where the extent is splitted.
* @split_flags: indicates if the extent could be zeroout if split fails, and
* the states(init or unwritten) of new extents.
* @flags: flags used to insert new extent to extent tree.
*
*
* Splits extent [a, b] into two extents [a, @split) and [@split, b], states
* of which are determined by split_flag.
*
* There are two cases:
* a> the extent are splitted into two extent.
* b> split is not needed, and just mark the extent.
*
* return 0 on success.
*/
static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
ext4_lblk_t split,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_fsblk_t newblock;
ext4_lblk_t ee_block;
struct ext4_extent *ex, newex, orig_ex, zero_ex;
struct ext4_extent *ex2 = NULL;
unsigned int ee_len, depth;
int err = 0;
BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
(EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
ext_debug(inode, "logical block %llu\n", (unsigned long long)split);
ext4_ext_show_leaf(inode, path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
newblock = split - ee_block + ext4_ext_pblock(ex);
BUG_ON(split < ee_block || split >= (ee_block + ee_len));
BUG_ON(!ext4_ext_is_unwritten(ex) &&
split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (split == ee_block) {
/*
* case b: block @split is the block that the extent begins with
* then we just change the state of the extent, and splitting
* is not needed.
*/
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex);
else
ext4_ext_mark_initialized(ex);
if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
}
/* case a */
memcpy(&orig_ex, ex, sizeof(orig_ex));
ex->ee_len = cpu_to_le16(split - ee_block);
if (split_flag & EXT4_EXT_MARK_UNWRIT1)
ext4_ext_mark_unwritten(ex);
/*
* path may lead to new leaf, not to original leaf any more
* after ext4_ext_insert_extent() returns,
*/
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto fix_extent_len;
ex2 = &newex;
ex2->ee_block = cpu_to_le32(split);
ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
ext4_ext_store_pblock(ex2, newblock);
if (split_flag & EXT4_EXT_MARK_UNWRIT2)
ext4_ext_mark_unwritten(ex2);
err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
if (err != -ENOSPC && err != -EDQUOT && err != -ENOMEM)
goto out;
if (EXT4_EXT_MAY_ZEROOUT & split_flag) {
if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
if (split_flag & EXT4_EXT_DATA_VALID1) {
err = ext4_ext_zeroout(inode, ex2);
zero_ex.ee_block = ex2->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex2));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex2));
} else {
err = ext4_ext_zeroout(inode, ex);
zero_ex.ee_block = ex->ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex));
}
} else {
err = ext4_ext_zeroout(inode, &orig_ex);
zero_ex.ee_block = orig_ex.ee_block;
zero_ex.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(&orig_ex));
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(&orig_ex));
}
if (!err) {
/* update the extent length and mark as initialized */
ex->ee_len = cpu_to_le16(ee_len);
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (!err)
/* update extent status tree */
ext4_zeroout_es(inode, &zero_ex);
/* If we failed at this point, we don't know in which
* state the extent tree exactly is so don't try to fix
* length of the original extent as it may do even more
* damage.
*/
goto out;
}
}
fix_extent_len:
ex->ee_len = orig_ex.ee_len;
/*
* Ignore ext4_ext_dirty return value since we are already in error path
* and err is a non-zero error code.
*/
ext4_ext_dirty(handle, inode, path + path->p_depth);
return err;
out:
ext4_ext_show_leaf(inode, path);
return err;
}
/*
* ext4_split_extents() splits an extent and mark extent which is covered
* by @map as split_flags indicates
*
* It may result in splitting the extent into multiple extents (up to three)
* There are three possibilities:
* a> There is no split required
* b> Splits in two extents: Split is happening at either end of the extent
* c> Splits in three extents: Somone is splitting in middle of the extent
*
*/
static int ext4_split_extent(handle_t *handle,
struct inode *inode,
struct ext4_ext_path **ppath,
struct ext4_map_blocks *map,
int split_flag,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len, depth;
int err = 0;
int unwritten;
int split_flag1, flags1;
int allocated = map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
unwritten = ext4_ext_is_unwritten(ex);
if (map->m_lblk + map->m_len < ee_block + ee_len) {
split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
if (unwritten)
split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
if (split_flag & EXT4_EXT_DATA_VALID2)
split_flag1 |= EXT4_EXT_DATA_VALID1;
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk + map->m_len, split_flag1, flags1);
if (err)
goto out;
} else {
allocated = ee_len - (map->m_lblk - ee_block);
}
/*
* Update path is required because previous ext4_split_extent_at() may
* result in split of original leaf or extent zeroout.
*/
path = ext4_find_extent(inode, map->m_lblk, ppath, flags);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
unwritten = ext4_ext_is_unwritten(ex);
if (map->m_lblk >= ee_block) {
split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
if (unwritten) {
split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
EXT4_EXT_MARK_UNWRIT2);
}
err = ext4_split_extent_at(handle, inode, ppath,
map->m_lblk, split_flag1, flags);
if (err)
goto out;
}
ext4_ext_show_leaf(inode, path);
out:
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() if someone tries to write
* to an unwritten extent. It may result in splitting the unwritten
* extent into multiple extents (up to three - one initialized and two
* unwritten).
* There are three possibilities:
* a> There is no split required: Entire extent should be initialized
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* Pre-conditions:
* - The extent pointed to by 'path' is unwritten.
* - The extent pointed to by 'path' contains a superset
* of the logical span [map->m_lblk, map->m_lblk + map->m_len).
*
* Post-conditions on success:
* - the returned value is the number of blocks beyond map->l_lblk
* that are allocated and initialized.
* It is guaranteed to be >= map->m_len.
*/
static int ext4_ext_convert_to_initialized(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
struct ext4_sb_info *sbi;
struct ext4_extent_header *eh;
struct ext4_map_blocks split_map;
struct ext4_extent zero_ex1, zero_ex2;
struct ext4_extent *ex, *abut_ex;
ext4_lblk_t ee_block, eof_block;
unsigned int ee_len, depth, map_len = map->m_len;
int allocated = 0, max_zeroout = 0;
int err = 0;
int split_flag = EXT4_EXT_DATA_VALID2;
ext_debug(inode, "logical block %llu, max_blocks %u\n",
(unsigned long long)map->m_lblk, map_len);
sbi = EXT4_SB(inode->i_sb);
eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
>> inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map_len)
eof_block = map->m_lblk + map_len;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
zero_ex1.ee_len = 0;
zero_ex2.ee_len = 0;
trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
/* Pre-conditions */
BUG_ON(!ext4_ext_is_unwritten(ex));
BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
/*
* Attempt to transfer newly initialized blocks from the currently
* unwritten extent to its neighbor. This is much cheaper
* than an insertion followed by a merge as those involve costly
* memmove() calls. Transferring to the left is the common case in
* steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
* followed by append writes.
*
* Limitations of the current logic:
* - L1: we do not deal with writes covering the whole extent.
* This would require removing the extent if the transfer
* is possible.
* - L2: we only attempt to merge with an extent stored in the
* same extent tree node.
*/
if ((map->m_lblk == ee_block) &&
/* See if we can merge left */
(map_len < ee_len) && /*L1*/
(ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
ext4_lblk_t prev_lblk;
ext4_fsblk_t prev_pblk, ee_pblk;
unsigned int prev_len;
abut_ex = ex - 1;
prev_lblk = le32_to_cpu(abut_ex->ee_block);
prev_len = ext4_ext_get_actual_len(abut_ex);
prev_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((prev_lblk + prev_len) == ee_block) && /*C2*/
((prev_pblk + prev_len) == ee_pblk) && /*C3*/
(prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of ex by 'map_len' blocks */
ex->ee_block = cpu_to_le32(ee_block + map_len);
ext4_ext_store_pblock(ex, ee_pblk + map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
} else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
(map_len < ee_len) && /*L1*/
ex < EXT_LAST_EXTENT(eh)) { /*L2*/
/* See if we can merge right */
ext4_lblk_t next_lblk;
ext4_fsblk_t next_pblk, ee_pblk;
unsigned int next_len;
abut_ex = ex + 1;
next_lblk = le32_to_cpu(abut_ex->ee_block);
next_len = ext4_ext_get_actual_len(abut_ex);
next_pblk = ext4_ext_pblock(abut_ex);
ee_pblk = ext4_ext_pblock(ex);
/*
* A transfer of blocks from 'ex' to 'abut_ex' is allowed
* upon those conditions:
* - C1: abut_ex is initialized,
* - C2: abut_ex is logically abutting ex,
* - C3: abut_ex is physically abutting ex,
* - C4: abut_ex can receive the additional blocks without
* overflowing the (initialized) length limit.
*/
if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
((map->m_lblk + map_len) == next_lblk) && /*C2*/
((ee_pblk + ee_len) == next_pblk) && /*C3*/
(next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
trace_ext4_ext_convert_to_initialized_fastpath(inode,
map, ex, abut_ex);
/* Shift the start of abut_ex by 'map_len' blocks */
abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
ex->ee_len = cpu_to_le16(ee_len - map_len);
ext4_ext_mark_unwritten(ex); /* Restore the flag */
/* Extend abut_ex by 'map_len' blocks */
abut_ex->ee_len = cpu_to_le16(next_len + map_len);
/* Result: number of initialized blocks past m_lblk */
allocated = map_len;
}
}
if (allocated) {
/* Mark the block containing both extents as dirty */
err = ext4_ext_dirty(handle, inode, path + depth);
/* Update path to point to the right extent */
path[depth].p_ext = abut_ex;
goto out;
} else
allocated = ee_len - (map->m_lblk - ee_block);
WARN_ON(map->m_lblk < ee_block);
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully inside i_size or new_size.
*/
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
if (EXT4_EXT_MAY_ZEROOUT & split_flag)
max_zeroout = sbi->s_extent_max_zeroout_kb >>
(inode->i_sb->s_blocksize_bits - 10);
/*
* five cases:
* 1. split the extent into three extents.
* 2. split the extent into two extents, zeroout the head of the first
* extent.
* 3. split the extent into two extents, zeroout the tail of the second
* extent.
* 4. split the extent into two extents with out zeroout.
* 5. no splitting needed, just possibly zeroout the head and / or the
* tail of the extent.
*/
split_map.m_lblk = map->m_lblk;
split_map.m_len = map->m_len;
if (max_zeroout && (allocated > split_map.m_len)) {
if (allocated <= max_zeroout) {
/* case 3 or 5 */
zero_ex1.ee_block =
cpu_to_le32(split_map.m_lblk +
split_map.m_len);
zero_ex1.ee_len =
cpu_to_le16(allocated - split_map.m_len);
ext4_ext_store_pblock(&zero_ex1,
ext4_ext_pblock(ex) + split_map.m_lblk +
split_map.m_len - ee_block);
err = ext4_ext_zeroout(inode, &zero_ex1);
if (err)
goto fallback;
split_map.m_len = allocated;
}
if (split_map.m_lblk - ee_block + split_map.m_len <
max_zeroout) {
/* case 2 or 5 */
if (split_map.m_lblk != ee_block) {
zero_ex2.ee_block = ex->ee_block;
zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
ee_block);
ext4_ext_store_pblock(&zero_ex2,
ext4_ext_pblock(ex));
err = ext4_ext_zeroout(inode, &zero_ex2);
if (err)
goto fallback;
}
split_map.m_len += split_map.m_lblk - ee_block;
split_map.m_lblk = ee_block;
allocated = map->m_len;
}
}
fallback:
err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
flags);
if (err > 0)
err = 0;
out:
/* If we have gotten a failure, don't zero out status tree */
if (!err) {
ext4_zeroout_es(inode, &zero_ex1);
ext4_zeroout_es(inode, &zero_ex2);
}
return err ? err : allocated;
}
/*
* This function is called by ext4_ext_map_blocks() from
* ext4_get_blocks_dio_write() when DIO to write
* to an unwritten extent.
*
* Writing to an unwritten extent may result in splitting the unwritten
* extent into multiple initialized/unwritten extents (up to three)
* There are three possibilities:
* a> There is no split required: Entire extent should be unwritten
* b> Splits in two extents: Write is happening at either end of the extent
* c> Splits in three extents: Somone is writing in middle of the extent
*
* This works the same way in the case of initialized -> unwritten conversion.
*
* One of more index blocks maybe needed if the extent tree grow after
* the unwritten extent split. To prevent ENOSPC occur at the IO
* complete, we need to split the unwritten extent before DIO submit
* the IO. The unwritten extent called at this time will be split
* into three unwritten extent(at most). After IO complete, the part
* being filled will be convert to initialized by the end_io callback function
* via ext4_convert_unwritten_extents().
*
* Returns the size of unwritten extent to be written on success.
*/
static int ext4_split_convert_extents(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
int flags)
{
struct ext4_ext_path *path = *ppath;
ext4_lblk_t eof_block;
ext4_lblk_t ee_block;
struct ext4_extent *ex;
unsigned int ee_len;
int split_flag = 0, depth;
ext_debug(inode, "logical block %llu, max_blocks %u\n",
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
>> inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully inside i_size or new_size.
*/
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
/* Convert to unwritten */
if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
split_flag |= EXT4_EXT_DATA_VALID1;
/* Convert to initialized */
} else if (flags & EXT4_GET_BLOCKS_CONVERT) {
split_flag |= ee_block + ee_len <= eof_block ?
EXT4_EXT_MAY_ZEROOUT : 0;
split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
}
flags |= EXT4_GET_BLOCKS_PRE_IO;
return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
}
static int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug(inode, "logical block %llu, max_blocks %u\n",
(unsigned long long)ee_block, ee_len);
/* If extent is larger than requested it is a clear sign that we still
* have some extent state machine issues left. So extent_split is still
* required.
* TODO: Once all related issues will be fixed this situation should be
* illegal.
*/
if (ee_block != map->m_lblk || ee_len > map->m_len) {
#ifdef CONFIG_EXT4_DEBUG
ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
" len %u; IO logical block %llu, len %u",
inode->i_ino, (unsigned long long)ee_block, ee_len,
(unsigned long long)map->m_lblk, map->m_len);
#endif
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
static int
convert_initialized_extent(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath,
unsigned int *allocated)
{
struct ext4_ext_path *path = *ppath;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
/*
* Make sure that the extent is no bigger than we support with
* unwritten extent
*/
if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug(inode, "logical block %llu, max_blocks %u\n",
(unsigned long long)ee_block, ee_len);
if (ee_block != map->m_lblk || ee_len > map->m_len) {
err = ext4_split_convert_extents(handle, inode, map, ppath,
EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
if (err < 0)
return err;
path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
if (IS_ERR(path))
return PTR_ERR(path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (!ex) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) map->m_lblk);
return -EFSCORRUPTED;
}
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/* first mark the extent as unwritten */
ext4_ext_mark_unwritten(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
if (err)
return err;
ext4_ext_show_leaf(inode, path);
ext4_update_inode_fsync_trans(handle, inode, 1);
map->m_flags |= EXT4_MAP_UNWRITTEN;
if (*allocated > map->m_len)
*allocated = map->m_len;
map->m_len = *allocated;
return 0;
}
static int
ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path **ppath, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
struct ext4_ext_path __maybe_unused *path = *ppath;
int ret = 0;
int err = 0;
ext_debug(inode, "logical block %llu, max_blocks %u, flags 0x%x, allocated %u\n",
(unsigned long long)map->m_lblk, map->m_len, flags,
allocated);
ext4_ext_show_leaf(inode, path);
/*
* When writing into unwritten space, we should not fail to
* allocate metadata blocks for the new extent block if needed.
*/
flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
allocated, newblock);
/* get_block() before submitting IO, split the extent */
if (flags & EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_convert_extents(handle, inode, map, ppath,
flags | EXT4_GET_BLOCKS_CONVERT);
if (ret < 0) {
err = ret;
goto out2;
}
/*
* shouldn't get a 0 return when splitting an extent unless
* m_len is 0 (bug) or extent has been corrupted
*/
if (unlikely(ret == 0)) {
EXT4_ERROR_INODE(inode,
"unexpected ret == 0, m_len = %u",
map->m_len);
err = -EFSCORRUPTED;
goto out2;
}
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if (flags & EXT4_GET_BLOCKS_CONVERT) {
err = ext4_convert_unwritten_extents_endio(handle, inode, map,
ppath);
if (err < 0)
goto out2;
ext4_update_inode_fsync_trans(handle, inode, 1);
goto map_out;
}
/* buffered IO cases */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto map_out;
}
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/*
* Default case when (flags & EXT4_GET_BLOCKS_CREATE) == 1.
* For buffered writes, at writepage time, etc. Convert a
* discovered unwritten extent to written.
*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
if (ret < 0) {
err = ret;
goto out2;
}
ext4_update_inode_fsync_trans(handle, inode, 1);
/*
* shouldn't get a 0 return when converting an unwritten extent
* unless m_len is 0 (bug) or extent has been corrupted
*/
if (unlikely(ret == 0)) {
EXT4_ERROR_INODE(inode, "unexpected ret == 0, m_len = %u",
map->m_len);
err = -EFSCORRUPTED;
goto out2;
}
out:
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
out1:
map->m_pblk = newblock;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
ext4_ext_show_leaf(inode, path);
out2:
return err ? err : allocated;
}
/*
* get_implied_cluster_alloc - check to see if the requested
* allocation (in the map structure) overlaps with a cluster already
* allocated in an extent.
* @sb The filesystem superblock structure
* @map The requested lblk->pblk mapping
* @ex The extent structure which might contain an implied
* cluster allocation
*
* This function is called by ext4_ext_map_blocks() after we failed to
* find blocks that were already in the inode's extent tree. Hence,
* we know that the beginning of the requested region cannot overlap
* the extent from the inode's extent tree. There are three cases we
* want to catch. The first is this case:
*
* |--- cluster # N--|
* |--- extent ---| |---- requested region ---|
* |==========|
*
* The second case that we need to test for is this one:
*
* |--------- cluster # N ----------------|
* |--- requested region --| |------- extent ----|
* |=======================|
*
* The third case is when the requested region lies between two extents
* within the same cluster:
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*
* In each of the above cases, we need to set the map->m_pblk and
* map->m_len so it corresponds to the return the extent labelled as
* "|====|" from cluster #N, since it is already in use for data in
* cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
* signal to ext4_ext_map_blocks() that map->m_pblk should be treated
* as a new "allocated" block region. Otherwise, we will return 0 and
* ext4_ext_map_blocks() will then allocate one or more new clusters
* by calling ext4_mb_new_blocks().
*/
static int get_implied_cluster_alloc(struct super_block *sb,
struct ext4_map_blocks *map,
struct ext4_extent *ex,
struct ext4_ext_path *path)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ext4_lblk_t ex_cluster_start, ex_cluster_end;
ext4_lblk_t rr_cluster_start;
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len = ext4_ext_get_actual_len(ex);
/* The extent passed in that we are trying to match */
ex_cluster_start = EXT4_B2C(sbi, ee_block);
ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
/* The requested region passed into ext4_map_blocks() */
rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
if ((rr_cluster_start == ex_cluster_end) ||
(rr_cluster_start == ex_cluster_start)) {
if (rr_cluster_start == ex_cluster_end)
ee_start += ee_len - 1;
map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
map->m_len = min(map->m_len,
(unsigned) sbi->s_cluster_ratio - c_offset);
/*
* Check for and handle this case:
*
* |--------- cluster # N-------------|
* |------- extent ----|
* |--- requested region ---|
* |===========|
*/
if (map->m_lblk < ee_block)
map->m_len = min(map->m_len, ee_block - map->m_lblk);
/*
* Check for the case where there is already another allocated
* block to the right of 'ex' but before the end of the cluster.
*
* |------------- cluster # N-------------|
* |----- ex -----| |---- ex_right ----|
* |------ requested region ------|
* |================|
*/
if (map->m_lblk > ee_block) {
ext4_lblk_t next = ext4_ext_next_allocated_block(path);
map->m_len = min(map->m_len, next - map->m_lblk);
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
return 1;
}
trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
return 0;
}
/*
* Block allocation/map/preallocation routine for extents based files
*
*
* Need to be called with
* down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
* (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
*
* return > 0, number of blocks already mapped/allocated
* if create == 0 and these are pre-allocated blocks
* buffer head is unmapped
* otherwise blocks are mapped
*
* return = 0, if plain look up failed (blocks have not been allocated)
* buffer head is unmapped
*
* return < 0, error case.
*/
int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent newex, *ex, ex2;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_fsblk_t newblock = 0, pblk;
int err = 0, depth, ret;
unsigned int allocated = 0, offset = 0;
unsigned int allocated_clusters = 0;
struct ext4_allocation_request ar;
ext4_lblk_t cluster_offset;
ext_debug(inode, "blocks %u/%u requested\n", map->m_lblk, map->m_len);
trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
/* find extent for this block */
path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out;
}
depth = ext_depth(inode);
/*
* consistent leaf must not be empty;
* this situation is possible, though, _during_ tree modification;
* this is why assert can't be put in ext4_find_extent()
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode, "bad extent address "
"lblock: %lu, depth: %d pblock %lld",
(unsigned long) map->m_lblk, depth,
path[depth].p_block);
err = -EFSCORRUPTED;
goto out;
}
ex = path[depth].p_ext;
if (ex) {
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len;
/*
* unwritten extents are treated as holes, except that
* we split out initialized portions during a write.
*/
ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
/* if found extent covers block, simply return it */
if (in_range(map->m_lblk, ee_block, ee_len)) {
newblock = map->m_lblk - ee_block + ee_start;
/* number of remaining blocks in the extent */
allocated = ee_len - (map->m_lblk - ee_block);
ext_debug(inode, "%u fit into %u:%d -> %llu\n",
map->m_lblk, ee_block, ee_len, newblock);
/*
* If the extent is initialized check whether the
* caller wants to convert it to unwritten.
*/
if ((!ext4_ext_is_unwritten(ex)) &&
(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
err = convert_initialized_extent(handle,
inode, map, &path, &allocated);
goto out;
} else if (!ext4_ext_is_unwritten(ex)) {
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
if (allocated > map->m_len)
allocated = map->m_len;
map->m_len = allocated;
ext4_ext_show_leaf(inode, path);
goto out;
}
ret = ext4_ext_handle_unwritten_extents(
handle, inode, map, &path, flags,
allocated, newblock);
if (ret < 0)
err = ret;
else
allocated = ret;
goto out;
}
}
/*
* requested block isn't allocated yet;
* we couldn't try to create block if create flag is zero
*/
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
ext4_lblk_t hole_start, hole_len;
hole_start = map->m_lblk;
hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
/*
* put just found gap into cache to speed up
* subsequent requests
*/
ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
/* Update hole_len to reflect hole size after map->m_lblk */
if (hole_start != map->m_lblk)
hole_len -= map->m_lblk - hole_start;
map->m_pblk = 0;
map->m_len = min_t(unsigned int, map->m_len, hole_len);
goto out;
}
/*
* Okay, we need to do block allocation.
*/
newex.ee_block = cpu_to_le32(map->m_lblk);
cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
/*
* If we are doing bigalloc, check to see if the extent returned
* by ext4_find_extent() implies a cluster we can use.
*/
if (cluster_offset && ex &&
get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
goto got_allocated_blocks;
}
/* find neighbour allocated blocks */
ar.lleft = map->m_lblk;
err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
if (err)
goto out;
ar.lright = map->m_lblk;
err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
if (err < 0)
goto out;
/* Check if the extent after searching to the right implies a
* cluster we can use. */
if ((sbi->s_cluster_ratio > 1) && err &&
get_implied_cluster_alloc(inode->i_sb, map, &ex2, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
goto got_allocated_blocks;
}
/*
* See if request is beyond maximum number of blocks we can have in
* a single extent. For an initialized extent this limit is
* EXT_INIT_MAX_LEN and for an unwritten extent this limit is
* EXT_UNWRITTEN_MAX_LEN.
*/
if (map->m_len > EXT_INIT_MAX_LEN &&
!(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_INIT_MAX_LEN;
else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_UNWRITTEN_MAX_LEN;
/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
newex.ee_len = cpu_to_le16(map->m_len);
err = ext4_ext_check_overlap(sbi, inode, &newex, path);
if (err)
allocated = ext4_ext_get_actual_len(&newex);
else
allocated = map->m_len;
/* allocate new block */
ar.inode = inode;
ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
ar.logical = map->m_lblk;
/*
* We calculate the offset from the beginning of the cluster
* for the logical block number, since when we allocate a
* physical cluster, the physical block should start at the
* same offset from the beginning of the cluster. This is
* needed so that future calls to get_implied_cluster_alloc()
* work correctly.
*/
offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
ar.goal -= offset;
ar.logical -= offset;
if (S_ISREG(inode->i_mode))
ar.flags = EXT4_MB_HINT_DATA;
else
/* disable in-core preallocation for non-regular files */
ar.flags = 0;
if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
ar.flags |= EXT4_MB_HINT_NOPREALLOC;
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ar.flags |= EXT4_MB_DELALLOC_RESERVED;
if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
ar.flags |= EXT4_MB_USE_RESERVED;
newblock = ext4_mb_new_blocks(handle, &ar, &err);
if (!newblock)
goto out;
allocated_clusters = ar.len;
ar.len = EXT4_C2B(sbi, ar.len) - offset;
ext_debug(inode, "allocate new block: goal %llu, found %llu/%u, requested %u\n",
ar.goal, newblock, ar.len, allocated);
if (ar.len > allocated)
ar.len = allocated;
got_allocated_blocks:
/* try to insert new extent into found leaf and return */
pblk = newblock + offset;
ext4_ext_store_pblock(&newex, pblk);
newex.ee_len = cpu_to_le16(ar.len);
/* Mark unwritten */
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
ext4_ext_mark_unwritten(&newex);
map->m_flags |= EXT4_MAP_UNWRITTEN;
}
err = ext4_ext_insert_extent(handle, inode, &path, &newex, flags);
if (err) {
if (allocated_clusters) {
int fb_flags = 0;
/*
* free data blocks we just allocated.
* not a good idea to call discard here directly,
* but otherwise we'd need to call it every free().
*/
ext4_discard_preallocations(inode, 0);
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
fb_flags = EXT4_FREE_BLOCKS_NO_QUOT_UPDATE;
ext4_free_blocks(handle, inode, NULL, newblock,
EXT4_C2B(sbi, allocated_clusters),
fb_flags);
}
goto out;
}
/*
* Reduce the reserved cluster count to reflect successful deferred
* allocation of delayed allocated clusters or direct allocation of
* clusters discovered to be delayed allocated. Once allocated, a
* cluster is not included in the reserved count.
*/
if (test_opt(inode->i_sb, DELALLOC) && allocated_clusters) {
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
/*
* When allocating delayed allocated clusters, simply
* reduce the reserved cluster count and claim quota
*/
ext4_da_update_reserve_space(inode, allocated_clusters,
1);
} else {
ext4_lblk_t lblk, len;
unsigned int n;
/*
* When allocating non-delayed allocated clusters
* (from fallocate, filemap, DIO, or clusters
* allocated when delalloc has been disabled by
* ext4_nonda_switch), reduce the reserved cluster
* count by the number of allocated clusters that
* have previously been delayed allocated. Quota
* has been claimed by ext4_mb_new_blocks() above,
* so release the quota reservations made for any
* previously delayed allocated clusters.
*/
lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
len = allocated_clusters << sbi->s_cluster_bits;
n = ext4_es_delayed_clu(inode, lblk, len);
if (n > 0)
ext4_da_update_reserve_space(inode, (int) n, 0);
}
}
/*
* Cache the extent and update transaction to commit on fdatasync only
* when it is _not_ an unwritten extent.
*/
if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
else
ext4_update_inode_fsync_trans(handle, inode, 0);
map->m_flags |= (EXT4_MAP_NEW | EXT4_MAP_MAPPED);
map->m_pblk = pblk;
map->m_len = ar.len;
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
out:
ext4_free_ext_path(path);
trace_ext4_ext_map_blocks_exit(inode, flags, map,
err ? err : allocated);
return err ? err : allocated;
}
int ext4_ext_truncate(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t last_block;
int err = 0;
/*
* TODO: optimization is possible here.
* Probably we need not scan at all,
* because page truncation is enough.
*/
/* we have to know where to truncate from in crash case */
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_mark_inode_dirty(handle, inode);
if (err)
return err;
last_block = (inode->i_size + sb->s_blocksize - 1)
>> EXT4_BLOCK_SIZE_BITS(sb);
ext4_es_remove_extent(inode, last_block, EXT_MAX_BLOCKS - last_block);
retry_remove_space:
err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
if (err == -ENOMEM) {
memalloc_retry_wait(GFP_ATOMIC);
goto retry_remove_space;
}
return err;
}
static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
ext4_lblk_t len, loff_t new_size,
int flags)
{
struct inode *inode = file_inode(file);
handle_t *handle;
int ret = 0, ret2 = 0, ret3 = 0;
int retries = 0;
int depth = 0;
struct ext4_map_blocks map;
unsigned int credits;
loff_t epos;
BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
map.m_lblk = offset;
map.m_len = len;
/*
* Don't normalize the request if it can fit in one extent so
* that it doesn't get unnecessarily split into multiple
* extents.
*/
if (len <= EXT_UNWRITTEN_MAX_LEN)
flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
retry:
while (len) {
/*
* Recalculate credits when extent tree depth changes.
*/
if (depth != ext_depth(inode)) {
credits = ext4_chunk_trans_blocks(inode, len);
depth = ext_depth(inode);
}
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
ret = ext4_map_blocks(handle, inode, &map, flags);
if (ret <= 0) {
ext4_debug("inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
break;
}
/*
* allow a full retry cycle for any remaining allocations
*/
retries = 0;
map.m_lblk += ret;
map.m_len = len = len - ret;
epos = (loff_t)map.m_lblk << inode->i_blkbits;
inode_set_ctime_current(inode);
if (new_size) {
if (epos > new_size)
epos = new_size;
if (ext4_update_inode_size(inode, epos) & 0x1)
inode->i_mtime = inode_get_ctime(inode);
}
ret2 = ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
ret3 = ext4_journal_stop(handle);
ret2 = ret3 ? ret3 : ret2;
if (unlikely(ret2))
break;
}
if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return ret > 0 ? ret2 : ret;
}
static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len);
static int ext4_insert_range(struct file *file, loff_t offset, loff_t len);
static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
struct address_space *mapping = file->f_mapping;
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
/*
* Round up offset. This is not fallocate, we need to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
inode_lock(inode);
/*
* Indirect files do not support unwritten extents
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > inode->i_size ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
/* Wait all existing dio workers, newcomers will block on i_rwsem */
inode_dio_wait(inode);
ret = file_modified(file);
if (ret)
goto out_mutex;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/*
* Prevent page faults from reinstantiating pages we have
* released from page cache.
*/
filemap_invalidate_lock(mapping);
ret = ext4_break_layouts(inode);
if (ret) {
filemap_invalidate_unlock(mapping);
goto out_mutex;
}
ret = ext4_update_disksize_before_punch(inode, offset, len);
if (ret) {
filemap_invalidate_unlock(mapping);
goto out_mutex;
}
/*
* For journalled data we need to write (and checkpoint) pages
* before discarding page cache to avoid inconsitent data on
* disk in case of crash before zeroing trans is committed.
*/
if (ext4_should_journal_data(inode)) {
ret = filemap_write_and_wait_range(mapping, start, end);
if (ret) {
filemap_invalidate_unlock(mapping);
goto out_mutex;
}
}
/* Now release the pages and zero block aligned part of pages */
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode_set_ctime_current(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags);
filemap_invalidate_unlock(mapping);
if (ret)
goto out_mutex;
}
if (!partial_begin && !partial_end)
goto out_mutex;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_mutex;
}
inode->i_mtime = inode_set_ctime_current(inode);
if (new_size)
ext4_update_inode_size(inode, new_size);
ret = ext4_mark_inode_dirty(handle, inode);
if (unlikely(ret))
goto out_handle;
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
out_handle:
ext4_journal_stop(handle);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* preallocate space for a file. This implements ext4's fallocate file
* operation, which gets called from sys_fallocate system call.
* For block-mapped files, posix_fallocate should fall back to the method
* of writing zeroes to the required new blocks (the same behavior which is
* expected for file systems which do not support fallocate() system call).
*/
long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
loff_t new_size = 0;
unsigned int max_blocks;
int ret = 0;
int flags;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
/*
* Encrypted inodes can't handle collapse range or insert
* range since we would need to re-encrypt blocks with a
* different IV or XTS tweak (which are based on the logical
* block number).
*/
if (IS_ENCRYPTED(inode) &&
(mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
return -EOPNOTSUPP;
/* Return error if mode is not supported */
if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
FALLOC_FL_INSERT_RANGE))
return -EOPNOTSUPP;
inode_lock(inode);
ret = ext4_convert_inline_data(inode);
inode_unlock(inode);
if (ret)
goto exit;
if (mode & FALLOC_FL_PUNCH_HOLE) {
ret = ext4_punch_hole(file, offset, len);
goto exit;
}
if (mode & FALLOC_FL_COLLAPSE_RANGE) {
ret = ext4_collapse_range(file, offset, len);
goto exit;
}
if (mode & FALLOC_FL_INSERT_RANGE) {
ret = ext4_insert_range(file, offset, len);
goto exit;
}
if (mode & FALLOC_FL_ZERO_RANGE) {
ret = ext4_zero_range(file, offset, len, mode);
goto exit;
}
trace_ext4_fallocate_enter(inode, offset, len, mode);
lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
inode_lock(inode);
/*
* We only support preallocation for extent-based files only
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(offset + len > inode->i_size ||
offset + len > EXT4_I(inode)->i_disksize)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out;
}
/* Wait all existing dio workers, newcomers will block on i_rwsem */
inode_dio_wait(inode);
ret = file_modified(file);
if (ret)
goto out;
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
if (ret)
goto out;
if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
ret = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
EXT4_I(inode)->i_sync_tid);
}
out:
inode_unlock(inode);
trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
exit:
return ret;
}
/*
* This function convert a range of blocks to written extents
* The caller of this function will pass the start offset and the size.
* all unwritten extents within this range will be converted to
* written extents.
*
* This function is called from the direct IO end io call back
* function, to convert the fallocated extents after IO is completed.
* Returns 0 on success.
*/
int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
loff_t offset, ssize_t len)
{
unsigned int max_blocks;
int ret = 0, ret2 = 0, ret3 = 0;
struct ext4_map_blocks map;
unsigned int blkbits = inode->i_blkbits;
unsigned int credits = 0;
map.m_lblk = offset >> blkbits;
max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
if (!handle) {
/*
* credits to insert 1 extent into extent tree
*/
credits = ext4_chunk_trans_blocks(inode, max_blocks);
}
while (ret >= 0 && ret < max_blocks) {
map.m_lblk += ret;
map.m_len = (max_blocks -= ret);
if (credits) {
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
break;
}
}
ret = ext4_map_blocks(handle, inode, &map,
EXT4_GET_BLOCKS_IO_CONVERT_EXT);
if (ret <= 0)
ext4_warning(inode->i_sb,
"inode #%lu: block %u: len %u: "
"ext4_ext_map_blocks returned %d",
inode->i_ino, map.m_lblk,
map.m_len, ret);
ret2 = ext4_mark_inode_dirty(handle, inode);
if (credits) {
ret3 = ext4_journal_stop(handle);
if (unlikely(ret3))
ret2 = ret3;
}
if (ret <= 0 || ret2)
break;
}
return ret > 0 ? ret2 : ret;
}
int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
{
int ret = 0, err = 0;
struct ext4_io_end_vec *io_end_vec;
/*
* This is somewhat ugly but the idea is clear: When transaction is
* reserved, everything goes into it. Otherwise we rather start several
* smaller transactions for conversion of each extent separately.
*/
if (handle) {
handle = ext4_journal_start_reserved(handle,
EXT4_HT_EXT_CONVERT);
if (IS_ERR(handle))
return PTR_ERR(handle);
}
list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
ret = ext4_convert_unwritten_extents(handle, io_end->inode,
io_end_vec->offset,
io_end_vec->size);
if (ret)
break;
}
if (handle)
err = ext4_journal_stop(handle);
return ret < 0 ? ret : err;
}
static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap)
{
__u64 physical = 0;
__u64 length = 0;
int blockbits = inode->i_sb->s_blocksize_bits;
int error = 0;
u16 iomap_type;
/* in-inode? */
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
struct ext4_iloc iloc;
int offset; /* offset of xattr in inode */
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
physical = (__u64)iloc.bh->b_blocknr << blockbits;
offset = EXT4_GOOD_OLD_INODE_SIZE +
EXT4_I(inode)->i_extra_isize;
physical += offset;
length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
brelse(iloc.bh);
iomap_type = IOMAP_INLINE;
} else if (EXT4_I(inode)->i_file_acl) { /* external block */
physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
length = inode->i_sb->s_blocksize;
iomap_type = IOMAP_MAPPED;
} else {
/* no in-inode or external block for xattr, so return -ENOENT */
error = -ENOENT;
goto out;
}
iomap->addr = physical;
iomap->offset = 0;
iomap->length = length;
iomap->type = iomap_type;
iomap->flags = 0;
out:
return error;
}
static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset,
loff_t length, unsigned flags,
struct iomap *iomap, struct iomap *srcmap)
{
int error;
error = ext4_iomap_xattr_fiemap(inode, iomap);
if (error == 0 && (offset >= iomap->length))
error = -ENOENT;
return error;
}
static const struct iomap_ops ext4_iomap_xattr_ops = {
.iomap_begin = ext4_iomap_xattr_begin,
};
static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len)
{
u64 maxbytes;
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
maxbytes = inode->i_sb->s_maxbytes;
else
maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
if (*len == 0)
return -EINVAL;
if (start > maxbytes)
return -EFBIG;
/*
* Shrink request scope to what the fs can actually handle.
*/
if (*len > maxbytes || (maxbytes - *len) < start)
*len = maxbytes - start;
return 0;
}
int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
int error = 0;
if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
error = ext4_ext_precache(inode);
if (error)
return error;
fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
}
/*
* For bitmap files the maximum size limit could be smaller than
* s_maxbytes, so check len here manually instead of just relying on the
* generic check.
*/
error = ext4_fiemap_check_ranges(inode, start, &len);
if (error)
return error;
if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR;
return iomap_fiemap(inode, fieinfo, start, len,
&ext4_iomap_xattr_ops);
}
return iomap_fiemap(inode, fieinfo, start, len, &ext4_iomap_report_ops);
}
int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
ext4_lblk_t start_blk, len_blks;
__u64 last_blk;
int error = 0;
if (ext4_has_inline_data(inode)) {
int has_inline;
down_read(&EXT4_I(inode)->xattr_sem);
has_inline = ext4_has_inline_data(inode);
up_read(&EXT4_I(inode)->xattr_sem);
if (has_inline)
return 0;
}
if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
error = ext4_ext_precache(inode);
if (error)
return error;
fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
}
error = fiemap_prep(inode, fieinfo, start, &len, 0);
if (error)
return error;
error = ext4_fiemap_check_ranges(inode, start, &len);
if (error)
return error;
start_blk = start >> inode->i_sb->s_blocksize_bits;
last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
if (last_blk >= EXT_MAX_BLOCKS)
last_blk = EXT_MAX_BLOCKS-1;
len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
/*
* Walk the extent tree gathering extent information
* and pushing extents back to the user.
*/
return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo);
}
/*
* ext4_ext_shift_path_extents:
* Shift the extents of a path structure lying between path[depth].p_ext
* and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
* if it is right shift or left shift operation.
*/
static int
ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
struct inode *inode, handle_t *handle,
enum SHIFT_DIRECTION SHIFT)
{
int depth, err = 0;
struct ext4_extent *ex_start, *ex_last;
bool update = false;
int credits, restart_credits;
depth = path->p_depth;
while (depth >= 0) {
if (depth == path->p_depth) {
ex_start = path[depth].p_ext;
if (!ex_start)
return -EFSCORRUPTED;
ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
/* leaf + sb + inode */
credits = 3;
if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr)) {
update = true;
/* extent tree + sb + inode */
credits = depth + 2;
}
restart_credits = ext4_writepage_trans_blocks(inode);
err = ext4_datasem_ensure_credits(handle, inode, credits,
restart_credits, 0);
if (err) {
if (err > 0)
err = -EAGAIN;
goto out;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
while (ex_start <= ex_last) {
if (SHIFT == SHIFT_LEFT) {
le32_add_cpu(&ex_start->ee_block,
-shift);
/* Try to merge to the left. */
if ((ex_start >
EXT_FIRST_EXTENT(path[depth].p_hdr))
&&
ext4_ext_try_to_merge_right(inode,
path, ex_start - 1))
ex_last--;
else
ex_start++;
} else {
le32_add_cpu(&ex_last->ee_block, shift);
ext4_ext_try_to_merge_right(inode, path,
ex_last);
ex_last--;
}
}
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
if (--depth < 0 || !update)
break;
}
/* Update index too */
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (SHIFT == SHIFT_LEFT)
le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
else
le32_add_cpu(&path[depth].p_idx->ei_block, shift);
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto out;
/* we are done if current index is not a starting index */
if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
break;
depth--;
}
out:
return err;
}
/*
* ext4_ext_shift_extents:
* All the extents which lies in the range from @start to the last allocated
* block for the @inode are shifted either towards left or right (depending
* upon @SHIFT) by @shift blocks.
* On success, 0 is returned, error otherwise.
*/
static int
ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
ext4_lblk_t start, ext4_lblk_t shift,
enum SHIFT_DIRECTION SHIFT)
{
struct ext4_ext_path *path;
int ret = 0, depth;
struct ext4_extent *extent;
ext4_lblk_t stop, *iterator, ex_start, ex_end;
ext4_lblk_t tmp = EXT_MAX_BLOCKS;
/* Let path point to the last extent */
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent)
goto out;
stop = le32_to_cpu(extent->ee_block);
/*
* For left shifts, make sure the hole on the left is big enough to
* accommodate the shift. For right shifts, make sure the last extent
* won't be shifted beyond EXT_MAX_BLOCKS.
*/
if (SHIFT == SHIFT_LEFT) {
path = ext4_find_extent(inode, start - 1, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (extent) {
ex_start = le32_to_cpu(extent->ee_block);
ex_end = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
ex_start = 0;
ex_end = 0;
}
if ((start == ex_start && shift > ex_start) ||
(shift > start - ex_end)) {
ret = -EINVAL;
goto out;
}
} else {
if (shift > EXT_MAX_BLOCKS -
(stop + ext4_ext_get_actual_len(extent))) {
ret = -EINVAL;
goto out;
}
}
/*
* In case of left shift, iterator points to start and it is increased
* till we reach stop. In case of right shift, iterator points to stop
* and it is decreased till we reach start.
*/
again:
ret = 0;
if (SHIFT == SHIFT_LEFT)
iterator = &start;
else
iterator = &stop;
if (tmp != EXT_MAX_BLOCKS)
*iterator = tmp;
/*
* Its safe to start updating extents. Start and stop are unsigned, so
* in case of right shift if extent with 0 block is reached, iterator
* becomes NULL to indicate the end of the loop.
*/
while (iterator && start <= stop) {
path = ext4_find_extent(inode, *iterator, &path,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
depth = path->p_depth;
extent = path[depth].p_ext;
if (!extent) {
EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
(unsigned long) *iterator);
return -EFSCORRUPTED;
}
if (SHIFT == SHIFT_LEFT && *iterator >
le32_to_cpu(extent->ee_block)) {
/* Hole, move to the next extent */
if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
path[depth].p_ext++;
} else {
*iterator = ext4_ext_next_allocated_block(path);
continue;
}
}
tmp = *iterator;
if (SHIFT == SHIFT_LEFT) {
extent = EXT_LAST_EXTENT(path[depth].p_hdr);
*iterator = le32_to_cpu(extent->ee_block) +
ext4_ext_get_actual_len(extent);
} else {
extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
if (le32_to_cpu(extent->ee_block) > start)
*iterator = le32_to_cpu(extent->ee_block) - 1;
else if (le32_to_cpu(extent->ee_block) == start)
iterator = NULL;
else {
extent = EXT_LAST_EXTENT(path[depth].p_hdr);
while (le32_to_cpu(extent->ee_block) >= start)
extent--;
if (extent == EXT_LAST_EXTENT(path[depth].p_hdr))
break;
extent++;
iterator = NULL;
}
path[depth].p_ext = extent;
}
ret = ext4_ext_shift_path_extents(path, shift, inode,
handle, SHIFT);
/* iterator can be NULL which means we should break */
if (ret == -EAGAIN)
goto again;
if (ret)
break;
}
out:
ext4_free_ext_path(path);
return ret;
}
/*
* ext4_collapse_range:
* This implements the fallocate's collapse range functionality for ext4
* Returns: 0 and non-zero on error.
*/
static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
struct address_space *mapping = inode->i_mapping;
ext4_lblk_t punch_start, punch_stop;
handle_t *handle;
unsigned int credits;
loff_t new_size, ioffset;
int ret;
/*
* We need to test this early because xfstests assumes that a
* collapse range of (0, 1) will return EOPNOTSUPP if the file
* system does not support collapse range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Collapse range works only on fs cluster size aligned regions. */
if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
return -EINVAL;
trace_ext4_collapse_range(inode, offset, len);
punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
inode_lock(inode);
/*
* There is no need to overlap collapse range with EOF, in which case
* it is effectively a truncate operation
*/
if (offset + len >= inode->i_size) {
ret = -EINVAL;
goto out_mutex;
}
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
ret = file_modified(file);
if (ret)
goto out_mutex;
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
filemap_invalidate_lock(mapping);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down offset to be aligned with page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/*
* Write tail of the last page before removed range since it will get
* removed from the page cache below.
*/
ret = filemap_write_and_wait_range(mapping, ioffset, offset);
if (ret)
goto out_mmap;
/*
* Write data that will be shifted to preserve them when discarding
* page cache below. We are also protected from pages becoming dirty
* by i_rwsem and invalidate_lock.
*/
ret = filemap_write_and_wait_range(mapping, offset + len,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE, handle);
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode, 0);
ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start);
ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ext4_discard_preallocations(inode, 0);
ret = ext4_ext_shift_extents(inode, handle, punch_stop,
punch_stop - punch_start, SHIFT_LEFT);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
new_size = inode->i_size - len;
i_size_write(inode, new_size);
EXT4_I(inode)->i_disksize = new_size;
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode_set_ctime_current(inode);
ret = ext4_mark_inode_dirty(handle, inode);
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
filemap_invalidate_unlock(mapping);
out_mutex:
inode_unlock(inode);
return ret;
}
/*
* ext4_insert_range:
* This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
* The data blocks starting from @offset to the EOF are shifted by @len
* towards right to create a hole in the @inode. Inode size is increased
* by len bytes.
* Returns 0 on success, error otherwise.
*/
static int ext4_insert_range(struct file *file, loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
struct address_space *mapping = inode->i_mapping;
handle_t *handle;
struct ext4_ext_path *path;
struct ext4_extent *extent;
ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
unsigned int credits, ee_len;
int ret = 0, depth, split_flag = 0;
loff_t ioffset;
/*
* We need to test this early because xfstests assumes that an
* insert range of (0, 1) will return EOPNOTSUPP if the file
* system does not support insert range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Insert range works only on fs cluster size aligned regions. */
if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
return -EINVAL;
trace_ext4_insert_range(inode, offset, len);
offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
inode_lock(inode);
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Check whether the maximum file size would be exceeded */
if (len > inode->i_sb->s_maxbytes - inode->i_size) {
ret = -EFBIG;
goto out_mutex;
}
/* Offset must be less than i_size */
if (offset >= inode->i_size) {
ret = -EINVAL;
goto out_mutex;
}
/* Wait for existing dio to complete */
inode_dio_wait(inode);
ret = file_modified(file);
if (ret)
goto out_mutex;
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
filemap_invalidate_lock(mapping);
ret = ext4_break_layouts(inode);
if (ret)
goto out_mmap;
/*
* Need to round down to align start offset to page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
goto out_mmap;
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE, handle);
/* Expand file to avoid data loss if there is error while shifting */
inode->i_size += len;
EXT4_I(inode)->i_disksize += len;
inode->i_mtime = inode_set_ctime_current(inode);
ret = ext4_mark_inode_dirty(handle, inode);
if (ret)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode, 0);
path = ext4_find_extent(inode, offset_lblk, NULL, 0);
if (IS_ERR(path)) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
depth = ext_depth(inode);
extent = path[depth].p_ext;
if (extent) {
ee_start_lblk = le32_to_cpu(extent->ee_block);
ee_len = ext4_ext_get_actual_len(extent);
/*
* If offset_lblk is not the starting block of extent, split
* the extent @offset_lblk
*/
if ((offset_lblk > ee_start_lblk) &&
(offset_lblk < (ee_start_lblk + ee_len))) {
if (ext4_ext_is_unwritten(extent))
split_flag = EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
ret = ext4_split_extent_at(handle, inode, &path,
offset_lblk, split_flag,
EXT4_EX_NOCACHE |
EXT4_GET_BLOCKS_PRE_IO |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
}
ext4_free_ext_path(path);
if (ret < 0) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
} else {
ext4_free_ext_path(path);
}
ext4_es_remove_extent(inode, offset_lblk, EXT_MAX_BLOCKS - offset_lblk);
/*
* if offset_lblk lies in a hole which is at start of file, use
* ee_start_lblk to shift extents
*/
ret = ext4_ext_shift_extents(inode, handle,
max(ee_start_lblk, offset_lblk), len_lblk, SHIFT_RIGHT);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_mmap:
filemap_invalidate_unlock(mapping);
out_mutex:
inode_unlock(inode);
return ret;
}
/**
* ext4_swap_extents() - Swap extents between two inodes
* @handle: handle for this transaction
* @inode1: First inode
* @inode2: Second inode
* @lblk1: Start block for first inode
* @lblk2: Start block for second inode
* @count: Number of blocks to swap
* @unwritten: Mark second inode's extents as unwritten after swap
* @erp: Pointer to save error value
*
* This helper routine does exactly what is promise "swap extents". All other
* stuff such as page-cache locking consistency, bh mapping consistency or
* extent's data copying must be performed by caller.
* Locking:
* i_rwsem is held for both inodes
* i_data_sem is locked for write for both inodes
* Assumptions:
* All pages from requested range are locked for both inodes
*/
int
ext4_swap_extents(handle_t *handle, struct inode *inode1,
struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
ext4_lblk_t count, int unwritten, int *erp)
{
struct ext4_ext_path *path1 = NULL;
struct ext4_ext_path *path2 = NULL;
int replaced_count = 0;
BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
BUG_ON(!inode_is_locked(inode1));
BUG_ON(!inode_is_locked(inode2));
ext4_es_remove_extent(inode1, lblk1, count);
ext4_es_remove_extent(inode2, lblk2, count);
while (count) {
struct ext4_extent *ex1, *ex2, tmp_ex;
ext4_lblk_t e1_blk, e2_blk;
int e1_len, e2_len, len;
int split = 0;
path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path1)) {
*erp = PTR_ERR(path1);
path1 = NULL;
finish:
count = 0;
goto repeat;
}
path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path2)) {
*erp = PTR_ERR(path2);
path2 = NULL;
goto finish;
}
ex1 = path1[path1->p_depth].p_ext;
ex2 = path2[path2->p_depth].p_ext;
/* Do we have something to swap ? */
if (unlikely(!ex2 || !ex1))
goto finish;
e1_blk = le32_to_cpu(ex1->ee_block);
e2_blk = le32_to_cpu(ex2->ee_block);
e1_len = ext4_ext_get_actual_len(ex1);
e2_len = ext4_ext_get_actual_len(ex2);
/* Hole handling */
if (!in_range(lblk1, e1_blk, e1_len) ||
!in_range(lblk2, e2_blk, e2_len)) {
ext4_lblk_t next1, next2;
/* if hole after extent, then go to next extent */
next1 = ext4_ext_next_allocated_block(path1);
next2 = ext4_ext_next_allocated_block(path2);
/* If hole before extent, then shift to that extent */
if (e1_blk > lblk1)
next1 = e1_blk;
if (e2_blk > lblk2)
next2 = e2_blk;
/* Do we have something to swap */
if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
goto finish;
/* Move to the rightest boundary */
len = next1 - lblk1;
if (len < next2 - lblk2)
len = next2 - lblk2;
if (len > count)
len = count;
lblk1 += len;
lblk2 += len;
count -= len;
goto repeat;
}
/* Prepare left boundary */
if (e1_blk < lblk1) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1, 0);
if (unlikely(*erp))
goto finish;
}
if (e2_blk < lblk2) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2, 0);
if (unlikely(*erp))
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
/* Prepare right boundary */
len = count;
if (len > e1_blk + e1_len - lblk1)
len = e1_blk + e1_len - lblk1;
if (len > e2_blk + e2_len - lblk2)
len = e2_blk + e2_len - lblk2;
if (len != e1_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode1,
&path1, lblk1 + len, 0);
if (unlikely(*erp))
goto finish;
}
if (len != e2_len) {
split = 1;
*erp = ext4_force_split_extent_at(handle, inode2,
&path2, lblk2 + len, 0);
if (*erp)
goto finish;
}
/* ext4_split_extent_at() may result in leaf extent split,
* path must to be revalidated. */
if (split)
goto repeat;
BUG_ON(e2_len != e1_len);
*erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
if (unlikely(*erp))
goto finish;
/* Both extents are fully inside boundaries. Swap it now */
tmp_ex = *ex1;
ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
ex1->ee_len = cpu_to_le16(e2_len);
ex2->ee_len = cpu_to_le16(e1_len);
if (unwritten)
ext4_ext_mark_unwritten(ex2);
if (ext4_ext_is_unwritten(&tmp_ex))
ext4_ext_mark_unwritten(ex1);
ext4_ext_try_to_merge(handle, inode2, path2, ex2);
ext4_ext_try_to_merge(handle, inode1, path1, ex1);
*erp = ext4_ext_dirty(handle, inode2, path2 +
path2->p_depth);
if (unlikely(*erp))
goto finish;
*erp = ext4_ext_dirty(handle, inode1, path1 +
path1->p_depth);
/*
* Looks scarry ah..? second inode already points to new blocks,
* and it was successfully dirtied. But luckily error may happen
* only due to journal error, so full transaction will be
* aborted anyway.
*/
if (unlikely(*erp))
goto finish;
lblk1 += len;
lblk2 += len;
replaced_count += len;
count -= len;
repeat:
ext4_free_ext_path(path1);
ext4_free_ext_path(path2);
path1 = path2 = NULL;
}
return replaced_count;
}
/*
* ext4_clu_mapped - determine whether any block in a logical cluster has
* been mapped to a physical cluster
*
* @inode - file containing the logical cluster
* @lclu - logical cluster of interest
*
* Returns 1 if any block in the logical cluster is mapped, signifying
* that a physical cluster has been allocated for it. Otherwise,
* returns 0. Can also return negative error codes. Derived from
* ext4_ext_map_blocks().
*/
int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_ext_path *path;
int depth, mapped = 0, err = 0;
struct ext4_extent *extent;
ext4_lblk_t first_lblk, first_lclu, last_lclu;
/*
* if data can be stored inline, the logical cluster isn't
* mapped - no physical clusters have been allocated, and the
* file has no extents
*/
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) ||
ext4_has_inline_data(inode))
return 0;
/* search for the extent closest to the first block in the cluster */
path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out;
}
depth = ext_depth(inode);
/*
* A consistent leaf must not be empty. This situation is possible,
* though, _during_ tree modification, and it's why an assert can't
* be put in ext4_find_extent().
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode,
"bad extent address - lblock: %lu, depth: %d, pblock: %lld",
(unsigned long) EXT4_C2B(sbi, lclu),
depth, path[depth].p_block);
err = -EFSCORRUPTED;
goto out;
}
extent = path[depth].p_ext;
/* can't be mapped if the extent tree is empty */
if (extent == NULL)
goto out;
first_lblk = le32_to_cpu(extent->ee_block);
first_lclu = EXT4_B2C(sbi, first_lblk);
/*
* Three possible outcomes at this point - found extent spanning
* the target cluster, to the left of the target cluster, or to the
* right of the target cluster. The first two cases are handled here.
* The last case indicates the target cluster is not mapped.
*/
if (lclu >= first_lclu) {
last_lclu = EXT4_B2C(sbi, first_lblk +
ext4_ext_get_actual_len(extent) - 1);
if (lclu <= last_lclu) {
mapped = 1;
} else {
first_lblk = ext4_ext_next_allocated_block(path);
first_lclu = EXT4_B2C(sbi, first_lblk);
if (lclu == first_lclu)
mapped = 1;
}
}
out:
ext4_free_ext_path(path);
return err ? err : mapped;
}
/*
* Updates physical block address and unwritten status of extent
* starting at lblk start and of len. If such an extent doesn't exist,
* this function splits the extent tree appropriately to create an
* extent like this. This function is called in the fast commit
* replay path. Returns 0 on success and error on failure.
*/
int ext4_ext_replay_update_ex(struct inode *inode, ext4_lblk_t start,
int len, int unwritten, ext4_fsblk_t pblk)
{
struct ext4_ext_path *path = NULL, *ppath;
struct ext4_extent *ex;
int ret;
path = ext4_find_extent(inode, start, NULL, 0);
if (IS_ERR(path))
return PTR_ERR(path);
ex = path[path->p_depth].p_ext;
if (!ex) {
ret = -EFSCORRUPTED;
goto out;
}
if (le32_to_cpu(ex->ee_block) != start ||
ext4_ext_get_actual_len(ex) != len) {
/* We need to split this extent to match our extent first */
ppath = path;
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_force_split_extent_at(NULL, inode, &ppath, start, 1);
up_write(&EXT4_I(inode)->i_data_sem);
if (ret)
goto out;
kfree(path);
path = ext4_find_extent(inode, start, NULL, 0);
if (IS_ERR(path))
return -1;
ppath = path;
ex = path[path->p_depth].p_ext;
WARN_ON(le32_to_cpu(ex->ee_block) != start);
if (ext4_ext_get_actual_len(ex) != len) {
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_force_split_extent_at(NULL, inode, &ppath,
start + len, 1);
up_write(&EXT4_I(inode)->i_data_sem);
if (ret)
goto out;
kfree(path);
path = ext4_find_extent(inode, start, NULL, 0);
if (IS_ERR(path))
return -EINVAL;
ex = path[path->p_depth].p_ext;
}
}
if (unwritten)
ext4_ext_mark_unwritten(ex);
else
ext4_ext_mark_initialized(ex);
ext4_ext_store_pblock(ex, pblk);
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
up_write(&EXT4_I(inode)->i_data_sem);
out:
ext4_free_ext_path(path);
ext4_mark_inode_dirty(NULL, inode);
return ret;
}
/* Try to shrink the extent tree */
void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ex;
ext4_lblk_t old_cur, cur = 0;
while (cur < end) {
path = ext4_find_extent(inode, cur, NULL, 0);
if (IS_ERR(path))
return;
ex = path[path->p_depth].p_ext;
if (!ex) {
ext4_free_ext_path(path);
ext4_mark_inode_dirty(NULL, inode);
return;
}
old_cur = cur;
cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
if (cur <= old_cur)
cur = old_cur + 1;
ext4_ext_try_to_merge(NULL, inode, path, ex);
down_write(&EXT4_I(inode)->i_data_sem);
ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
up_write(&EXT4_I(inode)->i_data_sem);
ext4_mark_inode_dirty(NULL, inode);
ext4_free_ext_path(path);
}
}
/* Check if *cur is a hole and if it is, skip it */
static int skip_hole(struct inode *inode, ext4_lblk_t *cur)
{
int ret;
struct ext4_map_blocks map;
map.m_lblk = *cur;
map.m_len = ((inode->i_size) >> inode->i_sb->s_blocksize_bits) - *cur;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
return ret;
if (ret != 0)
return 0;
*cur = *cur + map.m_len;
return 0;
}
/* Count number of blocks used by this inode and update i_blocks */
int ext4_ext_replay_set_iblocks(struct inode *inode)
{
struct ext4_ext_path *path = NULL, *path2 = NULL;
struct ext4_extent *ex;
ext4_lblk_t cur = 0, end;
int numblks = 0, i, ret = 0;
ext4_fsblk_t cmp1, cmp2;
struct ext4_map_blocks map;
/* Determin the size of the file first */
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
ex = path[path->p_depth].p_ext;
if (!ex) {
ext4_free_ext_path(path);
goto out;
}
end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
ext4_free_ext_path(path);
/* Count the number of data blocks */
cur = 0;
while (cur < end) {
map.m_lblk = cur;
map.m_len = end - cur;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
break;
if (ret > 0)
numblks += ret;
cur = cur + map.m_len;
}
/*
* Count the number of extent tree blocks. We do it by looking up
* two successive extents and determining the difference between
* their paths. When path is different for 2 successive extents
* we compare the blocks in the path at each level and increment
* iblocks by total number of differences found.
*/
cur = 0;
ret = skip_hole(inode, &cur);
if (ret < 0)
goto out;
path = ext4_find_extent(inode, cur, NULL, 0);
if (IS_ERR(path))
goto out;
numblks += path->p_depth;
ext4_free_ext_path(path);
while (cur < end) {
path = ext4_find_extent(inode, cur, NULL, 0);
if (IS_ERR(path))
break;
ex = path[path->p_depth].p_ext;
if (!ex) {
ext4_free_ext_path(path);
return 0;
}
cur = max(cur + 1, le32_to_cpu(ex->ee_block) +
ext4_ext_get_actual_len(ex));
ret = skip_hole(inode, &cur);
if (ret < 0) {
ext4_free_ext_path(path);
break;
}
path2 = ext4_find_extent(inode, cur, NULL, 0);
if (IS_ERR(path2)) {
ext4_free_ext_path(path);
break;
}
for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) {
cmp1 = cmp2 = 0;
if (i <= path->p_depth)
cmp1 = path[i].p_bh ?
path[i].p_bh->b_blocknr : 0;
if (i <= path2->p_depth)
cmp2 = path2[i].p_bh ?
path2[i].p_bh->b_blocknr : 0;
if (cmp1 != cmp2 && cmp2 != 0)
numblks++;
}
ext4_free_ext_path(path);
ext4_free_ext_path(path2);
}
out:
inode->i_blocks = numblks << (inode->i_sb->s_blocksize_bits - 9);
ext4_mark_inode_dirty(NULL, inode);
return 0;
}
int ext4_ext_clear_bb(struct inode *inode)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ex;
ext4_lblk_t cur = 0, end;
int j, ret = 0;
struct ext4_map_blocks map;
if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA))
return 0;
/* Determin the size of the file first */
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
ex = path[path->p_depth].p_ext;
if (!ex) {
ext4_free_ext_path(path);
return 0;
}
end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
ext4_free_ext_path(path);
cur = 0;
while (cur < end) {
map.m_lblk = cur;
map.m_len = end - cur;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
break;
if (ret > 0) {
path = ext4_find_extent(inode, map.m_lblk, NULL, 0);
if (!IS_ERR_OR_NULL(path)) {
for (j = 0; j < path->p_depth; j++) {
ext4_mb_mark_bb(inode->i_sb,
path[j].p_block, 1, 0);
ext4_fc_record_regions(inode->i_sb, inode->i_ino,
0, path[j].p_block, 1, 1);
}
ext4_free_ext_path(path);
}
ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
ext4_fc_record_regions(inode->i_sb, inode->i_ino,
map.m_lblk, map.m_pblk, map.m_len, 1);
}
cur = cur + map.m_len;
}
return 0;
}
| linux-master | fs/ext4/extents.c |
// SPDX-License-Identifier: LGPL-2.1
/*
* Copyright IBM Corporation, 2007
* Author Aneesh Kumar K.V <[email protected]>
*
*/
#include <linux/slab.h>
#include "ext4_jbd2.h"
#include "ext4_extents.h"
/*
* The contiguous blocks details which can be
* represented by a single extent
*/
struct migrate_struct {
ext4_lblk_t first_block, last_block, curr_block;
ext4_fsblk_t first_pblock, last_pblock;
};
static int finish_range(handle_t *handle, struct inode *inode,
struct migrate_struct *lb)
{
int retval = 0, needed;
struct ext4_extent newext;
struct ext4_ext_path *path;
if (lb->first_pblock == 0)
return 0;
/* Add the extent to temp inode*/
newext.ee_block = cpu_to_le32(lb->first_block);
newext.ee_len = cpu_to_le16(lb->last_block - lb->first_block + 1);
ext4_ext_store_pblock(&newext, lb->first_pblock);
/* Locking only for convenience since we are operating on temp inode */
down_write(&EXT4_I(inode)->i_data_sem);
path = ext4_find_extent(inode, lb->first_block, NULL, 0);
if (IS_ERR(path)) {
retval = PTR_ERR(path);
path = NULL;
goto err_out;
}
/*
* Calculate the credit needed to inserting this extent
* Since we are doing this in loop we may accumulate extra
* credit. But below we try to not accumulate too much
* of them by restarting the journal.
*/
needed = ext4_ext_calc_credits_for_single_extent(inode,
lb->last_block - lb->first_block + 1, path);
retval = ext4_datasem_ensure_credits(handle, inode, needed, needed, 0);
if (retval < 0)
goto err_out;
retval = ext4_ext_insert_extent(handle, inode, &path, &newext, 0);
err_out:
up_write((&EXT4_I(inode)->i_data_sem));
ext4_free_ext_path(path);
lb->first_pblock = 0;
return retval;
}
static int update_extent_range(handle_t *handle, struct inode *inode,
ext4_fsblk_t pblock, struct migrate_struct *lb)
{
int retval;
/*
* See if we can add on to the existing range (if it exists)
*/
if (lb->first_pblock &&
(lb->last_pblock+1 == pblock) &&
(lb->last_block+1 == lb->curr_block)) {
lb->last_pblock = pblock;
lb->last_block = lb->curr_block;
lb->curr_block++;
return 0;
}
/*
* Start a new range.
*/
retval = finish_range(handle, inode, lb);
lb->first_pblock = lb->last_pblock = pblock;
lb->first_block = lb->last_block = lb->curr_block;
lb->curr_block++;
return retval;
}
static int update_ind_extent_range(handle_t *handle, struct inode *inode,
ext4_fsblk_t pblock,
struct migrate_struct *lb)
{
struct buffer_head *bh;
__le32 *i_data;
int i, retval = 0;
unsigned long max_entries = inode->i_sb->s_blocksize >> 2;
bh = ext4_sb_bread(inode->i_sb, pblock, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
i_data = (__le32 *)bh->b_data;
for (i = 0; i < max_entries; i++) {
if (i_data[i]) {
retval = update_extent_range(handle, inode,
le32_to_cpu(i_data[i]), lb);
if (retval)
break;
} else {
lb->curr_block++;
}
}
put_bh(bh);
return retval;
}
static int update_dind_extent_range(handle_t *handle, struct inode *inode,
ext4_fsblk_t pblock,
struct migrate_struct *lb)
{
struct buffer_head *bh;
__le32 *i_data;
int i, retval = 0;
unsigned long max_entries = inode->i_sb->s_blocksize >> 2;
bh = ext4_sb_bread(inode->i_sb, pblock, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
i_data = (__le32 *)bh->b_data;
for (i = 0; i < max_entries; i++) {
if (i_data[i]) {
retval = update_ind_extent_range(handle, inode,
le32_to_cpu(i_data[i]), lb);
if (retval)
break;
} else {
/* Only update the file block number */
lb->curr_block += max_entries;
}
}
put_bh(bh);
return retval;
}
static int update_tind_extent_range(handle_t *handle, struct inode *inode,
ext4_fsblk_t pblock,
struct migrate_struct *lb)
{
struct buffer_head *bh;
__le32 *i_data;
int i, retval = 0;
unsigned long max_entries = inode->i_sb->s_blocksize >> 2;
bh = ext4_sb_bread(inode->i_sb, pblock, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
i_data = (__le32 *)bh->b_data;
for (i = 0; i < max_entries; i++) {
if (i_data[i]) {
retval = update_dind_extent_range(handle, inode,
le32_to_cpu(i_data[i]), lb);
if (retval)
break;
} else {
/* Only update the file block number */
lb->curr_block += max_entries * max_entries;
}
}
put_bh(bh);
return retval;
}
static int free_dind_blocks(handle_t *handle,
struct inode *inode, __le32 i_data)
{
int i;
__le32 *tmp_idata;
struct buffer_head *bh;
struct super_block *sb = inode->i_sb;
unsigned long max_entries = inode->i_sb->s_blocksize >> 2;
int err;
bh = ext4_sb_bread(sb, le32_to_cpu(i_data), 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
tmp_idata = (__le32 *)bh->b_data;
for (i = 0; i < max_entries; i++) {
if (tmp_idata[i]) {
err = ext4_journal_ensure_credits(handle,
EXT4_RESERVE_TRANS_BLOCKS,
ext4_free_metadata_revoke_credits(sb, 1));
if (err < 0) {
put_bh(bh);
return err;
}
ext4_free_blocks(handle, inode, NULL,
le32_to_cpu(tmp_idata[i]), 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
}
}
put_bh(bh);
err = ext4_journal_ensure_credits(handle, EXT4_RESERVE_TRANS_BLOCKS,
ext4_free_metadata_revoke_credits(sb, 1));
if (err < 0)
return err;
ext4_free_blocks(handle, inode, NULL, le32_to_cpu(i_data), 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
return 0;
}
static int free_tind_blocks(handle_t *handle,
struct inode *inode, __le32 i_data)
{
int i, retval = 0;
__le32 *tmp_idata;
struct buffer_head *bh;
unsigned long max_entries = inode->i_sb->s_blocksize >> 2;
bh = ext4_sb_bread(inode->i_sb, le32_to_cpu(i_data), 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
tmp_idata = (__le32 *)bh->b_data;
for (i = 0; i < max_entries; i++) {
if (tmp_idata[i]) {
retval = free_dind_blocks(handle,
inode, tmp_idata[i]);
if (retval) {
put_bh(bh);
return retval;
}
}
}
put_bh(bh);
retval = ext4_journal_ensure_credits(handle, EXT4_RESERVE_TRANS_BLOCKS,
ext4_free_metadata_revoke_credits(inode->i_sb, 1));
if (retval < 0)
return retval;
ext4_free_blocks(handle, inode, NULL, le32_to_cpu(i_data), 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
return 0;
}
static int free_ind_block(handle_t *handle, struct inode *inode, __le32 *i_data)
{
int retval;
/* ei->i_data[EXT4_IND_BLOCK] */
if (i_data[0]) {
retval = ext4_journal_ensure_credits(handle,
EXT4_RESERVE_TRANS_BLOCKS,
ext4_free_metadata_revoke_credits(inode->i_sb, 1));
if (retval < 0)
return retval;
ext4_free_blocks(handle, inode, NULL,
le32_to_cpu(i_data[0]), 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
}
/* ei->i_data[EXT4_DIND_BLOCK] */
if (i_data[1]) {
retval = free_dind_blocks(handle, inode, i_data[1]);
if (retval)
return retval;
}
/* ei->i_data[EXT4_TIND_BLOCK] */
if (i_data[2]) {
retval = free_tind_blocks(handle, inode, i_data[2]);
if (retval)
return retval;
}
return 0;
}
static int ext4_ext_swap_inode_data(handle_t *handle, struct inode *inode,
struct inode *tmp_inode)
{
int retval, retval2 = 0;
__le32 i_data[3];
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_inode_info *tmp_ei = EXT4_I(tmp_inode);
/*
* One credit accounted for writing the
* i_data field of the original inode
*/
retval = ext4_journal_ensure_credits(handle, 1, 0);
if (retval < 0)
goto err_out;
i_data[0] = ei->i_data[EXT4_IND_BLOCK];
i_data[1] = ei->i_data[EXT4_DIND_BLOCK];
i_data[2] = ei->i_data[EXT4_TIND_BLOCK];
down_write(&EXT4_I(inode)->i_data_sem);
/*
* if EXT4_STATE_EXT_MIGRATE is cleared a block allocation
* happened after we started the migrate. We need to
* fail the migrate
*/
if (!ext4_test_inode_state(inode, EXT4_STATE_EXT_MIGRATE)) {
retval = -EAGAIN;
up_write(&EXT4_I(inode)->i_data_sem);
goto err_out;
} else
ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
/*
* We have the extent map build with the tmp inode.
* Now copy the i_data across
*/
ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
memcpy(ei->i_data, tmp_ei->i_data, sizeof(ei->i_data));
/*
* Update i_blocks with the new blocks that got
* allocated while adding extents for extent index
* blocks.
*
* While converting to extents we need not
* update the original inode i_blocks for extent blocks
* via quota APIs. The quota update happened via tmp_inode already.
*/
spin_lock(&inode->i_lock);
inode->i_blocks += tmp_inode->i_blocks;
spin_unlock(&inode->i_lock);
up_write(&EXT4_I(inode)->i_data_sem);
/*
* We mark the inode dirty after, because we decrement the
* i_blocks when freeing the indirect meta-data blocks
*/
retval = free_ind_block(handle, inode, i_data);
retval2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(retval2 && !retval))
retval = retval2;
err_out:
return retval;
}
static int free_ext_idx(handle_t *handle, struct inode *inode,
struct ext4_extent_idx *ix)
{
int i, retval = 0;
ext4_fsblk_t block;
struct buffer_head *bh;
struct ext4_extent_header *eh;
block = ext4_idx_pblock(ix);
bh = ext4_sb_bread(inode->i_sb, block, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
eh = (struct ext4_extent_header *)bh->b_data;
if (eh->eh_depth != 0) {
ix = EXT_FIRST_INDEX(eh);
for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ix++) {
retval = free_ext_idx(handle, inode, ix);
if (retval) {
put_bh(bh);
return retval;
}
}
}
put_bh(bh);
retval = ext4_journal_ensure_credits(handle, EXT4_RESERVE_TRANS_BLOCKS,
ext4_free_metadata_revoke_credits(inode->i_sb, 1));
if (retval < 0)
return retval;
ext4_free_blocks(handle, inode, NULL, block, 1,
EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
return 0;
}
/*
* Free the extent meta data blocks only
*/
static int free_ext_block(handle_t *handle, struct inode *inode)
{
int i, retval = 0;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_extent_header *eh = (struct ext4_extent_header *)ei->i_data;
struct ext4_extent_idx *ix;
if (eh->eh_depth == 0)
/*
* No extra blocks allocated for extent meta data
*/
return 0;
ix = EXT_FIRST_INDEX(eh);
for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ix++) {
retval = free_ext_idx(handle, inode, ix);
if (retval)
return retval;
}
return retval;
}
int ext4_ext_migrate(struct inode *inode)
{
handle_t *handle;
int retval = 0, i;
__le32 *i_data;
struct ext4_inode_info *ei;
struct inode *tmp_inode = NULL;
struct migrate_struct lb;
unsigned long max_entries;
__u32 goal, tmp_csum_seed;
uid_t owner[2];
int alloc_ctx;
/*
* If the filesystem does not support extents, or the inode
* already is extent-based, error out.
*/
if (!ext4_has_feature_extents(inode->i_sb) ||
ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
ext4_has_inline_data(inode))
return -EINVAL;
if (S_ISLNK(inode->i_mode) && inode->i_blocks == 0)
/*
* don't migrate fast symlink
*/
return retval;
alloc_ctx = ext4_writepages_down_write(inode->i_sb);
/*
* Worst case we can touch the allocation bitmaps and a block
* group descriptor block. We do need to worry about
* credits for modifying the quota inode.
*/
handle = ext4_journal_start(inode, EXT4_HT_MIGRATE,
3 + EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
goto out_unlock;
}
goal = (((inode->i_ino - 1) / EXT4_INODES_PER_GROUP(inode->i_sb)) *
EXT4_INODES_PER_GROUP(inode->i_sb)) + 1;
owner[0] = i_uid_read(inode);
owner[1] = i_gid_read(inode);
tmp_inode = ext4_new_inode(handle, d_inode(inode->i_sb->s_root),
S_IFREG, NULL, goal, owner, 0);
if (IS_ERR(tmp_inode)) {
retval = PTR_ERR(tmp_inode);
ext4_journal_stop(handle);
goto out_unlock;
}
/*
* Use the correct seed for checksum (i.e. the seed from 'inode'). This
* is so that the metadata blocks will have the correct checksum after
* the migration.
*/
ei = EXT4_I(inode);
tmp_csum_seed = EXT4_I(tmp_inode)->i_csum_seed;
EXT4_I(tmp_inode)->i_csum_seed = ei->i_csum_seed;
i_size_write(tmp_inode, i_size_read(inode));
/*
* Set the i_nlink to zero so it will be deleted later
* when we drop inode reference.
*/
clear_nlink(tmp_inode);
ext4_ext_tree_init(handle, tmp_inode);
ext4_journal_stop(handle);
/*
* start with one credit accounted for
* superblock modification.
*
* For the tmp_inode we already have committed the
* transaction that created the inode. Later as and
* when we add extents we extent the journal
*/
/*
* Even though we take i_rwsem we can still cause block
* allocation via mmap write to holes. If we have allocated
* new blocks we fail migrate. New block allocation will
* clear EXT4_STATE_EXT_MIGRATE flag. The flag is updated
* with i_data_sem held to prevent racing with block
* allocation.
*/
down_read(&EXT4_I(inode)->i_data_sem);
ext4_set_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
up_read((&EXT4_I(inode)->i_data_sem));
handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1);
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
goto out_tmp_inode;
}
i_data = ei->i_data;
memset(&lb, 0, sizeof(lb));
/* 32 bit block address 4 bytes */
max_entries = inode->i_sb->s_blocksize >> 2;
for (i = 0; i < EXT4_NDIR_BLOCKS; i++) {
if (i_data[i]) {
retval = update_extent_range(handle, tmp_inode,
le32_to_cpu(i_data[i]), &lb);
if (retval)
goto err_out;
} else
lb.curr_block++;
}
if (i_data[EXT4_IND_BLOCK]) {
retval = update_ind_extent_range(handle, tmp_inode,
le32_to_cpu(i_data[EXT4_IND_BLOCK]), &lb);
if (retval)
goto err_out;
} else
lb.curr_block += max_entries;
if (i_data[EXT4_DIND_BLOCK]) {
retval = update_dind_extent_range(handle, tmp_inode,
le32_to_cpu(i_data[EXT4_DIND_BLOCK]), &lb);
if (retval)
goto err_out;
} else
lb.curr_block += max_entries * max_entries;
if (i_data[EXT4_TIND_BLOCK]) {
retval = update_tind_extent_range(handle, tmp_inode,
le32_to_cpu(i_data[EXT4_TIND_BLOCK]), &lb);
if (retval)
goto err_out;
}
/*
* Build the last extent
*/
retval = finish_range(handle, tmp_inode, &lb);
err_out:
if (retval)
/*
* Failure case delete the extent information with the
* tmp_inode
*/
free_ext_block(handle, tmp_inode);
else {
retval = ext4_ext_swap_inode_data(handle, inode, tmp_inode);
if (retval)
/*
* if we fail to swap inode data free the extent
* details of the tmp inode
*/
free_ext_block(handle, tmp_inode);
}
/* We mark the tmp_inode dirty via ext4_ext_tree_init. */
retval = ext4_journal_ensure_credits(handle, 1, 0);
if (retval < 0)
goto out_stop;
/*
* Mark the tmp_inode as of size zero
*/
i_size_write(tmp_inode, 0);
/*
* set the i_blocks count to zero
* so that the ext4_evict_inode() does the
* right job
*
* We don't need to take the i_lock because
* the inode is not visible to user space.
*/
tmp_inode->i_blocks = 0;
EXT4_I(tmp_inode)->i_csum_seed = tmp_csum_seed;
/* Reset the extent details */
ext4_ext_tree_init(handle, tmp_inode);
out_stop:
ext4_journal_stop(handle);
out_tmp_inode:
unlock_new_inode(tmp_inode);
iput(tmp_inode);
out_unlock:
ext4_writepages_up_write(inode->i_sb, alloc_ctx);
return retval;
}
/*
* Migrate a simple extent-based inode to use the i_blocks[] array
*/
int ext4_ind_migrate(struct inode *inode)
{
struct ext4_extent_header *eh;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_super_block *es = sbi->s_es;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_extent *ex;
unsigned int i, len;
ext4_lblk_t start, end;
ext4_fsblk_t blk;
handle_t *handle;
int ret, ret2 = 0;
int alloc_ctx;
if (!ext4_has_feature_extents(inode->i_sb) ||
(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
return -EINVAL;
if (ext4_has_feature_bigalloc(inode->i_sb))
return -EOPNOTSUPP;
/*
* In order to get correct extent info, force all delayed allocation
* blocks to be allocated, otherwise delayed allocation blocks may not
* be reflected and bypass the checks on extent header.
*/
if (test_opt(inode->i_sb, DELALLOC))
ext4_alloc_da_blocks(inode);
alloc_ctx = ext4_writepages_down_write(inode->i_sb);
handle = ext4_journal_start(inode, EXT4_HT_MIGRATE, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_unlock;
}
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_ext_check_inode(inode);
if (ret)
goto errout;
eh = ext_inode_hdr(inode);
ex = EXT_FIRST_EXTENT(eh);
if (ext4_blocks_count(es) > EXT4_MAX_BLOCK_FILE_PHYS ||
eh->eh_depth != 0 || le16_to_cpu(eh->eh_entries) > 1) {
ret = -EOPNOTSUPP;
goto errout;
}
if (eh->eh_entries == 0)
blk = len = start = end = 0;
else {
len = le16_to_cpu(ex->ee_len);
blk = ext4_ext_pblock(ex);
start = le32_to_cpu(ex->ee_block);
end = start + len - 1;
if (end >= EXT4_NDIR_BLOCKS) {
ret = -EOPNOTSUPP;
goto errout;
}
}
ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
memset(ei->i_data, 0, sizeof(ei->i_data));
for (i = start; i <= end; i++)
ei->i_data[i] = cpu_to_le32(blk++);
ret2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(ret2 && !ret))
ret = ret2;
errout:
ext4_journal_stop(handle);
up_write(&EXT4_I(inode)->i_data_sem);
out_unlock:
ext4_writepages_up_write(inode->i_sb, alloc_ctx);
return ret;
}
| linux-master | fs/ext4/migrate.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/balloc.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* Enhanced block allocation by Stephen Tweedie ([email protected]), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/time.h>
#include <linux/capability.h>
#include <linux/fs.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "mballoc.h"
#include <trace/events/ext4.h>
static unsigned ext4_num_base_meta_clusters(struct super_block *sb,
ext4_group_t block_group);
/*
* balloc.c contains the blocks allocation and deallocation routines
*/
/*
* Calculate block group number for a given block number
*/
ext4_group_t ext4_get_group_number(struct super_block *sb,
ext4_fsblk_t block)
{
ext4_group_t group;
if (test_opt2(sb, STD_GROUP_SIZE))
group = (block -
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) >>
(EXT4_BLOCK_SIZE_BITS(sb) + EXT4_CLUSTER_BITS(sb) + 3);
else
ext4_get_group_no_and_offset(sb, block, &group, NULL);
return group;
}
/*
* Calculate the block group number and offset into the block/cluster
* allocation bitmap, given a block number
*/
void ext4_get_group_no_and_offset(struct super_block *sb, ext4_fsblk_t blocknr,
ext4_group_t *blockgrpp, ext4_grpblk_t *offsetp)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
ext4_grpblk_t offset;
blocknr = blocknr - le32_to_cpu(es->s_first_data_block);
offset = do_div(blocknr, EXT4_BLOCKS_PER_GROUP(sb)) >>
EXT4_SB(sb)->s_cluster_bits;
if (offsetp)
*offsetp = offset;
if (blockgrpp)
*blockgrpp = blocknr;
}
/*
* Check whether the 'block' lives within the 'block_group'. Returns 1 if so
* and 0 otherwise.
*/
static inline int ext4_block_in_group(struct super_block *sb,
ext4_fsblk_t block,
ext4_group_t block_group)
{
ext4_group_t actual_group;
actual_group = ext4_get_group_number(sb, block);
return (actual_group == block_group) ? 1 : 0;
}
/*
* Return the number of clusters used for file system metadata; this
* represents the overhead needed by the file system.
*/
static unsigned ext4_num_overhead_clusters(struct super_block *sb,
ext4_group_t block_group,
struct ext4_group_desc *gdp)
{
unsigned base_clusters, num_clusters;
int block_cluster = -1, inode_cluster;
int itbl_cluster_start = -1, itbl_cluster_end = -1;
ext4_fsblk_t start = ext4_group_first_block_no(sb, block_group);
ext4_fsblk_t end = start + EXT4_BLOCKS_PER_GROUP(sb) - 1;
ext4_fsblk_t itbl_blk_start, itbl_blk_end;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* This is the number of clusters used by the superblock,
* block group descriptors, and reserved block group
* descriptor blocks */
base_clusters = ext4_num_base_meta_clusters(sb, block_group);
num_clusters = base_clusters;
/*
* Account and record inode table clusters if any cluster
* is in the block group, or inode table cluster range is
* [-1, -1] and won't overlap with block/inode bitmap cluster
* accounted below.
*/
itbl_blk_start = ext4_inode_table(sb, gdp);
itbl_blk_end = itbl_blk_start + sbi->s_itb_per_group - 1;
if (itbl_blk_start <= end && itbl_blk_end >= start) {
itbl_blk_start = itbl_blk_start >= start ?
itbl_blk_start : start;
itbl_blk_end = itbl_blk_end <= end ?
itbl_blk_end : end;
itbl_cluster_start = EXT4_B2C(sbi, itbl_blk_start - start);
itbl_cluster_end = EXT4_B2C(sbi, itbl_blk_end - start);
num_clusters += itbl_cluster_end - itbl_cluster_start + 1;
/* check if border cluster is overlapped */
if (itbl_cluster_start == base_clusters - 1)
num_clusters--;
}
/*
* For the allocation bitmaps, we first need to check to see
* if the block is in the block group. If it is, then check
* to see if the cluster is already accounted for in the clusters
* used for the base metadata cluster and inode tables cluster.
* Normally all of these blocks are contiguous, so the special
* case handling shouldn't be necessary except for *very*
* unusual file system layouts.
*/
if (ext4_block_in_group(sb, ext4_block_bitmap(sb, gdp), block_group)) {
block_cluster = EXT4_B2C(sbi,
ext4_block_bitmap(sb, gdp) - start);
if (block_cluster >= base_clusters &&
(block_cluster < itbl_cluster_start ||
block_cluster > itbl_cluster_end))
num_clusters++;
}
if (ext4_block_in_group(sb, ext4_inode_bitmap(sb, gdp), block_group)) {
inode_cluster = EXT4_B2C(sbi,
ext4_inode_bitmap(sb, gdp) - start);
/*
* Additional check if inode bitmap is in just accounted
* block_cluster
*/
if (inode_cluster != block_cluster &&
inode_cluster >= base_clusters &&
(inode_cluster < itbl_cluster_start ||
inode_cluster > itbl_cluster_end))
num_clusters++;
}
return num_clusters;
}
static unsigned int num_clusters_in_group(struct super_block *sb,
ext4_group_t block_group)
{
unsigned int blocks;
if (block_group == ext4_get_groups_count(sb) - 1) {
/*
* Even though mke2fs always initializes the first and
* last group, just in case some other tool was used,
* we need to make sure we calculate the right free
* blocks.
*/
blocks = ext4_blocks_count(EXT4_SB(sb)->s_es) -
ext4_group_first_block_no(sb, block_group);
} else
blocks = EXT4_BLOCKS_PER_GROUP(sb);
return EXT4_NUM_B2C(EXT4_SB(sb), blocks);
}
/* Initializes an uninitialized block bitmap */
static int ext4_init_block_bitmap(struct super_block *sb,
struct buffer_head *bh,
ext4_group_t block_group,
struct ext4_group_desc *gdp)
{
unsigned int bit, bit_max;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t start, tmp;
ASSERT(buffer_locked(bh));
if (!ext4_group_desc_csum_verify(sb, block_group, gdp)) {
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT |
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
return -EFSBADCRC;
}
memset(bh->b_data, 0, sb->s_blocksize);
bit_max = ext4_num_base_meta_clusters(sb, block_group);
if ((bit_max >> 3) >= bh->b_size)
return -EFSCORRUPTED;
for (bit = 0; bit < bit_max; bit++)
ext4_set_bit(bit, bh->b_data);
start = ext4_group_first_block_no(sb, block_group);
/* Set bits for block and inode bitmaps, and inode table */
tmp = ext4_block_bitmap(sb, gdp);
if (ext4_block_in_group(sb, tmp, block_group))
ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
tmp = ext4_inode_bitmap(sb, gdp);
if (ext4_block_in_group(sb, tmp, block_group))
ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
tmp = ext4_inode_table(sb, gdp);
for (; tmp < ext4_inode_table(sb, gdp) +
sbi->s_itb_per_group; tmp++) {
if (ext4_block_in_group(sb, tmp, block_group))
ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
}
/*
* Also if the number of blocks within the group is less than
* the blocksize * 8 ( which is the size of bitmap ), set rest
* of the block bitmap to 1
*/
ext4_mark_bitmap_end(num_clusters_in_group(sb, block_group),
sb->s_blocksize * 8, bh->b_data);
return 0;
}
/* Return the number of free blocks in a block group. It is used when
* the block bitmap is uninitialized, so we can't just count the bits
* in the bitmap. */
unsigned ext4_free_clusters_after_init(struct super_block *sb,
ext4_group_t block_group,
struct ext4_group_desc *gdp)
{
return num_clusters_in_group(sb, block_group) -
ext4_num_overhead_clusters(sb, block_group, gdp);
}
/*
* The free blocks are managed by bitmaps. A file system contains several
* blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap
* block for inodes, N blocks for the inode table and data blocks.
*
* The file system contains group descriptors which are located after the
* super block. Each descriptor contains the number of the bitmap block and
* the free blocks count in the block. The descriptors are loaded in memory
* when a file system is mounted (see ext4_fill_super).
*/
/**
* ext4_get_group_desc() -- load group descriptor from disk
* @sb: super block
* @block_group: given block group
* @bh: pointer to the buffer head to store the block
* group descriptor
*/
struct ext4_group_desc * ext4_get_group_desc(struct super_block *sb,
ext4_group_t block_group,
struct buffer_head **bh)
{
unsigned int group_desc;
unsigned int offset;
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct ext4_group_desc *desc;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *bh_p;
if (block_group >= ngroups) {
ext4_error(sb, "block_group >= groups_count - block_group = %u,"
" groups_count = %u", block_group, ngroups);
return NULL;
}
group_desc = block_group >> EXT4_DESC_PER_BLOCK_BITS(sb);
offset = block_group & (EXT4_DESC_PER_BLOCK(sb) - 1);
bh_p = sbi_array_rcu_deref(sbi, s_group_desc, group_desc);
/*
* sbi_array_rcu_deref returns with rcu unlocked, this is ok since
* the pointer being dereferenced won't be dereferenced again. By
* looking at the usage in add_new_gdb() the value isn't modified,
* just the pointer, and so it remains valid.
*/
if (!bh_p) {
ext4_error(sb, "Group descriptor not loaded - "
"block_group = %u, group_desc = %u, desc = %u",
block_group, group_desc, offset);
return NULL;
}
desc = (struct ext4_group_desc *)(
(__u8 *)bh_p->b_data +
offset * EXT4_DESC_SIZE(sb));
if (bh)
*bh = bh_p;
return desc;
}
static ext4_fsblk_t ext4_valid_block_bitmap_padding(struct super_block *sb,
ext4_group_t block_group,
struct buffer_head *bh)
{
ext4_grpblk_t next_zero_bit;
unsigned long bitmap_size = sb->s_blocksize * 8;
unsigned int offset = num_clusters_in_group(sb, block_group);
if (bitmap_size <= offset)
return 0;
next_zero_bit = ext4_find_next_zero_bit(bh->b_data, bitmap_size, offset);
return (next_zero_bit < bitmap_size ? next_zero_bit : 0);
}
struct ext4_group_info *ext4_get_group_info(struct super_block *sb,
ext4_group_t group)
{
struct ext4_group_info **grp_info;
long indexv, indexh;
if (unlikely(group >= EXT4_SB(sb)->s_groups_count))
return NULL;
indexv = group >> (EXT4_DESC_PER_BLOCK_BITS(sb));
indexh = group & ((EXT4_DESC_PER_BLOCK(sb)) - 1);
grp_info = sbi_array_rcu_deref(EXT4_SB(sb), s_group_info, indexv);
return grp_info[indexh];
}
/*
* Return the block number which was discovered to be invalid, or 0 if
* the block bitmap is valid.
*/
static ext4_fsblk_t ext4_valid_block_bitmap(struct super_block *sb,
struct ext4_group_desc *desc,
ext4_group_t block_group,
struct buffer_head *bh)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_grpblk_t offset;
ext4_grpblk_t next_zero_bit;
ext4_grpblk_t max_bit = EXT4_CLUSTERS_PER_GROUP(sb);
ext4_fsblk_t blk;
ext4_fsblk_t group_first_block;
if (ext4_has_feature_flex_bg(sb)) {
/* with FLEX_BG, the inode/block bitmaps and itable
* blocks may not be in the group at all
* so the bitmap validation will be skipped for those groups
* or it has to also read the block group where the bitmaps
* are located to verify they are set.
*/
return 0;
}
group_first_block = ext4_group_first_block_no(sb, block_group);
/* check whether block bitmap block number is set */
blk = ext4_block_bitmap(sb, desc);
offset = blk - group_first_block;
if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
!ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
/* bad block bitmap */
return blk;
/* check whether the inode bitmap block number is set */
blk = ext4_inode_bitmap(sb, desc);
offset = blk - group_first_block;
if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
!ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
/* bad block bitmap */
return blk;
/* check whether the inode table block number is set */
blk = ext4_inode_table(sb, desc);
offset = blk - group_first_block;
if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) >= max_bit)
return blk;
next_zero_bit = ext4_find_next_zero_bit(bh->b_data,
EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) + 1,
EXT4_B2C(sbi, offset));
if (next_zero_bit <
EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) + 1)
/* bad bitmap for inode tables */
return blk;
return 0;
}
static int ext4_validate_block_bitmap(struct super_block *sb,
struct ext4_group_desc *desc,
ext4_group_t block_group,
struct buffer_head *bh)
{
ext4_fsblk_t blk;
struct ext4_group_info *grp;
if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
return 0;
grp = ext4_get_group_info(sb, block_group);
if (buffer_verified(bh))
return 0;
if (!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
return -EFSCORRUPTED;
ext4_lock_group(sb, block_group);
if (buffer_verified(bh))
goto verified;
if (unlikely(!ext4_block_bitmap_csum_verify(sb, desc, bh) ||
ext4_simulate_fail(sb, EXT4_SIM_BBITMAP_CRC))) {
ext4_unlock_group(sb, block_group);
ext4_error(sb, "bg %u: bad block bitmap checksum", block_group);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
return -EFSBADCRC;
}
blk = ext4_valid_block_bitmap(sb, desc, block_group, bh);
if (unlikely(blk != 0)) {
ext4_unlock_group(sb, block_group);
ext4_error(sb, "bg %u: block %llu: invalid block bitmap",
block_group, blk);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
return -EFSCORRUPTED;
}
blk = ext4_valid_block_bitmap_padding(sb, block_group, bh);
if (unlikely(blk != 0)) {
ext4_unlock_group(sb, block_group);
ext4_error(sb, "bg %u: block %llu: padding at end of block bitmap is not set",
block_group, blk);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
return -EFSCORRUPTED;
}
set_buffer_verified(bh);
verified:
ext4_unlock_group(sb, block_group);
return 0;
}
/**
* ext4_read_block_bitmap_nowait()
* @sb: super block
* @block_group: given block group
* @ignore_locked: ignore locked buffers
*
* Read the bitmap for a given block_group,and validate the
* bits for block/inode/inode tables are set in the bitmaps
*
* Return buffer_head on success or an ERR_PTR in case of failure.
*/
struct buffer_head *
ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group,
bool ignore_locked)
{
struct ext4_group_desc *desc;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *bh;
ext4_fsblk_t bitmap_blk;
int err;
desc = ext4_get_group_desc(sb, block_group, NULL);
if (!desc)
return ERR_PTR(-EFSCORRUPTED);
bitmap_blk = ext4_block_bitmap(sb, desc);
if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
ext4_error(sb, "Invalid block bitmap block %llu in "
"block_group %u", bitmap_blk, block_group);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
return ERR_PTR(-EFSCORRUPTED);
}
bh = sb_getblk(sb, bitmap_blk);
if (unlikely(!bh)) {
ext4_warning(sb, "Cannot get buffer for block bitmap - "
"block_group = %u, block_bitmap = %llu",
block_group, bitmap_blk);
return ERR_PTR(-ENOMEM);
}
if (ignore_locked && buffer_locked(bh)) {
/* buffer under IO already, return if called for prefetching */
put_bh(bh);
return NULL;
}
if (bitmap_uptodate(bh))
goto verify;
lock_buffer(bh);
if (bitmap_uptodate(bh)) {
unlock_buffer(bh);
goto verify;
}
ext4_lock_group(sb, block_group);
if (ext4_has_group_desc_csum(sb) &&
(desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
if (block_group == 0) {
ext4_unlock_group(sb, block_group);
unlock_buffer(bh);
ext4_error(sb, "Block bitmap for bg 0 marked "
"uninitialized");
err = -EFSCORRUPTED;
goto out;
}
err = ext4_init_block_bitmap(sb, bh, block_group, desc);
if (err) {
ext4_unlock_group(sb, block_group);
unlock_buffer(bh);
ext4_error(sb, "Failed to init block bitmap for group "
"%u: %d", block_group, err);
goto out;
}
set_bitmap_uptodate(bh);
set_buffer_uptodate(bh);
set_buffer_verified(bh);
ext4_unlock_group(sb, block_group);
unlock_buffer(bh);
return bh;
}
ext4_unlock_group(sb, block_group);
if (buffer_uptodate(bh)) {
/*
* if not uninit if bh is uptodate,
* bitmap is also uptodate
*/
set_bitmap_uptodate(bh);
unlock_buffer(bh);
goto verify;
}
/*
* submit the buffer_head for reading
*/
set_buffer_new(bh);
trace_ext4_read_block_bitmap_load(sb, block_group, ignore_locked);
ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO |
(ignore_locked ? REQ_RAHEAD : 0),
ext4_end_bitmap_read);
return bh;
verify:
err = ext4_validate_block_bitmap(sb, desc, block_group, bh);
if (err)
goto out;
return bh;
out:
put_bh(bh);
return ERR_PTR(err);
}
/* Returns 0 on success, -errno on error */
int ext4_wait_block_bitmap(struct super_block *sb, ext4_group_t block_group,
struct buffer_head *bh)
{
struct ext4_group_desc *desc;
if (!buffer_new(bh))
return 0;
desc = ext4_get_group_desc(sb, block_group, NULL);
if (!desc)
return -EFSCORRUPTED;
wait_on_buffer(bh);
ext4_simulate_fail_bh(sb, bh, EXT4_SIM_BBITMAP_EIO);
if (!buffer_uptodate(bh)) {
ext4_error_err(sb, EIO, "Cannot read block bitmap - "
"block_group = %u, block_bitmap = %llu",
block_group, (unsigned long long) bh->b_blocknr);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
return -EIO;
}
clear_buffer_new(bh);
/* Panic or remount fs read-only if block bitmap is invalid */
return ext4_validate_block_bitmap(sb, desc, block_group, bh);
}
struct buffer_head *
ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group)
{
struct buffer_head *bh;
int err;
bh = ext4_read_block_bitmap_nowait(sb, block_group, false);
if (IS_ERR(bh))
return bh;
err = ext4_wait_block_bitmap(sb, block_group, bh);
if (err) {
put_bh(bh);
return ERR_PTR(err);
}
return bh;
}
/**
* ext4_has_free_clusters()
* @sbi: in-core super block structure.
* @nclusters: number of needed blocks
* @flags: flags from ext4_mb_new_blocks()
*
* Check if filesystem has nclusters free & available for allocation.
* On success return 1, return 0 on failure.
*/
static int ext4_has_free_clusters(struct ext4_sb_info *sbi,
s64 nclusters, unsigned int flags)
{
s64 free_clusters, dirty_clusters, rsv, resv_clusters;
struct percpu_counter *fcc = &sbi->s_freeclusters_counter;
struct percpu_counter *dcc = &sbi->s_dirtyclusters_counter;
free_clusters = percpu_counter_read_positive(fcc);
dirty_clusters = percpu_counter_read_positive(dcc);
resv_clusters = atomic64_read(&sbi->s_resv_clusters);
/*
* r_blocks_count should always be multiple of the cluster ratio so
* we are safe to do a plane bit shift only.
*/
rsv = (ext4_r_blocks_count(sbi->s_es) >> sbi->s_cluster_bits) +
resv_clusters;
if (free_clusters - (nclusters + rsv + dirty_clusters) <
EXT4_FREECLUSTERS_WATERMARK) {
free_clusters = percpu_counter_sum_positive(fcc);
dirty_clusters = percpu_counter_sum_positive(dcc);
}
/* Check whether we have space after accounting for current
* dirty clusters & root reserved clusters.
*/
if (free_clusters >= (rsv + nclusters + dirty_clusters))
return 1;
/* Hm, nope. Are (enough) root reserved clusters available? */
if (uid_eq(sbi->s_resuid, current_fsuid()) ||
(!gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) && in_group_p(sbi->s_resgid)) ||
capable(CAP_SYS_RESOURCE) ||
(flags & EXT4_MB_USE_ROOT_BLOCKS)) {
if (free_clusters >= (nclusters + dirty_clusters +
resv_clusters))
return 1;
}
/* No free blocks. Let's see if we can dip into reserved pool */
if (flags & EXT4_MB_USE_RESERVED) {
if (free_clusters >= (nclusters + dirty_clusters))
return 1;
}
return 0;
}
int ext4_claim_free_clusters(struct ext4_sb_info *sbi,
s64 nclusters, unsigned int flags)
{
if (ext4_has_free_clusters(sbi, nclusters, flags)) {
percpu_counter_add(&sbi->s_dirtyclusters_counter, nclusters);
return 0;
} else
return -ENOSPC;
}
/**
* ext4_should_retry_alloc() - check if a block allocation should be retried
* @sb: superblock
* @retries: number of retry attempts made so far
*
* ext4_should_retry_alloc() is called when ENOSPC is returned while
* attempting to allocate blocks. If there's an indication that a pending
* journal transaction might free some space and allow another attempt to
* succeed, this function will wait for the current or committing transaction
* to complete and then return TRUE.
*/
int ext4_should_retry_alloc(struct super_block *sb, int *retries)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!sbi->s_journal)
return 0;
if (++(*retries) > 3) {
percpu_counter_inc(&sbi->s_sra_exceeded_retry_limit);
return 0;
}
/*
* if there's no indication that blocks are about to be freed it's
* possible we just missed a transaction commit that did so
*/
smp_mb();
if (sbi->s_mb_free_pending == 0) {
if (test_opt(sb, DISCARD)) {
atomic_inc(&sbi->s_retry_alloc_pending);
flush_work(&sbi->s_discard_work);
atomic_dec(&sbi->s_retry_alloc_pending);
}
return ext4_has_free_clusters(sbi, 1, 0);
}
/*
* it's possible we've just missed a transaction commit here,
* so ignore the returned status
*/
ext4_debug("%s: retrying operation after ENOSPC\n", sb->s_id);
(void) jbd2_journal_force_commit_nested(sbi->s_journal);
return 1;
}
/*
* ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks
*
* @handle: handle to this transaction
* @inode: file inode
* @goal: given target block(filesystem wide)
* @count: pointer to total number of clusters needed
* @errp: error code
*
* Return 1st allocated block number on success, *count stores total account
* error stores in errp pointer
*/
ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode,
ext4_fsblk_t goal, unsigned int flags,
unsigned long *count, int *errp)
{
struct ext4_allocation_request ar;
ext4_fsblk_t ret;
memset(&ar, 0, sizeof(ar));
/* Fill with neighbour allocated blocks */
ar.inode = inode;
ar.goal = goal;
ar.len = count ? *count : 1;
ar.flags = flags;
ret = ext4_mb_new_blocks(handle, &ar, errp);
if (count)
*count = ar.len;
/*
* Account for the allocated meta blocks. We will never
* fail EDQUOT for metdata, but we do account for it.
*/
if (!(*errp) && (flags & EXT4_MB_DELALLOC_RESERVED)) {
dquot_alloc_block_nofail(inode,
EXT4_C2B(EXT4_SB(inode->i_sb), ar.len));
}
return ret;
}
/**
* ext4_count_free_clusters() -- count filesystem free clusters
* @sb: superblock
*
* Adds up the number of free clusters from each block group.
*/
ext4_fsblk_t ext4_count_free_clusters(struct super_block *sb)
{
ext4_fsblk_t desc_count;
struct ext4_group_desc *gdp;
ext4_group_t i;
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct ext4_group_info *grp;
#ifdef EXT4FS_DEBUG
struct ext4_super_block *es;
ext4_fsblk_t bitmap_count;
unsigned int x;
struct buffer_head *bitmap_bh = NULL;
es = EXT4_SB(sb)->s_es;
desc_count = 0;
bitmap_count = 0;
gdp = NULL;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
grp = NULL;
if (EXT4_SB(sb)->s_group_info)
grp = ext4_get_group_info(sb, i);
if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
desc_count += ext4_free_group_clusters(sb, gdp);
brelse(bitmap_bh);
bitmap_bh = ext4_read_block_bitmap(sb, i);
if (IS_ERR(bitmap_bh)) {
bitmap_bh = NULL;
continue;
}
x = ext4_count_free(bitmap_bh->b_data,
EXT4_CLUSTERS_PER_GROUP(sb) / 8);
printk(KERN_DEBUG "group %u: stored = %d, counted = %u\n",
i, ext4_free_group_clusters(sb, gdp), x);
bitmap_count += x;
}
brelse(bitmap_bh);
printk(KERN_DEBUG "ext4_count_free_clusters: stored = %llu"
", computed = %llu, %llu\n",
EXT4_NUM_B2C(EXT4_SB(sb), ext4_free_blocks_count(es)),
desc_count, bitmap_count);
return bitmap_count;
#else
desc_count = 0;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
grp = NULL;
if (EXT4_SB(sb)->s_group_info)
grp = ext4_get_group_info(sb, i);
if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
desc_count += ext4_free_group_clusters(sb, gdp);
}
return desc_count;
#endif
}
static inline int test_root(ext4_group_t a, int b)
{
while (1) {
if (a < b)
return 0;
if (a == b)
return 1;
if ((a % b) != 0)
return 0;
a = a / b;
}
}
/**
* ext4_bg_has_super - number of blocks used by the superblock in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the superblock (primary or backup)
* in this group. Currently this will be only 0 or 1.
*/
int ext4_bg_has_super(struct super_block *sb, ext4_group_t group)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (group == 0)
return 1;
if (ext4_has_feature_sparse_super2(sb)) {
if (group == le32_to_cpu(es->s_backup_bgs[0]) ||
group == le32_to_cpu(es->s_backup_bgs[1]))
return 1;
return 0;
}
if ((group <= 1) || !ext4_has_feature_sparse_super(sb))
return 1;
if (!(group & 1))
return 0;
if (test_root(group, 3) || (test_root(group, 5)) ||
test_root(group, 7))
return 1;
return 0;
}
static unsigned long ext4_bg_num_gdb_meta(struct super_block *sb,
ext4_group_t group)
{
unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
ext4_group_t first = metagroup * EXT4_DESC_PER_BLOCK(sb);
ext4_group_t last = first + EXT4_DESC_PER_BLOCK(sb) - 1;
if (group == first || group == first + 1 || group == last)
return 1;
return 0;
}
static unsigned long ext4_bg_num_gdb_nometa(struct super_block *sb,
ext4_group_t group)
{
if (!ext4_bg_has_super(sb, group))
return 0;
if (ext4_has_feature_meta_bg(sb))
return le32_to_cpu(EXT4_SB(sb)->s_es->s_first_meta_bg);
else
return EXT4_SB(sb)->s_gdb_count;
}
/**
* ext4_bg_num_gdb - number of blocks used by the group table in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the group descriptor table
* (primary or backup) in this group. In the future there may be a
* different number of descriptor blocks in each group.
*/
unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group)
{
unsigned long first_meta_bg =
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_meta_bg);
unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
if (!ext4_has_feature_meta_bg(sb) || metagroup < first_meta_bg)
return ext4_bg_num_gdb_nometa(sb, group);
return ext4_bg_num_gdb_meta(sb,group);
}
/*
* This function returns the number of file system metadata blocks at
* the beginning of a block group, including the reserved gdt blocks.
*/
unsigned int ext4_num_base_meta_blocks(struct super_block *sb,
ext4_group_t block_group)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned num;
/* Check for superblock and gdt backups in this group */
num = ext4_bg_has_super(sb, block_group);
if (!ext4_has_feature_meta_bg(sb) ||
block_group < le32_to_cpu(sbi->s_es->s_first_meta_bg) *
sbi->s_desc_per_block) {
if (num) {
num += ext4_bg_num_gdb_nometa(sb, block_group);
num += le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks);
}
} else { /* For META_BG_BLOCK_GROUPS */
num += ext4_bg_num_gdb_meta(sb, block_group);
}
return num;
}
static unsigned int ext4_num_base_meta_clusters(struct super_block *sb,
ext4_group_t block_group)
{
return EXT4_NUM_B2C(EXT4_SB(sb), ext4_num_base_meta_blocks(sb, block_group));
}
/**
* ext4_inode_to_goal_block - return a hint for block allocation
* @inode: inode for block allocation
*
* Return the ideal location to start allocating blocks for a
* newly created inode.
*/
ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_group_t block_group;
ext4_grpblk_t colour;
int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
ext4_fsblk_t bg_start;
ext4_fsblk_t last_block;
block_group = ei->i_block_group;
if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
/*
* If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
* block groups per flexgroup, reserve the first block
* group for directories and special files. Regular
* files will start at the second block group. This
* tends to speed up directory access and improves
* fsck times.
*/
block_group &= ~(flex_size-1);
if (S_ISREG(inode->i_mode))
block_group++;
}
bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
/*
* If we are doing delayed allocation, we don't need take
* colour into account.
*/
if (test_opt(inode->i_sb, DELALLOC))
return bg_start;
if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
colour = (task_pid_nr(current) % 16) *
(EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
else
colour = (task_pid_nr(current) % 16) *
((last_block - bg_start) / 16);
return bg_start + colour;
}
| linux-master | fs/ext4/balloc.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/xattr_trusted.c
* Handler for trusted extended attributes.
*
* Copyright (C) 2003 by Andreas Gruenbacher, <[email protected]>
*/
#include <linux/string.h>
#include <linux/capability.h>
#include <linux/fs.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
static bool
ext4_xattr_trusted_list(struct dentry *dentry)
{
return capable(CAP_SYS_ADMIN);
}
static int
ext4_xattr_trusted_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_TRUSTED,
name, buffer, size);
}
static int
ext4_xattr_trusted_set(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)
{
return ext4_xattr_set(inode, EXT4_XATTR_INDEX_TRUSTED,
name, value, size, flags);
}
const struct xattr_handler ext4_xattr_trusted_handler = {
.prefix = XATTR_TRUSTED_PREFIX,
.list = ext4_xattr_trusted_list,
.get = ext4_xattr_trusted_get,
.set = ext4_xattr_trusted_set,
};
| linux-master | fs/ext4/xattr_trusted.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2003-2006, Cluster File Systems, Inc, [email protected]
* Written by Alex Tomas <[email protected]>
*/
/*
* mballoc.c contains the multiblocks allocation routines
*/
#include "ext4_jbd2.h"
#include "mballoc.h"
#include <linux/log2.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/nospec.h>
#include <linux/backing-dev.h>
#include <linux/freezer.h>
#include <trace/events/ext4.h>
/*
* MUSTDO:
* - test ext4_ext_search_left() and ext4_ext_search_right()
* - search for metadata in few groups
*
* TODO v4:
* - normalization should take into account whether file is still open
* - discard preallocations if no free space left (policy?)
* - don't normalize tails
* - quota
* - reservation for superuser
*
* TODO v3:
* - bitmap read-ahead (proposed by Oleg Drokin aka green)
* - track min/max extents in each group for better group selection
* - mb_mark_used() may allocate chunk right after splitting buddy
* - tree of groups sorted by number of free blocks
* - error handling
*/
/*
* The allocation request involve request for multiple number of blocks
* near to the goal(block) value specified.
*
* During initialization phase of the allocator we decide to use the
* group preallocation or inode preallocation depending on the size of
* the file. The size of the file could be the resulting file size we
* would have after allocation, or the current file size, which ever
* is larger. If the size is less than sbi->s_mb_stream_request we
* select to use the group preallocation. The default value of
* s_mb_stream_request is 16 blocks. This can also be tuned via
* /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
* terms of number of blocks.
*
* The main motivation for having small file use group preallocation is to
* ensure that we have small files closer together on the disk.
*
* First stage the allocator looks at the inode prealloc list,
* ext4_inode_info->i_prealloc_list, which contains list of prealloc
* spaces for this particular inode. The inode prealloc space is
* represented as:
*
* pa_lstart -> the logical start block for this prealloc space
* pa_pstart -> the physical start block for this prealloc space
* pa_len -> length for this prealloc space (in clusters)
* pa_free -> free space available in this prealloc space (in clusters)
*
* The inode preallocation space is used looking at the _logical_ start
* block. If only the logical file block falls within the range of prealloc
* space we will consume the particular prealloc space. This makes sure that
* we have contiguous physical blocks representing the file blocks
*
* The important thing to be noted in case of inode prealloc space is that
* we don't modify the values associated to inode prealloc space except
* pa_free.
*
* If we are not able to find blocks in the inode prealloc space and if we
* have the group allocation flag set then we look at the locality group
* prealloc space. These are per CPU prealloc list represented as
*
* ext4_sb_info.s_locality_groups[smp_processor_id()]
*
* The reason for having a per cpu locality group is to reduce the contention
* between CPUs. It is possible to get scheduled at this point.
*
* The locality group prealloc space is used looking at whether we have
* enough free space (pa_free) within the prealloc space.
*
* If we can't allocate blocks via inode prealloc or/and locality group
* prealloc then we look at the buddy cache. The buddy cache is represented
* by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
* mapped to the buddy and bitmap information regarding different
* groups. The buddy information is attached to buddy cache inode so that
* we can access them through the page cache. The information regarding
* each group is loaded via ext4_mb_load_buddy. The information involve
* block bitmap and buddy information. The information are stored in the
* inode as:
*
* { page }
* [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
*
*
* one block each for bitmap and buddy information. So for each group we
* take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
* blocksize) blocks. So it can have information regarding groups_per_page
* which is blocks_per_page/2
*
* The buddy cache inode is not stored on disk. The inode is thrown
* away when the filesystem is unmounted.
*
* We look for count number of blocks in the buddy cache. If we were able
* to locate that many free blocks we return with additional information
* regarding rest of the contiguous physical block available
*
* Before allocating blocks via buddy cache we normalize the request
* blocks. This ensure we ask for more blocks that we needed. The extra
* blocks that we get after allocation is added to the respective prealloc
* list. In case of inode preallocation we follow a list of heuristics
* based on file size. This can be found in ext4_mb_normalize_request. If
* we are doing a group prealloc we try to normalize the request to
* sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
* dependent on the cluster size; for non-bigalloc file systems, it is
* 512 blocks. This can be tuned via
* /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
* terms of number of blocks. If we have mounted the file system with -O
* stripe=<value> option the group prealloc request is normalized to the
* smallest multiple of the stripe value (sbi->s_stripe) which is
* greater than the default mb_group_prealloc.
*
* If "mb_optimize_scan" mount option is set, we maintain in memory group info
* structures in two data structures:
*
* 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
*
* Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
*
* This is an array of lists where the index in the array represents the
* largest free order in the buddy bitmap of the participating group infos of
* that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
* number of buddy bitmap orders possible) number of lists. Group-infos are
* placed in appropriate lists.
*
* 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
*
* Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
*
* This is an array of lists where in the i-th list there are groups with
* average fragment size >= 2^i and < 2^(i+1). The average fragment size
* is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
* Note that we don't bother with a special list for completely empty groups
* so we only have MB_NUM_ORDERS(sb) lists.
*
* When "mb_optimize_scan" mount option is set, mballoc consults the above data
* structures to decide the order in which groups are to be traversed for
* fulfilling an allocation request.
*
* At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
* >= the order of the request. We directly look at the largest free order list
* in the data structure (1) above where largest_free_order = order of the
* request. If that list is empty, we look at remaining list in the increasing
* order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
* lookup in O(1) time.
*
* At CR_GOAL_LEN_FAST, we only consider groups where
* average fragment size > request size. So, we lookup a group which has average
* fragment size just above or equal to request size using our average fragment
* size group lists (data structure 2) in O(1) time.
*
* At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
* in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
* CR_GOAL_LEN_FAST suggests that there is no BG that has avg
* fragment size > goal length. So before falling to the slower
* CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
* then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
* enough average fragment size. This increases the chances of finding a
* suitable block group in O(1) time and results in faster allocation at the
* cost of reduced size of allocation.
*
* If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
* linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
* CR_GOAL_LEN_FAST phase.
*
* The regular allocator (using the buddy cache) supports a few tunables.
*
* /sys/fs/ext4/<partition>/mb_min_to_scan
* /sys/fs/ext4/<partition>/mb_max_to_scan
* /sys/fs/ext4/<partition>/mb_order2_req
* /sys/fs/ext4/<partition>/mb_linear_limit
*
* The regular allocator uses buddy scan only if the request len is power of
* 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
* value of s_mb_order2_reqs can be tuned via
* /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
* stripe size (sbi->s_stripe), we try to search for contiguous block in
* stripe size. This should result in better allocation on RAID setups. If
* not, we search in the specific group using bitmap for best extents. The
* tunable min_to_scan and max_to_scan control the behaviour here.
* min_to_scan indicate how long the mballoc __must__ look for a best
* extent and max_to_scan indicates how long the mballoc __can__ look for a
* best extent in the found extents. Searching for the blocks starts with
* the group specified as the goal value in allocation context via
* ac_g_ex. Each group is first checked based on the criteria whether it
* can be used for allocation. ext4_mb_good_group explains how the groups are
* checked.
*
* When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
* get traversed linearly. That may result in subsequent allocations being not
* close to each other. And so, the underlying device may get filled up in a
* non-linear fashion. While that may not matter on non-rotational devices, for
* rotational devices that may result in higher seek times. "mb_linear_limit"
* tells mballoc how many groups mballoc should search linearly before
* performing consulting above data structures for more efficient lookups. For
* non rotational devices, this value defaults to 0 and for rotational devices
* this is set to MB_DEFAULT_LINEAR_LIMIT.
*
* Both the prealloc space are getting populated as above. So for the first
* request we will hit the buddy cache which will result in this prealloc
* space getting filled. The prealloc space is then later used for the
* subsequent request.
*/
/*
* mballoc operates on the following data:
* - on-disk bitmap
* - in-core buddy (actually includes buddy and bitmap)
* - preallocation descriptors (PAs)
*
* there are two types of preallocations:
* - inode
* assiged to specific inode and can be used for this inode only.
* it describes part of inode's space preallocated to specific
* physical blocks. any block from that preallocated can be used
* independent. the descriptor just tracks number of blocks left
* unused. so, before taking some block from descriptor, one must
* make sure corresponded logical block isn't allocated yet. this
* also means that freeing any block within descriptor's range
* must discard all preallocated blocks.
* - locality group
* assigned to specific locality group which does not translate to
* permanent set of inodes: inode can join and leave group. space
* from this type of preallocation can be used for any inode. thus
* it's consumed from the beginning to the end.
*
* relation between them can be expressed as:
* in-core buddy = on-disk bitmap + preallocation descriptors
*
* this mean blocks mballoc considers used are:
* - allocated blocks (persistent)
* - preallocated blocks (non-persistent)
*
* consistency in mballoc world means that at any time a block is either
* free or used in ALL structures. notice: "any time" should not be read
* literally -- time is discrete and delimited by locks.
*
* to keep it simple, we don't use block numbers, instead we count number of
* blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
*
* all operations can be expressed as:
* - init buddy: buddy = on-disk + PAs
* - new PA: buddy += N; PA = N
* - use inode PA: on-disk += N; PA -= N
* - discard inode PA buddy -= on-disk - PA; PA = 0
* - use locality group PA on-disk += N; PA -= N
* - discard locality group PA buddy -= PA; PA = 0
* note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
* is used in real operation because we can't know actual used
* bits from PA, only from on-disk bitmap
*
* if we follow this strict logic, then all operations above should be atomic.
* given some of them can block, we'd have to use something like semaphores
* killing performance on high-end SMP hardware. let's try to relax it using
* the following knowledge:
* 1) if buddy is referenced, it's already initialized
* 2) while block is used in buddy and the buddy is referenced,
* nobody can re-allocate that block
* 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
* bit set and PA claims same block, it's OK. IOW, one can set bit in
* on-disk bitmap if buddy has same bit set or/and PA covers corresponded
* block
*
* so, now we're building a concurrency table:
* - init buddy vs.
* - new PA
* blocks for PA are allocated in the buddy, buddy must be referenced
* until PA is linked to allocation group to avoid concurrent buddy init
* - use inode PA
* we need to make sure that either on-disk bitmap or PA has uptodate data
* given (3) we care that PA-=N operation doesn't interfere with init
* - discard inode PA
* the simplest way would be to have buddy initialized by the discard
* - use locality group PA
* again PA-=N must be serialized with init
* - discard locality group PA
* the simplest way would be to have buddy initialized by the discard
* - new PA vs.
* - use inode PA
* i_data_sem serializes them
* - discard inode PA
* discard process must wait until PA isn't used by another process
* - use locality group PA
* some mutex should serialize them
* - discard locality group PA
* discard process must wait until PA isn't used by another process
* - use inode PA
* - use inode PA
* i_data_sem or another mutex should serializes them
* - discard inode PA
* discard process must wait until PA isn't used by another process
* - use locality group PA
* nothing wrong here -- they're different PAs covering different blocks
* - discard locality group PA
* discard process must wait until PA isn't used by another process
*
* now we're ready to make few consequences:
* - PA is referenced and while it is no discard is possible
* - PA is referenced until block isn't marked in on-disk bitmap
* - PA changes only after on-disk bitmap
* - discard must not compete with init. either init is done before
* any discard or they're serialized somehow
* - buddy init as sum of on-disk bitmap and PAs is done atomically
*
* a special case when we've used PA to emptiness. no need to modify buddy
* in this case, but we should care about concurrent init
*
*/
/*
* Logic in few words:
*
* - allocation:
* load group
* find blocks
* mark bits in on-disk bitmap
* release group
*
* - use preallocation:
* find proper PA (per-inode or group)
* load group
* mark bits in on-disk bitmap
* release group
* release PA
*
* - free:
* load group
* mark bits in on-disk bitmap
* release group
*
* - discard preallocations in group:
* mark PAs deleted
* move them onto local list
* load on-disk bitmap
* load group
* remove PA from object (inode or locality group)
* mark free blocks in-core
*
* - discard inode's preallocations:
*/
/*
* Locking rules
*
* Locks:
* - bitlock on a group (group)
* - object (inode/locality) (object)
* - per-pa lock (pa)
* - cr_power2_aligned lists lock (cr_power2_aligned)
* - cr_goal_len_fast lists lock (cr_goal_len_fast)
*
* Paths:
* - new pa
* object
* group
*
* - find and use pa:
* pa
*
* - release consumed pa:
* pa
* group
* object
*
* - generate in-core bitmap:
* group
* pa
*
* - discard all for given object (inode, locality group):
* object
* pa
* group
*
* - discard all for given group:
* group
* pa
* group
* object
*
* - allocation path (ext4_mb_regular_allocator)
* group
* cr_power2_aligned/cr_goal_len_fast
*/
static struct kmem_cache *ext4_pspace_cachep;
static struct kmem_cache *ext4_ac_cachep;
static struct kmem_cache *ext4_free_data_cachep;
/* We create slab caches for groupinfo data structures based on the
* superblock block size. There will be one per mounted filesystem for
* each unique s_blocksize_bits */
#define NR_GRPINFO_CACHES 8
static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
"ext4_groupinfo_64k", "ext4_groupinfo_128k"
};
static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
ext4_group_t group);
static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
ext4_group_t group);
static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
ext4_group_t group, enum criteria cr);
static int ext4_try_to_trim_range(struct super_block *sb,
struct ext4_buddy *e4b, ext4_grpblk_t start,
ext4_grpblk_t max, ext4_grpblk_t minblocks);
/*
* The algorithm using this percpu seq counter goes below:
* 1. We sample the percpu discard_pa_seq counter before trying for block
* allocation in ext4_mb_new_blocks().
* 2. We increment this percpu discard_pa_seq counter when we either allocate
* or free these blocks i.e. while marking those blocks as used/free in
* mb_mark_used()/mb_free_blocks().
* 3. We also increment this percpu seq counter when we successfully identify
* that the bb_prealloc_list is not empty and hence proceed for discarding
* of those PAs inside ext4_mb_discard_group_preallocations().
*
* Now to make sure that the regular fast path of block allocation is not
* affected, as a small optimization we only sample the percpu seq counter
* on that cpu. Only when the block allocation fails and when freed blocks
* found were 0, that is when we sample percpu seq counter for all cpus using
* below function ext4_get_discard_pa_seq_sum(). This happens after making
* sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
*/
static DEFINE_PER_CPU(u64, discard_pa_seq);
static inline u64 ext4_get_discard_pa_seq_sum(void)
{
int __cpu;
u64 __seq = 0;
for_each_possible_cpu(__cpu)
__seq += per_cpu(discard_pa_seq, __cpu);
return __seq;
}
static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
{
#if BITS_PER_LONG == 64
*bit += ((unsigned long) addr & 7UL) << 3;
addr = (void *) ((unsigned long) addr & ~7UL);
#elif BITS_PER_LONG == 32
*bit += ((unsigned long) addr & 3UL) << 3;
addr = (void *) ((unsigned long) addr & ~3UL);
#else
#error "how many bits you are?!"
#endif
return addr;
}
static inline int mb_test_bit(int bit, void *addr)
{
/*
* ext4_test_bit on architecture like powerpc
* needs unsigned long aligned address
*/
addr = mb_correct_addr_and_bit(&bit, addr);
return ext4_test_bit(bit, addr);
}
static inline void mb_set_bit(int bit, void *addr)
{
addr = mb_correct_addr_and_bit(&bit, addr);
ext4_set_bit(bit, addr);
}
static inline void mb_clear_bit(int bit, void *addr)
{
addr = mb_correct_addr_and_bit(&bit, addr);
ext4_clear_bit(bit, addr);
}
static inline int mb_test_and_clear_bit(int bit, void *addr)
{
addr = mb_correct_addr_and_bit(&bit, addr);
return ext4_test_and_clear_bit(bit, addr);
}
static inline int mb_find_next_zero_bit(void *addr, int max, int start)
{
int fix = 0, ret, tmpmax;
addr = mb_correct_addr_and_bit(&fix, addr);
tmpmax = max + fix;
start += fix;
ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
if (ret > max)
return max;
return ret;
}
static inline int mb_find_next_bit(void *addr, int max, int start)
{
int fix = 0, ret, tmpmax;
addr = mb_correct_addr_and_bit(&fix, addr);
tmpmax = max + fix;
start += fix;
ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
if (ret > max)
return max;
return ret;
}
static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
{
char *bb;
BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
BUG_ON(max == NULL);
if (order > e4b->bd_blkbits + 1) {
*max = 0;
return NULL;
}
/* at order 0 we see each particular block */
if (order == 0) {
*max = 1 << (e4b->bd_blkbits + 3);
return e4b->bd_bitmap;
}
bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
return bb;
}
#ifdef DOUBLE_CHECK
static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
int first, int count)
{
int i;
struct super_block *sb = e4b->bd_sb;
if (unlikely(e4b->bd_info->bb_bitmap == NULL))
return;
assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
for (i = 0; i < count; i++) {
if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
ext4_fsblk_t blocknr;
blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
ext4_grp_locked_error(sb, e4b->bd_group,
inode ? inode->i_ino : 0,
blocknr,
"freeing block already freed "
"(bit %u)",
first + i);
ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
}
mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
}
}
static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
{
int i;
if (unlikely(e4b->bd_info->bb_bitmap == NULL))
return;
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
for (i = 0; i < count; i++) {
BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
}
}
static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
{
if (unlikely(e4b->bd_info->bb_bitmap == NULL))
return;
if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
unsigned char *b1, *b2;
int i;
b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
b2 = (unsigned char *) bitmap;
for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
if (b1[i] != b2[i]) {
ext4_msg(e4b->bd_sb, KERN_ERR,
"corruption in group %u "
"at byte %u(%u): %x in copy != %x "
"on disk/prealloc",
e4b->bd_group, i, i * 8, b1[i], b2[i]);
BUG();
}
}
}
}
static void mb_group_bb_bitmap_alloc(struct super_block *sb,
struct ext4_group_info *grp, ext4_group_t group)
{
struct buffer_head *bh;
grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
if (!grp->bb_bitmap)
return;
bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR_OR_NULL(bh)) {
kfree(grp->bb_bitmap);
grp->bb_bitmap = NULL;
return;
}
memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
put_bh(bh);
}
static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
{
kfree(grp->bb_bitmap);
}
#else
static inline void mb_free_blocks_double(struct inode *inode,
struct ext4_buddy *e4b, int first, int count)
{
return;
}
static inline void mb_mark_used_double(struct ext4_buddy *e4b,
int first, int count)
{
return;
}
static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
{
return;
}
static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
struct ext4_group_info *grp, ext4_group_t group)
{
return;
}
static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
{
return;
}
#endif
#ifdef AGGRESSIVE_CHECK
#define MB_CHECK_ASSERT(assert) \
do { \
if (!(assert)) { \
printk(KERN_EMERG \
"Assertion failure in %s() at %s:%d: \"%s\"\n", \
function, file, line, # assert); \
BUG(); \
} \
} while (0)
static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
const char *function, int line)
{
struct super_block *sb = e4b->bd_sb;
int order = e4b->bd_blkbits + 1;
int max;
int max2;
int i;
int j;
int k;
int count;
struct ext4_group_info *grp;
int fragments = 0;
int fstart;
struct list_head *cur;
void *buddy;
void *buddy2;
if (e4b->bd_info->bb_check_counter++ % 10)
return 0;
while (order > 1) {
buddy = mb_find_buddy(e4b, order, &max);
MB_CHECK_ASSERT(buddy);
buddy2 = mb_find_buddy(e4b, order - 1, &max2);
MB_CHECK_ASSERT(buddy2);
MB_CHECK_ASSERT(buddy != buddy2);
MB_CHECK_ASSERT(max * 2 == max2);
count = 0;
for (i = 0; i < max; i++) {
if (mb_test_bit(i, buddy)) {
/* only single bit in buddy2 may be 0 */
if (!mb_test_bit(i << 1, buddy2)) {
MB_CHECK_ASSERT(
mb_test_bit((i<<1)+1, buddy2));
}
continue;
}
/* both bits in buddy2 must be 1 */
MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
for (j = 0; j < (1 << order); j++) {
k = (i * (1 << order)) + j;
MB_CHECK_ASSERT(
!mb_test_bit(k, e4b->bd_bitmap));
}
count++;
}
MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
order--;
}
fstart = -1;
buddy = mb_find_buddy(e4b, 0, &max);
for (i = 0; i < max; i++) {
if (!mb_test_bit(i, buddy)) {
MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
if (fstart == -1) {
fragments++;
fstart = i;
}
continue;
}
fstart = -1;
/* check used bits only */
for (j = 0; j < e4b->bd_blkbits + 1; j++) {
buddy2 = mb_find_buddy(e4b, j, &max2);
k = i >> j;
MB_CHECK_ASSERT(k < max2);
MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
}
}
MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
grp = ext4_get_group_info(sb, e4b->bd_group);
if (!grp)
return NULL;
list_for_each(cur, &grp->bb_prealloc_list) {
ext4_group_t groupnr;
struct ext4_prealloc_space *pa;
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
MB_CHECK_ASSERT(groupnr == e4b->bd_group);
for (i = 0; i < pa->pa_len; i++)
MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
}
return 0;
}
#undef MB_CHECK_ASSERT
#define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
__FILE__, __func__, __LINE__)
#else
#define mb_check_buddy(e4b)
#endif
/*
* Divide blocks started from @first with length @len into
* smaller chunks with power of 2 blocks.
* Clear the bits in bitmap which the blocks of the chunk(s) covered,
* then increase bb_counters[] for corresponded chunk size.
*/
static void ext4_mb_mark_free_simple(struct super_block *sb,
void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
struct ext4_group_info *grp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_grpblk_t min;
ext4_grpblk_t max;
ext4_grpblk_t chunk;
unsigned int border;
BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
border = 2 << sb->s_blocksize_bits;
while (len > 0) {
/* find how many blocks can be covered since this position */
max = ffs(first | border) - 1;
/* find how many blocks of power 2 we need to mark */
min = fls(len) - 1;
if (max < min)
min = max;
chunk = 1 << min;
/* mark multiblock chunks only */
grp->bb_counters[min]++;
if (min > 0)
mb_clear_bit(first >> min,
buddy + sbi->s_mb_offsets[min]);
len -= chunk;
first += chunk;
}
}
static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
{
int order;
/*
* We don't bother with a special lists groups with only 1 block free
* extents and for completely empty groups.
*/
order = fls(len) - 2;
if (order < 0)
return 0;
if (order == MB_NUM_ORDERS(sb))
order--;
return order;
}
/* Move group to appropriate avg_fragment_size list */
static void
mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int new_order;
if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
return;
new_order = mb_avg_fragment_size_order(sb,
grp->bb_free / grp->bb_fragments);
if (new_order == grp->bb_avg_fragment_size_order)
return;
if (grp->bb_avg_fragment_size_order != -1) {
write_lock(&sbi->s_mb_avg_fragment_size_locks[
grp->bb_avg_fragment_size_order]);
list_del(&grp->bb_avg_fragment_size_node);
write_unlock(&sbi->s_mb_avg_fragment_size_locks[
grp->bb_avg_fragment_size_order]);
}
grp->bb_avg_fragment_size_order = new_order;
write_lock(&sbi->s_mb_avg_fragment_size_locks[
grp->bb_avg_fragment_size_order]);
list_add_tail(&grp->bb_avg_fragment_size_node,
&sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
write_unlock(&sbi->s_mb_avg_fragment_size_locks[
grp->bb_avg_fragment_size_order]);
}
/*
* Choose next group by traversing largest_free_order lists. Updates *new_cr if
* cr level needs an update.
*/
static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_group_info *iter;
int i;
if (ac->ac_status == AC_STATUS_FOUND)
return;
if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
atomic_inc(&sbi->s_bal_p2_aligned_bad_suggestions);
for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
if (list_empty(&sbi->s_mb_largest_free_orders[i]))
continue;
read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
continue;
}
list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
bb_largest_free_order_node) {
if (sbi->s_mb_stats)
atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
*group = iter->bb_group;
ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
return;
}
}
read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
}
/* Increment cr and search again if no group is found */
*new_cr = CR_GOAL_LEN_FAST;
}
/*
* Find a suitable group of given order from the average fragments list.
*/
static struct ext4_group_info *
ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
struct ext4_group_info *grp = NULL, *iter;
enum criteria cr = ac->ac_criteria;
if (list_empty(frag_list))
return NULL;
read_lock(frag_list_lock);
if (list_empty(frag_list)) {
read_unlock(frag_list_lock);
return NULL;
}
list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
if (sbi->s_mb_stats)
atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
grp = iter;
break;
}
}
read_unlock(frag_list_lock);
return grp;
}
/*
* Choose next group by traversing average fragment size list of suitable
* order. Updates *new_cr if cr level needs an update.
*/
static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_group_info *grp = NULL;
int i;
if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
if (sbi->s_mb_stats)
atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
}
for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
i < MB_NUM_ORDERS(ac->ac_sb); i++) {
grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
if (grp) {
*group = grp->bb_group;
ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
return;
}
}
/*
* CR_BEST_AVAIL_LEN works based on the concept that we have
* a larger normalized goal len request which can be trimmed to
* a smaller goal len such that it can still satisfy original
* request len. However, allocation request for non-regular
* files never gets normalized.
* See function ext4_mb_normalize_request() (EXT4_MB_HINT_DATA).
*/
if (ac->ac_flags & EXT4_MB_HINT_DATA)
*new_cr = CR_BEST_AVAIL_LEN;
else
*new_cr = CR_GOAL_LEN_SLOW;
}
/*
* We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
* order we have and proactively trim the goal request length to that order to
* find a suitable group faster.
*
* This optimizes allocation speed at the cost of slightly reduced
* preallocations. However, we make sure that we don't trim the request too
* much and fall to CR_GOAL_LEN_SLOW in that case.
*/
static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_group_info *grp = NULL;
int i, order, min_order;
unsigned long num_stripe_clusters = 0;
if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
if (sbi->s_mb_stats)
atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
}
/*
* mb_avg_fragment_size_order() returns order in a way that makes
* retrieving back the length using (1 << order) inaccurate. Hence, use
* fls() instead since we need to know the actual length while modifying
* goal length.
*/
order = fls(ac->ac_g_ex.fe_len) - 1;
min_order = order - sbi->s_mb_best_avail_max_trim_order;
if (min_order < 0)
min_order = 0;
if (sbi->s_stripe > 0) {
/*
* We are assuming that stripe size is always a multiple of
* cluster ratio otherwise __ext4_fill_super exists early.
*/
num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
if (1 << min_order < num_stripe_clusters)
/*
* We consider 1 order less because later we round
* up the goal len to num_stripe_clusters
*/
min_order = fls(num_stripe_clusters) - 1;
}
if (1 << min_order < ac->ac_o_ex.fe_len)
min_order = fls(ac->ac_o_ex.fe_len);
for (i = order; i >= min_order; i--) {
int frag_order;
/*
* Scale down goal len to make sure we find something
* in the free fragments list. Basically, reduce
* preallocations.
*/
ac->ac_g_ex.fe_len = 1 << i;
if (num_stripe_clusters > 0) {
/*
* Try to round up the adjusted goal length to
* stripe size (in cluster units) multiple for
* efficiency.
*/
ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
num_stripe_clusters);
}
frag_order = mb_avg_fragment_size_order(ac->ac_sb,
ac->ac_g_ex.fe_len);
grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
if (grp) {
*group = grp->bb_group;
ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
return;
}
}
/* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
*new_cr = CR_GOAL_LEN_SLOW;
}
static inline int should_optimize_scan(struct ext4_allocation_context *ac)
{
if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
return 0;
if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
return 0;
if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
return 0;
return 1;
}
/*
* Return next linear group for allocation. If linear traversal should not be
* performed, this function just returns the same group
*/
static ext4_group_t
next_linear_group(struct ext4_allocation_context *ac, ext4_group_t group,
ext4_group_t ngroups)
{
if (!should_optimize_scan(ac))
goto inc_and_return;
if (ac->ac_groups_linear_remaining) {
ac->ac_groups_linear_remaining--;
goto inc_and_return;
}
return group;
inc_and_return:
/*
* Artificially restricted ngroups for non-extent
* files makes group > ngroups possible on first loop.
*/
return group + 1 >= ngroups ? 0 : group + 1;
}
/*
* ext4_mb_choose_next_group: choose next group for allocation.
*
* @ac Allocation Context
* @new_cr This is an output parameter. If the there is no good group
* available at current CR level, this field is updated to indicate
* the new cr level that should be used.
* @group This is an input / output parameter. As an input it indicates the
* next group that the allocator intends to use for allocation. As
* output, this field indicates the next group that should be used as
* determined by the optimization functions.
* @ngroups Total number of groups
*/
static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
{
*new_cr = ac->ac_criteria;
if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
*group = next_linear_group(ac, *group, ngroups);
return;
}
if (*new_cr == CR_POWER2_ALIGNED) {
ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group, ngroups);
} else if (*new_cr == CR_GOAL_LEN_FAST) {
ext4_mb_choose_next_group_goal_fast(ac, new_cr, group, ngroups);
} else if (*new_cr == CR_BEST_AVAIL_LEN) {
ext4_mb_choose_next_group_best_avail(ac, new_cr, group, ngroups);
} else {
/*
* TODO: For CR=2, we can arrange groups in an rb tree sorted by
* bb_free. But until that happens, we should never come here.
*/
WARN_ON(1);
}
}
/*
* Cache the order of the largest free extent we have available in this block
* group.
*/
static void
mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int i;
for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
if (grp->bb_counters[i] > 0)
break;
/* No need to move between order lists? */
if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
i == grp->bb_largest_free_order) {
grp->bb_largest_free_order = i;
return;
}
if (grp->bb_largest_free_order >= 0) {
write_lock(&sbi->s_mb_largest_free_orders_locks[
grp->bb_largest_free_order]);
list_del_init(&grp->bb_largest_free_order_node);
write_unlock(&sbi->s_mb_largest_free_orders_locks[
grp->bb_largest_free_order]);
}
grp->bb_largest_free_order = i;
if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
write_lock(&sbi->s_mb_largest_free_orders_locks[
grp->bb_largest_free_order]);
list_add_tail(&grp->bb_largest_free_order_node,
&sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
write_unlock(&sbi->s_mb_largest_free_orders_locks[
grp->bb_largest_free_order]);
}
}
static noinline_for_stack
void ext4_mb_generate_buddy(struct super_block *sb,
void *buddy, void *bitmap, ext4_group_t group,
struct ext4_group_info *grp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
ext4_grpblk_t i = 0;
ext4_grpblk_t first;
ext4_grpblk_t len;
unsigned free = 0;
unsigned fragments = 0;
unsigned long long period = get_cycles();
/* initialize buddy from bitmap which is aggregation
* of on-disk bitmap and preallocations */
i = mb_find_next_zero_bit(bitmap, max, 0);
grp->bb_first_free = i;
while (i < max) {
fragments++;
first = i;
i = mb_find_next_bit(bitmap, max, i);
len = i - first;
free += len;
if (len > 1)
ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
else
grp->bb_counters[0]++;
if (i < max)
i = mb_find_next_zero_bit(bitmap, max, i);
}
grp->bb_fragments = fragments;
if (free != grp->bb_free) {
ext4_grp_locked_error(sb, group, 0, 0,
"block bitmap and bg descriptor "
"inconsistent: %u vs %u free clusters",
free, grp->bb_free);
/*
* If we intend to continue, we consider group descriptor
* corrupt and update bb_free using bitmap value
*/
grp->bb_free = free;
ext4_mark_group_bitmap_corrupted(sb, group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
}
mb_set_largest_free_order(sb, grp);
mb_update_avg_fragment_size(sb, grp);
clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
period = get_cycles() - period;
atomic_inc(&sbi->s_mb_buddies_generated);
atomic64_add(period, &sbi->s_mb_generation_time);
}
/* The buddy information is attached the buddy cache inode
* for convenience. The information regarding each group
* is loaded via ext4_mb_load_buddy. The information involve
* block bitmap and buddy information. The information are
* stored in the inode as
*
* { page }
* [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
*
*
* one block each for bitmap and buddy information.
* So for each group we take up 2 blocks. A page can
* contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
* So it can have information regarding groups_per_page which
* is blocks_per_page/2
*
* Locking note: This routine takes the block group lock of all groups
* for this page; do not hold this lock when calling this routine!
*/
static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
{
ext4_group_t ngroups;
unsigned int blocksize;
int blocks_per_page;
int groups_per_page;
int err = 0;
int i;
ext4_group_t first_group, group;
int first_block;
struct super_block *sb;
struct buffer_head *bhs;
struct buffer_head **bh = NULL;
struct inode *inode;
char *data;
char *bitmap;
struct ext4_group_info *grinfo;
inode = page->mapping->host;
sb = inode->i_sb;
ngroups = ext4_get_groups_count(sb);
blocksize = i_blocksize(inode);
blocks_per_page = PAGE_SIZE / blocksize;
mb_debug(sb, "init page %lu\n", page->index);
groups_per_page = blocks_per_page >> 1;
if (groups_per_page == 0)
groups_per_page = 1;
/* allocate buffer_heads to read bitmaps */
if (groups_per_page > 1) {
i = sizeof(struct buffer_head *) * groups_per_page;
bh = kzalloc(i, gfp);
if (bh == NULL)
return -ENOMEM;
} else
bh = &bhs;
first_group = page->index * blocks_per_page / 2;
/* read all groups the page covers into the cache */
for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
if (group >= ngroups)
break;
grinfo = ext4_get_group_info(sb, group);
if (!grinfo)
continue;
/*
* If page is uptodate then we came here after online resize
* which added some new uninitialized group info structs, so
* we must skip all initialized uptodate buddies on the page,
* which may be currently in use by an allocating task.
*/
if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
bh[i] = NULL;
continue;
}
bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
if (IS_ERR(bh[i])) {
err = PTR_ERR(bh[i]);
bh[i] = NULL;
goto out;
}
mb_debug(sb, "read bitmap for group %u\n", group);
}
/* wait for I/O completion */
for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
int err2;
if (!bh[i])
continue;
err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
if (!err)
err = err2;
}
first_block = page->index * blocks_per_page;
for (i = 0; i < blocks_per_page; i++) {
group = (first_block + i) >> 1;
if (group >= ngroups)
break;
if (!bh[group - first_group])
/* skip initialized uptodate buddy */
continue;
if (!buffer_verified(bh[group - first_group]))
/* Skip faulty bitmaps */
continue;
err = 0;
/*
* data carry information regarding this
* particular group in the format specified
* above
*
*/
data = page_address(page) + (i * blocksize);
bitmap = bh[group - first_group]->b_data;
/*
* We place the buddy block and bitmap block
* close together
*/
if ((first_block + i) & 1) {
/* this is block of buddy */
BUG_ON(incore == NULL);
mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
group, page->index, i * blocksize);
trace_ext4_mb_buddy_bitmap_load(sb, group);
grinfo = ext4_get_group_info(sb, group);
if (!grinfo) {
err = -EFSCORRUPTED;
goto out;
}
grinfo->bb_fragments = 0;
memset(grinfo->bb_counters, 0,
sizeof(*grinfo->bb_counters) *
(MB_NUM_ORDERS(sb)));
/*
* incore got set to the group block bitmap below
*/
ext4_lock_group(sb, group);
/* init the buddy */
memset(data, 0xff, blocksize);
ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
ext4_unlock_group(sb, group);
incore = NULL;
} else {
/* this is block of bitmap */
BUG_ON(incore != NULL);
mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
group, page->index, i * blocksize);
trace_ext4_mb_bitmap_load(sb, group);
/* see comments in ext4_mb_put_pa() */
ext4_lock_group(sb, group);
memcpy(data, bitmap, blocksize);
/* mark all preallocated blks used in in-core bitmap */
ext4_mb_generate_from_pa(sb, data, group);
ext4_mb_generate_from_freelist(sb, data, group);
ext4_unlock_group(sb, group);
/* set incore so that the buddy information can be
* generated using this
*/
incore = data;
}
}
SetPageUptodate(page);
out:
if (bh) {
for (i = 0; i < groups_per_page; i++)
brelse(bh[i]);
if (bh != &bhs)
kfree(bh);
}
return err;
}
/*
* Lock the buddy and bitmap pages. This make sure other parallel init_group
* on the same buddy page doesn't happen whild holding the buddy page lock.
* Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
* are on the same page e4b->bd_buddy_page is NULL and return value is 0.
*/
static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
{
struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
int block, pnum, poff;
int blocks_per_page;
struct page *page;
e4b->bd_buddy_page = NULL;
e4b->bd_bitmap_page = NULL;
blocks_per_page = PAGE_SIZE / sb->s_blocksize;
/*
* the buddy cache inode stores the block bitmap
* and buddy information in consecutive blocks.
* So for each group we need two blocks.
*/
block = group * 2;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
page = find_or_create_page(inode->i_mapping, pnum, gfp);
if (!page)
return -ENOMEM;
BUG_ON(page->mapping != inode->i_mapping);
e4b->bd_bitmap_page = page;
e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
if (blocks_per_page >= 2) {
/* buddy and bitmap are on the same page */
return 0;
}
block++;
pnum = block / blocks_per_page;
page = find_or_create_page(inode->i_mapping, pnum, gfp);
if (!page)
return -ENOMEM;
BUG_ON(page->mapping != inode->i_mapping);
e4b->bd_buddy_page = page;
return 0;
}
static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
{
if (e4b->bd_bitmap_page) {
unlock_page(e4b->bd_bitmap_page);
put_page(e4b->bd_bitmap_page);
}
if (e4b->bd_buddy_page) {
unlock_page(e4b->bd_buddy_page);
put_page(e4b->bd_buddy_page);
}
}
/*
* Locking note: This routine calls ext4_mb_init_cache(), which takes the
* block group lock of all groups for this page; do not hold the BG lock when
* calling this routine!
*/
static noinline_for_stack
int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
{
struct ext4_group_info *this_grp;
struct ext4_buddy e4b;
struct page *page;
int ret = 0;
might_sleep();
mb_debug(sb, "init group %u\n", group);
this_grp = ext4_get_group_info(sb, group);
if (!this_grp)
return -EFSCORRUPTED;
/*
* This ensures that we don't reinit the buddy cache
* page which map to the group from which we are already
* allocating. If we are looking at the buddy cache we would
* have taken a reference using ext4_mb_load_buddy and that
* would have pinned buddy page to page cache.
* The call to ext4_mb_get_buddy_page_lock will mark the
* page accessed.
*/
ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
/*
* somebody initialized the group
* return without doing anything
*/
goto err;
}
page = e4b.bd_bitmap_page;
ret = ext4_mb_init_cache(page, NULL, gfp);
if (ret)
goto err;
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
if (e4b.bd_buddy_page == NULL) {
/*
* If both the bitmap and buddy are in
* the same page we don't need to force
* init the buddy
*/
ret = 0;
goto err;
}
/* init buddy cache */
page = e4b.bd_buddy_page;
ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
if (ret)
goto err;
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
err:
ext4_mb_put_buddy_page_lock(&e4b);
return ret;
}
/*
* Locking note: This routine calls ext4_mb_init_cache(), which takes the
* block group lock of all groups for this page; do not hold the BG lock when
* calling this routine!
*/
static noinline_for_stack int
ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
struct ext4_buddy *e4b, gfp_t gfp)
{
int blocks_per_page;
int block;
int pnum;
int poff;
struct page *page;
int ret;
struct ext4_group_info *grp;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct inode *inode = sbi->s_buddy_cache;
might_sleep();
mb_debug(sb, "load group %u\n", group);
blocks_per_page = PAGE_SIZE / sb->s_blocksize;
grp = ext4_get_group_info(sb, group);
if (!grp)
return -EFSCORRUPTED;
e4b->bd_blkbits = sb->s_blocksize_bits;
e4b->bd_info = grp;
e4b->bd_sb = sb;
e4b->bd_group = group;
e4b->bd_buddy_page = NULL;
e4b->bd_bitmap_page = NULL;
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
/*
* we need full data about the group
* to make a good selection
*/
ret = ext4_mb_init_group(sb, group, gfp);
if (ret)
return ret;
}
/*
* the buddy cache inode stores the block bitmap
* and buddy information in consecutive blocks.
* So for each group we need two blocks.
*/
block = group * 2;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
/* we could use find_or_create_page(), but it locks page
* what we'd like to avoid in fast path ... */
page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
if (page == NULL || !PageUptodate(page)) {
if (page)
/*
* drop the page reference and try
* to get the page with lock. If we
* are not uptodate that implies
* somebody just created the page but
* is yet to initialize the same. So
* wait for it to initialize.
*/
put_page(page);
page = find_or_create_page(inode->i_mapping, pnum, gfp);
if (page) {
if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
"ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
/* should never happen */
unlock_page(page);
ret = -EINVAL;
goto err;
}
if (!PageUptodate(page)) {
ret = ext4_mb_init_cache(page, NULL, gfp);
if (ret) {
unlock_page(page);
goto err;
}
mb_cmp_bitmaps(e4b, page_address(page) +
(poff * sb->s_blocksize));
}
unlock_page(page);
}
}
if (page == NULL) {
ret = -ENOMEM;
goto err;
}
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
/* Pages marked accessed already */
e4b->bd_bitmap_page = page;
e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
block++;
pnum = block / blocks_per_page;
poff = block % blocks_per_page;
page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
if (page == NULL || !PageUptodate(page)) {
if (page)
put_page(page);
page = find_or_create_page(inode->i_mapping, pnum, gfp);
if (page) {
if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
"ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
/* should never happen */
unlock_page(page);
ret = -EINVAL;
goto err;
}
if (!PageUptodate(page)) {
ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
gfp);
if (ret) {
unlock_page(page);
goto err;
}
}
unlock_page(page);
}
}
if (page == NULL) {
ret = -ENOMEM;
goto err;
}
if (!PageUptodate(page)) {
ret = -EIO;
goto err;
}
/* Pages marked accessed already */
e4b->bd_buddy_page = page;
e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
return 0;
err:
if (page)
put_page(page);
if (e4b->bd_bitmap_page)
put_page(e4b->bd_bitmap_page);
e4b->bd_buddy = NULL;
e4b->bd_bitmap = NULL;
return ret;
}
static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
struct ext4_buddy *e4b)
{
return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
}
static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
{
if (e4b->bd_bitmap_page)
put_page(e4b->bd_bitmap_page);
if (e4b->bd_buddy_page)
put_page(e4b->bd_buddy_page);
}
static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
{
int order = 1, max;
void *bb;
BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
while (order <= e4b->bd_blkbits + 1) {
bb = mb_find_buddy(e4b, order, &max);
if (!mb_test_bit(block >> order, bb)) {
/* this block is part of buddy of order 'order' */
return order;
}
order++;
}
return 0;
}
static void mb_clear_bits(void *bm, int cur, int len)
{
__u32 *addr;
len = cur + len;
while (cur < len) {
if ((cur & 31) == 0 && (len - cur) >= 32) {
/* fast path: clear whole word at once */
addr = bm + (cur >> 3);
*addr = 0;
cur += 32;
continue;
}
mb_clear_bit(cur, bm);
cur++;
}
}
/* clear bits in given range
* will return first found zero bit if any, -1 otherwise
*/
static int mb_test_and_clear_bits(void *bm, int cur, int len)
{
__u32 *addr;
int zero_bit = -1;
len = cur + len;
while (cur < len) {
if ((cur & 31) == 0 && (len - cur) >= 32) {
/* fast path: clear whole word at once */
addr = bm + (cur >> 3);
if (*addr != (__u32)(-1) && zero_bit == -1)
zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
*addr = 0;
cur += 32;
continue;
}
if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
zero_bit = cur;
cur++;
}
return zero_bit;
}
void mb_set_bits(void *bm, int cur, int len)
{
__u32 *addr;
len = cur + len;
while (cur < len) {
if ((cur & 31) == 0 && (len - cur) >= 32) {
/* fast path: set whole word at once */
addr = bm + (cur >> 3);
*addr = 0xffffffff;
cur += 32;
continue;
}
mb_set_bit(cur, bm);
cur++;
}
}
static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
{
if (mb_test_bit(*bit + side, bitmap)) {
mb_clear_bit(*bit, bitmap);
(*bit) -= side;
return 1;
}
else {
(*bit) += side;
mb_set_bit(*bit, bitmap);
return -1;
}
}
static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
{
int max;
int order = 1;
void *buddy = mb_find_buddy(e4b, order, &max);
while (buddy) {
void *buddy2;
/* Bits in range [first; last] are known to be set since
* corresponding blocks were allocated. Bits in range
* (first; last) will stay set because they form buddies on
* upper layer. We just deal with borders if they don't
* align with upper layer and then go up.
* Releasing entire group is all about clearing
* single bit of highest order buddy.
*/
/* Example:
* ---------------------------------
* | 1 | 1 | 1 | 1 |
* ---------------------------------
* | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
* ---------------------------------
* 0 1 2 3 4 5 6 7
* \_____________________/
*
* Neither [1] nor [6] is aligned to above layer.
* Left neighbour [0] is free, so mark it busy,
* decrease bb_counters and extend range to
* [0; 6]
* Right neighbour [7] is busy. It can't be coaleasced with [6], so
* mark [6] free, increase bb_counters and shrink range to
* [0; 5].
* Then shift range to [0; 2], go up and do the same.
*/
if (first & 1)
e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
if (!(last & 1))
e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
if (first > last)
break;
order++;
buddy2 = mb_find_buddy(e4b, order, &max);
if (!buddy2) {
mb_clear_bits(buddy, first, last - first + 1);
e4b->bd_info->bb_counters[order - 1] += last - first + 1;
break;
}
first >>= 1;
last >>= 1;
buddy = buddy2;
}
}
static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
int first, int count)
{
int left_is_free = 0;
int right_is_free = 0;
int block;
int last = first + count - 1;
struct super_block *sb = e4b->bd_sb;
if (WARN_ON(count == 0))
return;
BUG_ON(last >= (sb->s_blocksize << 3));
assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
/* Don't bother if the block group is corrupt. */
if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
return;
mb_check_buddy(e4b);
mb_free_blocks_double(inode, e4b, first, count);
this_cpu_inc(discard_pa_seq);
e4b->bd_info->bb_free += count;
if (first < e4b->bd_info->bb_first_free)
e4b->bd_info->bb_first_free = first;
/* access memory sequentially: check left neighbour,
* clear range and then check right neighbour
*/
if (first != 0)
left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
if (unlikely(block != -1)) {
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t blocknr;
blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
blocknr += EXT4_C2B(sbi, block);
if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
ext4_grp_locked_error(sb, e4b->bd_group,
inode ? inode->i_ino : 0,
blocknr,
"freeing already freed block (bit %u); block bitmap corrupt.",
block);
ext4_mark_group_bitmap_corrupted(
sb, e4b->bd_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
}
goto done;
}
/* let's maintain fragments counter */
if (left_is_free && right_is_free)
e4b->bd_info->bb_fragments--;
else if (!left_is_free && !right_is_free)
e4b->bd_info->bb_fragments++;
/* buddy[0] == bd_bitmap is a special case, so handle
* it right away and let mb_buddy_mark_free stay free of
* zero order checks.
* Check if neighbours are to be coaleasced,
* adjust bitmap bb_counters and borders appropriately.
*/
if (first & 1) {
first += !left_is_free;
e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
}
if (!(last & 1)) {
last -= !right_is_free;
e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
}
if (first <= last)
mb_buddy_mark_free(e4b, first >> 1, last >> 1);
done:
mb_set_largest_free_order(sb, e4b->bd_info);
mb_update_avg_fragment_size(sb, e4b->bd_info);
mb_check_buddy(e4b);
}
static int mb_find_extent(struct ext4_buddy *e4b, int block,
int needed, struct ext4_free_extent *ex)
{
int next = block;
int max, order;
void *buddy;
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
BUG_ON(ex == NULL);
buddy = mb_find_buddy(e4b, 0, &max);
BUG_ON(buddy == NULL);
BUG_ON(block >= max);
if (mb_test_bit(block, buddy)) {
ex->fe_len = 0;
ex->fe_start = 0;
ex->fe_group = 0;
return 0;
}
/* find actual order */
order = mb_find_order_for_block(e4b, block);
block = block >> order;
ex->fe_len = 1 << order;
ex->fe_start = block << order;
ex->fe_group = e4b->bd_group;
/* calc difference from given start */
next = next - ex->fe_start;
ex->fe_len -= next;
ex->fe_start += next;
while (needed > ex->fe_len &&
mb_find_buddy(e4b, order, &max)) {
if (block + 1 >= max)
break;
next = (block + 1) * (1 << order);
if (mb_test_bit(next, e4b->bd_bitmap))
break;
order = mb_find_order_for_block(e4b, next);
block = next >> order;
ex->fe_len += 1 << order;
}
if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
/* Should never happen! (but apparently sometimes does?!?) */
WARN_ON(1);
ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
"corruption or bug in mb_find_extent "
"block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
block, order, needed, ex->fe_group, ex->fe_start,
ex->fe_len, ex->fe_logical);
ex->fe_len = 0;
ex->fe_start = 0;
ex->fe_group = 0;
}
return ex->fe_len;
}
static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
{
int ord;
int mlen = 0;
int max = 0;
int cur;
int start = ex->fe_start;
int len = ex->fe_len;
unsigned ret = 0;
int len0 = len;
void *buddy;
bool split = false;
BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
BUG_ON(e4b->bd_group != ex->fe_group);
assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
mb_check_buddy(e4b);
mb_mark_used_double(e4b, start, len);
this_cpu_inc(discard_pa_seq);
e4b->bd_info->bb_free -= len;
if (e4b->bd_info->bb_first_free == start)
e4b->bd_info->bb_first_free += len;
/* let's maintain fragments counter */
if (start != 0)
mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
max = !mb_test_bit(start + len, e4b->bd_bitmap);
if (mlen && max)
e4b->bd_info->bb_fragments++;
else if (!mlen && !max)
e4b->bd_info->bb_fragments--;
/* let's maintain buddy itself */
while (len) {
if (!split)
ord = mb_find_order_for_block(e4b, start);
if (((start >> ord) << ord) == start && len >= (1 << ord)) {
/* the whole chunk may be allocated at once! */
mlen = 1 << ord;
if (!split)
buddy = mb_find_buddy(e4b, ord, &max);
else
split = false;
BUG_ON((start >> ord) >= max);
mb_set_bit(start >> ord, buddy);
e4b->bd_info->bb_counters[ord]--;
start += mlen;
len -= mlen;
BUG_ON(len < 0);
continue;
}
/* store for history */
if (ret == 0)
ret = len | (ord << 16);
/* we have to split large buddy */
BUG_ON(ord <= 0);
buddy = mb_find_buddy(e4b, ord, &max);
mb_set_bit(start >> ord, buddy);
e4b->bd_info->bb_counters[ord]--;
ord--;
cur = (start >> ord) & ~1U;
buddy = mb_find_buddy(e4b, ord, &max);
mb_clear_bit(cur, buddy);
mb_clear_bit(cur + 1, buddy);
e4b->bd_info->bb_counters[ord]++;
e4b->bd_info->bb_counters[ord]++;
split = true;
}
mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
mb_check_buddy(e4b);
return ret;
}
/*
* Must be called under group lock!
*/
static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int ret;
BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
BUG_ON(ac->ac_status == AC_STATUS_FOUND);
ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
ret = mb_mark_used(e4b, &ac->ac_b_ex);
/* preallocation can change ac_b_ex, thus we store actually
* allocated blocks for history */
ac->ac_f_ex = ac->ac_b_ex;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_tail = ret & 0xffff;
ac->ac_buddy = ret >> 16;
/*
* take the page reference. We want the page to be pinned
* so that we don't get a ext4_mb_init_cache_call for this
* group until we update the bitmap. That would mean we
* double allocate blocks. The reference is dropped
* in ext4_mb_release_context
*/
ac->ac_bitmap_page = e4b->bd_bitmap_page;
get_page(ac->ac_bitmap_page);
ac->ac_buddy_page = e4b->bd_buddy_page;
get_page(ac->ac_buddy_page);
/* store last allocated for subsequent stream allocation */
if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
spin_lock(&sbi->s_md_lock);
sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
spin_unlock(&sbi->s_md_lock);
}
/*
* As we've just preallocated more space than
* user requested originally, we store allocated
* space in a special descriptor.
*/
if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
ext4_mb_new_preallocation(ac);
}
static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b,
int finish_group)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_free_extent *bex = &ac->ac_b_ex;
struct ext4_free_extent *gex = &ac->ac_g_ex;
if (ac->ac_status == AC_STATUS_FOUND)
return;
/*
* We don't want to scan for a whole year
*/
if (ac->ac_found > sbi->s_mb_max_to_scan &&
!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
ac->ac_status = AC_STATUS_BREAK;
return;
}
/*
* Haven't found good chunk so far, let's continue
*/
if (bex->fe_len < gex->fe_len)
return;
if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
ext4_mb_use_best_found(ac, e4b);
}
/*
* The routine checks whether found extent is good enough. If it is,
* then the extent gets marked used and flag is set to the context
* to stop scanning. Otherwise, the extent is compared with the
* previous found extent and if new one is better, then it's stored
* in the context. Later, the best found extent will be used, if
* mballoc can't find good enough extent.
*
* The algorithm used is roughly as follows:
*
* * If free extent found is exactly as big as goal, then
* stop the scan and use it immediately
*
* * If free extent found is smaller than goal, then keep retrying
* upto a max of sbi->s_mb_max_to_scan times (default 200). After
* that stop scanning and use whatever we have.
*
* * If free extent found is bigger than goal, then keep retrying
* upto a max of sbi->s_mb_min_to_scan times (default 10) before
* stopping the scan and using the extent.
*
*
* FIXME: real allocation policy is to be designed yet!
*/
static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
struct ext4_free_extent *ex,
struct ext4_buddy *e4b)
{
struct ext4_free_extent *bex = &ac->ac_b_ex;
struct ext4_free_extent *gex = &ac->ac_g_ex;
BUG_ON(ex->fe_len <= 0);
BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
ac->ac_found++;
ac->ac_cX_found[ac->ac_criteria]++;
/*
* The special case - take what you catch first
*/
if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
*bex = *ex;
ext4_mb_use_best_found(ac, e4b);
return;
}
/*
* Let's check whether the chuck is good enough
*/
if (ex->fe_len == gex->fe_len) {
*bex = *ex;
ext4_mb_use_best_found(ac, e4b);
return;
}
/*
* If this is first found extent, just store it in the context
*/
if (bex->fe_len == 0) {
*bex = *ex;
return;
}
/*
* If new found extent is better, store it in the context
*/
if (bex->fe_len < gex->fe_len) {
/* if the request isn't satisfied, any found extent
* larger than previous best one is better */
if (ex->fe_len > bex->fe_len)
*bex = *ex;
} else if (ex->fe_len > gex->fe_len) {
/* if the request is satisfied, then we try to find
* an extent that still satisfy the request, but is
* smaller than previous one */
if (ex->fe_len < bex->fe_len)
*bex = *ex;
}
ext4_mb_check_limits(ac, e4b, 0);
}
static noinline_for_stack
void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct ext4_free_extent ex = ac->ac_b_ex;
ext4_group_t group = ex.fe_group;
int max;
int err;
BUG_ON(ex.fe_len <= 0);
err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
if (err)
return;
ext4_lock_group(ac->ac_sb, group);
max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
if (max > 0) {
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
ext4_unlock_group(ac->ac_sb, group);
ext4_mb_unload_buddy(e4b);
}
static noinline_for_stack
int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
ext4_group_t group = ac->ac_g_ex.fe_group;
int max;
int err;
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
struct ext4_free_extent ex;
if (!grp)
return -EFSCORRUPTED;
if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
return 0;
if (grp->bb_free == 0)
return 0;
err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
if (err)
return err;
if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
ext4_mb_unload_buddy(e4b);
return 0;
}
ext4_lock_group(ac->ac_sb, group);
max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
ac->ac_g_ex.fe_len, &ex);
ex.fe_logical = 0xDEADFA11; /* debug value */
if (max >= ac->ac_g_ex.fe_len &&
ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
ext4_fsblk_t start;
start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
/* use do_div to get remainder (would be 64-bit modulo) */
if (do_div(start, sbi->s_stripe) == 0) {
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
} else if (max >= ac->ac_g_ex.fe_len) {
BUG_ON(ex.fe_len <= 0);
BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
/* Sometimes, caller may want to merge even small
* number of blocks to an existing extent */
BUG_ON(ex.fe_len <= 0);
BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
ac->ac_found++;
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
}
ext4_unlock_group(ac->ac_sb, group);
ext4_mb_unload_buddy(e4b);
return 0;
}
/*
* The routine scans buddy structures (not bitmap!) from given order
* to max order and tries to find big enough chunk to satisfy the req
*/
static noinline_for_stack
void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
struct ext4_group_info *grp = e4b->bd_info;
void *buddy;
int i;
int k;
int max;
BUG_ON(ac->ac_2order <= 0);
for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
if (grp->bb_counters[i] == 0)
continue;
buddy = mb_find_buddy(e4b, i, &max);
if (WARN_RATELIMIT(buddy == NULL,
"ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
continue;
k = mb_find_next_zero_bit(buddy, max, 0);
if (k >= max) {
ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
"%d free clusters of order %d. But found 0",
grp->bb_counters[i], i);
ext4_mark_group_bitmap_corrupted(ac->ac_sb,
e4b->bd_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
break;
}
ac->ac_found++;
ac->ac_cX_found[ac->ac_criteria]++;
ac->ac_b_ex.fe_len = 1 << i;
ac->ac_b_ex.fe_start = k << i;
ac->ac_b_ex.fe_group = e4b->bd_group;
ext4_mb_use_best_found(ac, e4b);
BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
if (EXT4_SB(sb)->s_mb_stats)
atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
break;
}
}
/*
* The routine scans the group and measures all found extents.
* In order to optimize scanning, caller must pass number of
* free blocks in the group, so the routine can know upper limit.
*/
static noinline_for_stack
void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
void *bitmap = e4b->bd_bitmap;
struct ext4_free_extent ex;
int i, j, freelen;
int free;
free = e4b->bd_info->bb_free;
if (WARN_ON(free <= 0))
return;
i = e4b->bd_info->bb_first_free;
while (free && ac->ac_status == AC_STATUS_CONTINUE) {
i = mb_find_next_zero_bit(bitmap,
EXT4_CLUSTERS_PER_GROUP(sb), i);
if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
/*
* IF we have corrupt bitmap, we won't find any
* free blocks even though group info says we
* have free blocks
*/
ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
"%d free clusters as per "
"group info. But bitmap says 0",
free);
ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
break;
}
if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
/*
* In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
* sure that this group will have a large enough
* continuous free extent, so skip over the smaller free
* extents
*/
j = mb_find_next_bit(bitmap,
EXT4_CLUSTERS_PER_GROUP(sb), i);
freelen = j - i;
if (freelen < ac->ac_g_ex.fe_len) {
i = j;
free -= freelen;
continue;
}
}
mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
if (WARN_ON(ex.fe_len <= 0))
break;
if (free < ex.fe_len) {
ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
"%d free clusters as per "
"group info. But got %d blocks",
free, ex.fe_len);
ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
EXT4_GROUP_INFO_BBITMAP_CORRUPT);
/*
* The number of free blocks differs. This mostly
* indicate that the bitmap is corrupt. So exit
* without claiming the space.
*/
break;
}
ex.fe_logical = 0xDEADC0DE; /* debug value */
ext4_mb_measure_extent(ac, &ex, e4b);
i += ex.fe_len;
free -= ex.fe_len;
}
ext4_mb_check_limits(ac, e4b, 1);
}
/*
* This is a special case for storages like raid5
* we try to find stripe-aligned chunks for stripe-size-multiple requests
*/
static noinline_for_stack
void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
struct ext4_buddy *e4b)
{
struct super_block *sb = ac->ac_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
void *bitmap = e4b->bd_bitmap;
struct ext4_free_extent ex;
ext4_fsblk_t first_group_block;
ext4_fsblk_t a;
ext4_grpblk_t i, stripe;
int max;
BUG_ON(sbi->s_stripe == 0);
/* find first stripe-aligned block in group */
first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
a = first_group_block + sbi->s_stripe - 1;
do_div(a, sbi->s_stripe);
i = (a * sbi->s_stripe) - first_group_block;
stripe = EXT4_B2C(sbi, sbi->s_stripe);
i = EXT4_B2C(sbi, i);
while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
if (!mb_test_bit(i, bitmap)) {
max = mb_find_extent(e4b, i, stripe, &ex);
if (max >= stripe) {
ac->ac_found++;
ac->ac_cX_found[ac->ac_criteria]++;
ex.fe_logical = 0xDEADF00D; /* debug value */
ac->ac_b_ex = ex;
ext4_mb_use_best_found(ac, e4b);
break;
}
}
i += stripe;
}
}
/*
* This is also called BEFORE we load the buddy bitmap.
* Returns either 1 or 0 indicating that the group is either suitable
* for the allocation or not.
*/
static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
ext4_group_t group, enum criteria cr)
{
ext4_grpblk_t free, fragments;
int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
return false;
free = grp->bb_free;
if (free == 0)
return false;
fragments = grp->bb_fragments;
if (fragments == 0)
return false;
switch (cr) {
case CR_POWER2_ALIGNED:
BUG_ON(ac->ac_2order == 0);
/* Avoid using the first bg of a flexgroup for data files */
if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
(flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
((group % flex_size) == 0))
return false;
if (free < ac->ac_g_ex.fe_len)
return false;
if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
return true;
if (grp->bb_largest_free_order < ac->ac_2order)
return false;
return true;
case CR_GOAL_LEN_FAST:
case CR_BEST_AVAIL_LEN:
if ((free / fragments) >= ac->ac_g_ex.fe_len)
return true;
break;
case CR_GOAL_LEN_SLOW:
if (free >= ac->ac_g_ex.fe_len)
return true;
break;
case CR_ANY_FREE:
return true;
default:
BUG();
}
return false;
}
/*
* This could return negative error code if something goes wrong
* during ext4_mb_init_group(). This should not be called with
* ext4_lock_group() held.
*
* Note: because we are conditionally operating with the group lock in
* the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
* function using __acquire and __release. This means we need to be
* super careful before messing with the error path handling via "goto
* out"!
*/
static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
ext4_group_t group, enum criteria cr)
{
struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
struct super_block *sb = ac->ac_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
ext4_grpblk_t free;
int ret = 0;
if (!grp)
return -EFSCORRUPTED;
if (sbi->s_mb_stats)
atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
if (should_lock) {
ext4_lock_group(sb, group);
__release(ext4_group_lock_ptr(sb, group));
}
free = grp->bb_free;
if (free == 0)
goto out;
/*
* In all criterias except CR_ANY_FREE we try to avoid groups that
* can't possibly satisfy the full goal request due to insufficient
* free blocks.
*/
if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
goto out;
if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
goto out;
if (should_lock) {
__acquire(ext4_group_lock_ptr(sb, group));
ext4_unlock_group(sb, group);
}
/* We only do this if the grp has never been initialized */
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, group, NULL);
int ret;
/*
* cr=CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
* search to find large good chunks almost for free. If buddy
* data is not ready, then this optimization makes no sense. But
* we never skip the first block group in a flex_bg, since this
* gets used for metadata block allocation, and we want to make
* sure we locate metadata blocks in the first block group in
* the flex_bg if possible.
*/
if (!ext4_mb_cr_expensive(cr) &&
(!sbi->s_log_groups_per_flex ||
((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
!(ext4_has_group_desc_csum(sb) &&
(gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
return 0;
ret = ext4_mb_init_group(sb, group, GFP_NOFS);
if (ret)
return ret;
}
if (should_lock) {
ext4_lock_group(sb, group);
__release(ext4_group_lock_ptr(sb, group));
}
ret = ext4_mb_good_group(ac, group, cr);
out:
if (should_lock) {
__acquire(ext4_group_lock_ptr(sb, group));
ext4_unlock_group(sb, group);
}
return ret;
}
/*
* Start prefetching @nr block bitmaps starting at @group.
* Return the next group which needs to be prefetched.
*/
ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
unsigned int nr, int *cnt)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct buffer_head *bh;
struct blk_plug plug;
blk_start_plug(&plug);
while (nr-- > 0) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
NULL);
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
/*
* Prefetch block groups with free blocks; but don't
* bother if it is marked uninitialized on disk, since
* it won't require I/O to read. Also only try to
* prefetch once, so we avoid getblk() call, which can
* be expensive.
*/
if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
EXT4_MB_GRP_NEED_INIT(grp) &&
ext4_free_group_clusters(sb, gdp) > 0 ) {
bh = ext4_read_block_bitmap_nowait(sb, group, true);
if (bh && !IS_ERR(bh)) {
if (!buffer_uptodate(bh) && cnt)
(*cnt)++;
brelse(bh);
}
}
if (++group >= ngroups)
group = 0;
}
blk_finish_plug(&plug);
return group;
}
/*
* Prefetching reads the block bitmap into the buffer cache; but we
* need to make sure that the buddy bitmap in the page cache has been
* initialized. Note that ext4_mb_init_group() will block if the I/O
* is not yet completed, or indeed if it was not initiated by
* ext4_mb_prefetch did not start the I/O.
*
* TODO: We should actually kick off the buddy bitmap setup in a work
* queue when the buffer I/O is completed, so that we don't block
* waiting for the block allocation bitmap read to finish when
* ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
*/
void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
unsigned int nr)
{
struct ext4_group_desc *gdp;
struct ext4_group_info *grp;
while (nr-- > 0) {
if (!group)
group = ext4_get_groups_count(sb);
group--;
gdp = ext4_get_group_desc(sb, group, NULL);
grp = ext4_get_group_info(sb, group);
if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
ext4_free_group_clusters(sb, gdp) > 0) {
if (ext4_mb_init_group(sb, group, GFP_NOFS))
break;
}
}
}
static noinline_for_stack int
ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
{
ext4_group_t prefetch_grp = 0, ngroups, group, i;
enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
int err = 0, first_err = 0;
unsigned int nr = 0, prefetch_ios = 0;
struct ext4_sb_info *sbi;
struct super_block *sb;
struct ext4_buddy e4b;
int lost;
sb = ac->ac_sb;
sbi = EXT4_SB(sb);
ngroups = ext4_get_groups_count(sb);
/* non-extent files are limited to low blocks/groups */
if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
ngroups = sbi->s_blockfile_groups;
BUG_ON(ac->ac_status == AC_STATUS_FOUND);
/* first, try the goal */
err = ext4_mb_find_by_goal(ac, &e4b);
if (err || ac->ac_status == AC_STATUS_FOUND)
goto out;
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
goto out;
/*
* ac->ac_2order is set only if the fe_len is a power of 2
* if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
* so that we try exact allocation using buddy.
*/
i = fls(ac->ac_g_ex.fe_len);
ac->ac_2order = 0;
/*
* We search using buddy data only if the order of the request
* is greater than equal to the sbi_s_mb_order2_reqs
* You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
* We also support searching for power-of-two requests only for
* requests upto maximum buddy size we have constructed.
*/
if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
if (is_power_of_2(ac->ac_g_ex.fe_len))
ac->ac_2order = array_index_nospec(i - 1,
MB_NUM_ORDERS(sb));
}
/* if stream allocation is enabled, use global goal */
if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
/* TBD: may be hot point */
spin_lock(&sbi->s_md_lock);
ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
spin_unlock(&sbi->s_md_lock);
}
/*
* Let's just scan groups to find more-less suitable blocks We
* start with CR_GOAL_LEN_FAST, unless it is power of 2
* aligned, in which case let's do that faster approach first.
*/
if (ac->ac_2order)
cr = CR_POWER2_ALIGNED;
repeat:
for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
ac->ac_criteria = cr;
/*
* searching for the right group start
* from the goal value specified
*/
group = ac->ac_g_ex.fe_group;
ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
prefetch_grp = group;
for (i = 0, new_cr = cr; i < ngroups; i++,
ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
int ret = 0;
cond_resched();
if (new_cr != cr) {
cr = new_cr;
goto repeat;
}
/*
* Batch reads of the block allocation bitmaps
* to get multiple READs in flight; limit
* prefetching at inexpensive CR, otherwise mballoc
* can spend a lot of time loading imperfect groups
*/
if ((prefetch_grp == group) &&
(ext4_mb_cr_expensive(cr) ||
prefetch_ios < sbi->s_mb_prefetch_limit)) {
nr = sbi->s_mb_prefetch;
if (ext4_has_feature_flex_bg(sb)) {
nr = 1 << sbi->s_log_groups_per_flex;
nr -= group & (nr - 1);
nr = min(nr, sbi->s_mb_prefetch);
}
prefetch_grp = ext4_mb_prefetch(sb, group,
nr, &prefetch_ios);
}
/* This now checks without needing the buddy page */
ret = ext4_mb_good_group_nolock(ac, group, cr);
if (ret <= 0) {
if (!first_err)
first_err = ret;
continue;
}
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err)
goto out;
ext4_lock_group(sb, group);
/*
* We need to check again after locking the
* block group
*/
ret = ext4_mb_good_group(ac, group, cr);
if (ret == 0) {
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
continue;
}
ac->ac_groups_scanned++;
if (cr == CR_POWER2_ALIGNED)
ext4_mb_simple_scan_group(ac, &e4b);
else if ((cr == CR_GOAL_LEN_FAST ||
cr == CR_BEST_AVAIL_LEN) &&
sbi->s_stripe &&
!(ac->ac_g_ex.fe_len %
EXT4_B2C(sbi, sbi->s_stripe)))
ext4_mb_scan_aligned(ac, &e4b);
else
ext4_mb_complex_scan_group(ac, &e4b);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
if (ac->ac_status != AC_STATUS_CONTINUE)
break;
}
/* Processed all groups and haven't found blocks */
if (sbi->s_mb_stats && i == ngroups)
atomic64_inc(&sbi->s_bal_cX_failed[cr]);
if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
/* Reset goal length to original goal length before
* falling into CR_GOAL_LEN_SLOW */
ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
}
if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
/*
* We've been searching too long. Let's try to allocate
* the best chunk we've found so far
*/
ext4_mb_try_best_found(ac, &e4b);
if (ac->ac_status != AC_STATUS_FOUND) {
/*
* Someone more lucky has already allocated it.
* The only thing we can do is just take first
* found block(s)
*/
lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
ac->ac_b_ex.fe_len, lost);
ac->ac_b_ex.fe_group = 0;
ac->ac_b_ex.fe_start = 0;
ac->ac_b_ex.fe_len = 0;
ac->ac_status = AC_STATUS_CONTINUE;
ac->ac_flags |= EXT4_MB_HINT_FIRST;
cr = CR_ANY_FREE;
goto repeat;
}
}
if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
out:
if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
err = first_err;
mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
ac->ac_flags, cr, err);
if (nr)
ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
return err;
}
static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
{
struct super_block *sb = pde_data(file_inode(seq->file));
ext4_group_t group;
if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
return NULL;
group = *pos + 1;
return (void *) ((unsigned long) group);
}
static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct super_block *sb = pde_data(file_inode(seq->file));
ext4_group_t group;
++*pos;
if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
return NULL;
group = *pos + 1;
return (void *) ((unsigned long) group);
}
static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
{
struct super_block *sb = pde_data(file_inode(seq->file));
ext4_group_t group = (ext4_group_t) ((unsigned long) v);
int i;
int err, buddy_loaded = 0;
struct ext4_buddy e4b;
struct ext4_group_info *grinfo;
unsigned char blocksize_bits = min_t(unsigned char,
sb->s_blocksize_bits,
EXT4_MAX_BLOCK_LOG_SIZE);
struct sg {
struct ext4_group_info info;
ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
} sg;
group--;
if (group == 0)
seq_puts(seq, "#group: free frags first ["
" 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
" 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
sizeof(struct ext4_group_info);
grinfo = ext4_get_group_info(sb, group);
if (!grinfo)
return 0;
/* Load the group info in memory only if not already loaded. */
if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err) {
seq_printf(seq, "#%-5u: I/O error\n", group);
return 0;
}
buddy_loaded = 1;
}
memcpy(&sg, grinfo, i);
if (buddy_loaded)
ext4_mb_unload_buddy(&e4b);
seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
sg.info.bb_fragments, sg.info.bb_first_free);
for (i = 0; i <= 13; i++)
seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
sg.info.bb_counters[i] : 0);
seq_puts(seq, " ]\n");
return 0;
}
static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
{
}
const struct seq_operations ext4_mb_seq_groups_ops = {
.start = ext4_mb_seq_groups_start,
.next = ext4_mb_seq_groups_next,
.stop = ext4_mb_seq_groups_stop,
.show = ext4_mb_seq_groups_show,
};
int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
seq_puts(seq, "mballoc:\n");
if (!sbi->s_mb_stats) {
seq_puts(seq, "\tmb stats collection turned off.\n");
seq_puts(
seq,
"\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
return 0;
}
seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
seq_printf(seq, "\tgroups_scanned: %u\n",
atomic_read(&sbi->s_bal_groups_scanned));
/* CR_POWER2_ALIGNED stats */
seq_puts(seq, "\tcr_p2_aligned_stats:\n");
seq_printf(seq, "\t\thits: %llu\n",
atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
seq_printf(
seq, "\t\tgroups_considered: %llu\n",
atomic64_read(
&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
seq_printf(seq, "\t\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
seq_printf(seq, "\t\tuseless_loops: %llu\n",
atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
seq_printf(seq, "\t\tbad_suggestions: %u\n",
atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
/* CR_GOAL_LEN_FAST stats */
seq_puts(seq, "\tcr_goal_fast_stats:\n");
seq_printf(seq, "\t\thits: %llu\n",
atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
seq_printf(seq, "\t\tgroups_considered: %llu\n",
atomic64_read(
&sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
seq_printf(seq, "\t\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
seq_printf(seq, "\t\tuseless_loops: %llu\n",
atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
seq_printf(seq, "\t\tbad_suggestions: %u\n",
atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
/* CR_BEST_AVAIL_LEN stats */
seq_puts(seq, "\tcr_best_avail_stats:\n");
seq_printf(seq, "\t\thits: %llu\n",
atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
seq_printf(
seq, "\t\tgroups_considered: %llu\n",
atomic64_read(
&sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
seq_printf(seq, "\t\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
seq_printf(seq, "\t\tuseless_loops: %llu\n",
atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
seq_printf(seq, "\t\tbad_suggestions: %u\n",
atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
/* CR_GOAL_LEN_SLOW stats */
seq_puts(seq, "\tcr_goal_slow_stats:\n");
seq_printf(seq, "\t\thits: %llu\n",
atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
seq_printf(seq, "\t\tgroups_considered: %llu\n",
atomic64_read(
&sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
seq_printf(seq, "\t\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
seq_printf(seq, "\t\tuseless_loops: %llu\n",
atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
/* CR_ANY_FREE stats */
seq_puts(seq, "\tcr_any_free_stats:\n");
seq_printf(seq, "\t\thits: %llu\n",
atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
seq_printf(
seq, "\t\tgroups_considered: %llu\n",
atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
seq_printf(seq, "\t\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
seq_printf(seq, "\t\tuseless_loops: %llu\n",
atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
/* Aggregates */
seq_printf(seq, "\textents_scanned: %u\n",
atomic_read(&sbi->s_bal_ex_scanned));
seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
seq_printf(seq, "\t\tlen_goal_hits: %u\n",
atomic_read(&sbi->s_bal_len_goals));
seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
seq_printf(seq, "\tbuddies_generated: %u/%u\n",
atomic_read(&sbi->s_mb_buddies_generated),
ext4_get_groups_count(sb));
seq_printf(seq, "\tbuddies_time_used: %llu\n",
atomic64_read(&sbi->s_mb_generation_time));
seq_printf(seq, "\tpreallocated: %u\n",
atomic_read(&sbi->s_mb_preallocated));
seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
return 0;
}
static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
__acquires(&EXT4_SB(sb)->s_mb_rb_lock)
{
struct super_block *sb = pde_data(file_inode(seq->file));
unsigned long position;
if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
return NULL;
position = *pos + 1;
return (void *) ((unsigned long) position);
}
static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct super_block *sb = pde_data(file_inode(seq->file));
unsigned long position;
++*pos;
if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
return NULL;
position = *pos + 1;
return (void *) ((unsigned long) position);
}
static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
{
struct super_block *sb = pde_data(file_inode(seq->file));
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long position = ((unsigned long) v);
struct ext4_group_info *grp;
unsigned int count;
position--;
if (position >= MB_NUM_ORDERS(sb)) {
position -= MB_NUM_ORDERS(sb);
if (position == 0)
seq_puts(seq, "avg_fragment_size_lists:\n");
count = 0;
read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
bb_avg_fragment_size_node)
count++;
read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
seq_printf(seq, "\tlist_order_%u_groups: %u\n",
(unsigned int)position, count);
return 0;
}
if (position == 0) {
seq_printf(seq, "optimize_scan: %d\n",
test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
seq_puts(seq, "max_free_order_lists:\n");
}
count = 0;
read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
bb_largest_free_order_node)
count++;
read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
seq_printf(seq, "\tlist_order_%u_groups: %u\n",
(unsigned int)position, count);
return 0;
}
static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
{
}
const struct seq_operations ext4_mb_seq_structs_summary_ops = {
.start = ext4_mb_seq_structs_summary_start,
.next = ext4_mb_seq_structs_summary_next,
.stop = ext4_mb_seq_structs_summary_stop,
.show = ext4_mb_seq_structs_summary_show,
};
static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
{
int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
BUG_ON(!cachep);
return cachep;
}
/*
* Allocate the top-level s_group_info array for the specified number
* of groups
*/
int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned size;
struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
EXT4_DESC_PER_BLOCK_BITS(sb);
if (size <= sbi->s_group_info_size)
return 0;
size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
new_groupinfo = kvzalloc(size, GFP_KERNEL);
if (!new_groupinfo) {
ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
return -ENOMEM;
}
rcu_read_lock();
old_groupinfo = rcu_dereference(sbi->s_group_info);
if (old_groupinfo)
memcpy(new_groupinfo, old_groupinfo,
sbi->s_group_info_size * sizeof(*sbi->s_group_info));
rcu_read_unlock();
rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
if (old_groupinfo)
ext4_kvfree_array_rcu(old_groupinfo);
ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
sbi->s_group_info_size);
return 0;
}
/* Create and initialize ext4_group_info data for the given group. */
int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *desc)
{
int i;
int metalen = 0;
int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_info **meta_group_info;
struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
/*
* First check if this group is the first of a reserved block.
* If it's true, we have to allocate a new table of pointers
* to ext4_group_info structures
*/
if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
metalen = sizeof(*meta_group_info) <<
EXT4_DESC_PER_BLOCK_BITS(sb);
meta_group_info = kmalloc(metalen, GFP_NOFS);
if (meta_group_info == NULL) {
ext4_msg(sb, KERN_ERR, "can't allocate mem "
"for a buddy group");
return -ENOMEM;
}
rcu_read_lock();
rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
rcu_read_unlock();
}
meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
if (meta_group_info[i] == NULL) {
ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
goto exit_group_info;
}
set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
&(meta_group_info[i]->bb_state));
/*
* initialize bb_free to be able to skip
* empty groups without initialization
*/
if (ext4_has_group_desc_csum(sb) &&
(desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
meta_group_info[i]->bb_free =
ext4_free_clusters_after_init(sb, group, desc);
} else {
meta_group_info[i]->bb_free =
ext4_free_group_clusters(sb, desc);
}
INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
init_rwsem(&meta_group_info[i]->alloc_sem);
meta_group_info[i]->bb_free_root = RB_ROOT;
INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
meta_group_info[i]->bb_avg_fragment_size_order = -1; /* uninit */
meta_group_info[i]->bb_group = group;
mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
return 0;
exit_group_info:
/* If a meta_group_info table has been allocated, release it now */
if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
struct ext4_group_info ***group_info;
rcu_read_lock();
group_info = rcu_dereference(sbi->s_group_info);
kfree(group_info[idx]);
group_info[idx] = NULL;
rcu_read_unlock();
}
return -ENOMEM;
} /* ext4_mb_add_groupinfo */
static int ext4_mb_init_backend(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
ext4_group_t i;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err;
struct ext4_group_desc *desc;
struct ext4_group_info ***group_info;
struct kmem_cache *cachep;
err = ext4_mb_alloc_groupinfo(sb, ngroups);
if (err)
return err;
sbi->s_buddy_cache = new_inode(sb);
if (sbi->s_buddy_cache == NULL) {
ext4_msg(sb, KERN_ERR, "can't get new inode");
goto err_freesgi;
}
/* To avoid potentially colliding with an valid on-disk inode number,
* use EXT4_BAD_INO for the buddy cache inode number. This inode is
* not in the inode hash, so it should never be found by iget(), but
* this will avoid confusion if it ever shows up during debugging. */
sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
for (i = 0; i < ngroups; i++) {
cond_resched();
desc = ext4_get_group_desc(sb, i, NULL);
if (desc == NULL) {
ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
goto err_freebuddy;
}
if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
goto err_freebuddy;
}
if (ext4_has_feature_flex_bg(sb)) {
/* a single flex group is supposed to be read by a single IO.
* 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
* unsigned integer, so the maximum shift is 32.
*/
if (sbi->s_es->s_log_groups_per_flex >= 32) {
ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
goto err_freebuddy;
}
sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
} else {
sbi->s_mb_prefetch = 32;
}
if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
sbi->s_mb_prefetch = ext4_get_groups_count(sb);
/* now many real IOs to prefetch within a single allocation at cr=0
* given cr=0 is an CPU-related optimization we shouldn't try to
* load too many groups, at some point we should start to use what
* we've got in memory.
* with an average random access time 5ms, it'd take a second to get
* 200 groups (* N with flex_bg), so let's make this limit 4
*/
sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
return 0;
err_freebuddy:
cachep = get_groupinfo_cache(sb->s_blocksize_bits);
while (i-- > 0) {
struct ext4_group_info *grp = ext4_get_group_info(sb, i);
if (grp)
kmem_cache_free(cachep, grp);
}
i = sbi->s_group_info_size;
rcu_read_lock();
group_info = rcu_dereference(sbi->s_group_info);
while (i-- > 0)
kfree(group_info[i]);
rcu_read_unlock();
iput(sbi->s_buddy_cache);
err_freesgi:
rcu_read_lock();
kvfree(rcu_dereference(sbi->s_group_info));
rcu_read_unlock();
return -ENOMEM;
}
static void ext4_groupinfo_destroy_slabs(void)
{
int i;
for (i = 0; i < NR_GRPINFO_CACHES; i++) {
kmem_cache_destroy(ext4_groupinfo_caches[i]);
ext4_groupinfo_caches[i] = NULL;
}
}
static int ext4_groupinfo_create_slab(size_t size)
{
static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
int slab_size;
int blocksize_bits = order_base_2(size);
int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
struct kmem_cache *cachep;
if (cache_index >= NR_GRPINFO_CACHES)
return -EINVAL;
if (unlikely(cache_index < 0))
cache_index = 0;
mutex_lock(&ext4_grpinfo_slab_create_mutex);
if (ext4_groupinfo_caches[cache_index]) {
mutex_unlock(&ext4_grpinfo_slab_create_mutex);
return 0; /* Already created */
}
slab_size = offsetof(struct ext4_group_info,
bb_counters[blocksize_bits + 2]);
cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
slab_size, 0, SLAB_RECLAIM_ACCOUNT,
NULL);
ext4_groupinfo_caches[cache_index] = cachep;
mutex_unlock(&ext4_grpinfo_slab_create_mutex);
if (!cachep) {
printk(KERN_EMERG
"EXT4-fs: no memory for groupinfo slab cache\n");
return -ENOMEM;
}
return 0;
}
static void ext4_discard_work(struct work_struct *work)
{
struct ext4_sb_info *sbi = container_of(work,
struct ext4_sb_info, s_discard_work);
struct super_block *sb = sbi->s_sb;
struct ext4_free_data *fd, *nfd;
struct ext4_buddy e4b;
LIST_HEAD(discard_list);
ext4_group_t grp, load_grp;
int err = 0;
spin_lock(&sbi->s_md_lock);
list_splice_init(&sbi->s_discard_list, &discard_list);
spin_unlock(&sbi->s_md_lock);
load_grp = UINT_MAX;
list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
/*
* If filesystem is umounting or no memory or suffering
* from no space, give up the discard
*/
if ((sb->s_flags & SB_ACTIVE) && !err &&
!atomic_read(&sbi->s_retry_alloc_pending)) {
grp = fd->efd_group;
if (grp != load_grp) {
if (load_grp != UINT_MAX)
ext4_mb_unload_buddy(&e4b);
err = ext4_mb_load_buddy(sb, grp, &e4b);
if (err) {
kmem_cache_free(ext4_free_data_cachep, fd);
load_grp = UINT_MAX;
continue;
} else {
load_grp = grp;
}
}
ext4_lock_group(sb, grp);
ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
fd->efd_start_cluster + fd->efd_count - 1, 1);
ext4_unlock_group(sb, grp);
}
kmem_cache_free(ext4_free_data_cachep, fd);
}
if (load_grp != UINT_MAX)
ext4_mb_unload_buddy(&e4b);
}
int ext4_mb_init(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned i, j;
unsigned offset, offset_incr;
unsigned max;
int ret;
i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
if (sbi->s_mb_offsets == NULL) {
ret = -ENOMEM;
goto out;
}
i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
if (sbi->s_mb_maxs == NULL) {
ret = -ENOMEM;
goto out;
}
ret = ext4_groupinfo_create_slab(sb->s_blocksize);
if (ret < 0)
goto out;
/* order 0 is regular bitmap */
sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
sbi->s_mb_offsets[0] = 0;
i = 1;
offset = 0;
offset_incr = 1 << (sb->s_blocksize_bits - 1);
max = sb->s_blocksize << 2;
do {
sbi->s_mb_offsets[i] = offset;
sbi->s_mb_maxs[i] = max;
offset += offset_incr;
offset_incr = offset_incr >> 1;
max = max >> 1;
i++;
} while (i < MB_NUM_ORDERS(sb));
sbi->s_mb_avg_fragment_size =
kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
GFP_KERNEL);
if (!sbi->s_mb_avg_fragment_size) {
ret = -ENOMEM;
goto out;
}
sbi->s_mb_avg_fragment_size_locks =
kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
GFP_KERNEL);
if (!sbi->s_mb_avg_fragment_size_locks) {
ret = -ENOMEM;
goto out;
}
for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
}
sbi->s_mb_largest_free_orders =
kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
GFP_KERNEL);
if (!sbi->s_mb_largest_free_orders) {
ret = -ENOMEM;
goto out;
}
sbi->s_mb_largest_free_orders_locks =
kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
GFP_KERNEL);
if (!sbi->s_mb_largest_free_orders_locks) {
ret = -ENOMEM;
goto out;
}
for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
}
spin_lock_init(&sbi->s_md_lock);
sbi->s_mb_free_pending = 0;
INIT_LIST_HEAD(&sbi->s_freed_data_list);
INIT_LIST_HEAD(&sbi->s_discard_list);
INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
atomic_set(&sbi->s_retry_alloc_pending, 0);
sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
sbi->s_mb_stats = MB_DEFAULT_STATS;
sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
/*
* The default group preallocation is 512, which for 4k block
* sizes translates to 2 megabytes. However for bigalloc file
* systems, this is probably too big (i.e, if the cluster size
* is 1 megabyte, then group preallocation size becomes half a
* gigabyte!). As a default, we will keep a two megabyte
* group pralloc size for cluster sizes up to 64k, and after
* that, we will force a minimum group preallocation size of
* 32 clusters. This translates to 8 megs when the cluster
* size is 256k, and 32 megs when the cluster size is 1 meg,
* which seems reasonable as a default.
*/
sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
sbi->s_cluster_bits, 32);
/*
* If there is a s_stripe > 1, then we set the s_mb_group_prealloc
* to the lowest multiple of s_stripe which is bigger than
* the s_mb_group_prealloc as determined above. We want
* the preallocation size to be an exact multiple of the
* RAID stripe size so that preallocations don't fragment
* the stripes.
*/
if (sbi->s_stripe > 1) {
sbi->s_mb_group_prealloc = roundup(
sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
}
sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
if (sbi->s_locality_groups == NULL) {
ret = -ENOMEM;
goto out;
}
for_each_possible_cpu(i) {
struct ext4_locality_group *lg;
lg = per_cpu_ptr(sbi->s_locality_groups, i);
mutex_init(&lg->lg_mutex);
for (j = 0; j < PREALLOC_TB_SIZE; j++)
INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
spin_lock_init(&lg->lg_prealloc_lock);
}
if (bdev_nonrot(sb->s_bdev))
sbi->s_mb_max_linear_groups = 0;
else
sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
/* init file for buddy data */
ret = ext4_mb_init_backend(sb);
if (ret != 0)
goto out_free_locality_groups;
return 0;
out_free_locality_groups:
free_percpu(sbi->s_locality_groups);
sbi->s_locality_groups = NULL;
out:
kfree(sbi->s_mb_avg_fragment_size);
kfree(sbi->s_mb_avg_fragment_size_locks);
kfree(sbi->s_mb_largest_free_orders);
kfree(sbi->s_mb_largest_free_orders_locks);
kfree(sbi->s_mb_offsets);
sbi->s_mb_offsets = NULL;
kfree(sbi->s_mb_maxs);
sbi->s_mb_maxs = NULL;
return ret;
}
/* need to called with the ext4 group lock held */
static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
{
struct ext4_prealloc_space *pa;
struct list_head *cur, *tmp;
int count = 0;
list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
list_del(&pa->pa_group_list);
count++;
kmem_cache_free(ext4_pspace_cachep, pa);
}
return count;
}
int ext4_mb_release(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
ext4_group_t i;
int num_meta_group_infos;
struct ext4_group_info *grinfo, ***group_info;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
int count;
if (test_opt(sb, DISCARD)) {
/*
* wait the discard work to drain all of ext4_free_data
*/
flush_work(&sbi->s_discard_work);
WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
}
if (sbi->s_group_info) {
for (i = 0; i < ngroups; i++) {
cond_resched();
grinfo = ext4_get_group_info(sb, i);
if (!grinfo)
continue;
mb_group_bb_bitmap_free(grinfo);
ext4_lock_group(sb, i);
count = ext4_mb_cleanup_pa(grinfo);
if (count)
mb_debug(sb, "mballoc: %d PAs left\n",
count);
ext4_unlock_group(sb, i);
kmem_cache_free(cachep, grinfo);
}
num_meta_group_infos = (ngroups +
EXT4_DESC_PER_BLOCK(sb) - 1) >>
EXT4_DESC_PER_BLOCK_BITS(sb);
rcu_read_lock();
group_info = rcu_dereference(sbi->s_group_info);
for (i = 0; i < num_meta_group_infos; i++)
kfree(group_info[i]);
kvfree(group_info);
rcu_read_unlock();
}
kfree(sbi->s_mb_avg_fragment_size);
kfree(sbi->s_mb_avg_fragment_size_locks);
kfree(sbi->s_mb_largest_free_orders);
kfree(sbi->s_mb_largest_free_orders_locks);
kfree(sbi->s_mb_offsets);
kfree(sbi->s_mb_maxs);
iput(sbi->s_buddy_cache);
if (sbi->s_mb_stats) {
ext4_msg(sb, KERN_INFO,
"mballoc: %u blocks %u reqs (%u success)",
atomic_read(&sbi->s_bal_allocated),
atomic_read(&sbi->s_bal_reqs),
atomic_read(&sbi->s_bal_success));
ext4_msg(sb, KERN_INFO,
"mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
"%u 2^N hits, %u breaks, %u lost",
atomic_read(&sbi->s_bal_ex_scanned),
atomic_read(&sbi->s_bal_groups_scanned),
atomic_read(&sbi->s_bal_goals),
atomic_read(&sbi->s_bal_2orders),
atomic_read(&sbi->s_bal_breaks),
atomic_read(&sbi->s_mb_lost_chunks));
ext4_msg(sb, KERN_INFO,
"mballoc: %u generated and it took %llu",
atomic_read(&sbi->s_mb_buddies_generated),
atomic64_read(&sbi->s_mb_generation_time));
ext4_msg(sb, KERN_INFO,
"mballoc: %u preallocated, %u discarded",
atomic_read(&sbi->s_mb_preallocated),
atomic_read(&sbi->s_mb_discarded));
}
free_percpu(sbi->s_locality_groups);
return 0;
}
static inline int ext4_issue_discard(struct super_block *sb,
ext4_group_t block_group, ext4_grpblk_t cluster, int count,
struct bio **biop)
{
ext4_fsblk_t discard_block;
discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
ext4_group_first_block_no(sb, block_group));
count = EXT4_C2B(EXT4_SB(sb), count);
trace_ext4_discard_blocks(sb,
(unsigned long long) discard_block, count);
if (biop) {
return __blkdev_issue_discard(sb->s_bdev,
(sector_t)discard_block << (sb->s_blocksize_bits - 9),
(sector_t)count << (sb->s_blocksize_bits - 9),
GFP_NOFS, biop);
} else
return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
}
static void ext4_free_data_in_buddy(struct super_block *sb,
struct ext4_free_data *entry)
{
struct ext4_buddy e4b;
struct ext4_group_info *db;
int err, count = 0;
mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
entry->efd_count, entry->efd_group, entry);
err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
/* we expect to find existing buddy because it's pinned */
BUG_ON(err != 0);
spin_lock(&EXT4_SB(sb)->s_md_lock);
EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
spin_unlock(&EXT4_SB(sb)->s_md_lock);
db = e4b.bd_info;
/* there are blocks to put in buddy to make them really free */
count += entry->efd_count;
ext4_lock_group(sb, entry->efd_group);
/* Take it out of per group rb tree */
rb_erase(&entry->efd_node, &(db->bb_free_root));
mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
/*
* Clear the trimmed flag for the group so that the next
* ext4_trim_fs can trim it.
* If the volume is mounted with -o discard, online discard
* is supported and the free blocks will be trimmed online.
*/
if (!test_opt(sb, DISCARD))
EXT4_MB_GRP_CLEAR_TRIMMED(db);
if (!db->bb_free_root.rb_node) {
/* No more items in the per group rb tree
* balance refcounts from ext4_mb_free_metadata()
*/
put_page(e4b.bd_buddy_page);
put_page(e4b.bd_bitmap_page);
}
ext4_unlock_group(sb, entry->efd_group);
ext4_mb_unload_buddy(&e4b);
mb_debug(sb, "freed %d blocks in 1 structures\n", count);
}
/*
* This function is called by the jbd2 layer once the commit has finished,
* so we know we can free the blocks that were released with that commit.
*/
void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_free_data *entry, *tmp;
LIST_HEAD(freed_data_list);
struct list_head *cut_pos = NULL;
bool wake;
spin_lock(&sbi->s_md_lock);
list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
if (entry->efd_tid != commit_tid)
break;
cut_pos = &entry->efd_list;
}
if (cut_pos)
list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
cut_pos);
spin_unlock(&sbi->s_md_lock);
list_for_each_entry(entry, &freed_data_list, efd_list)
ext4_free_data_in_buddy(sb, entry);
if (test_opt(sb, DISCARD)) {
spin_lock(&sbi->s_md_lock);
wake = list_empty(&sbi->s_discard_list);
list_splice_tail(&freed_data_list, &sbi->s_discard_list);
spin_unlock(&sbi->s_md_lock);
if (wake)
queue_work(system_unbound_wq, &sbi->s_discard_work);
} else {
list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
kmem_cache_free(ext4_free_data_cachep, entry);
}
}
int __init ext4_init_mballoc(void)
{
ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
SLAB_RECLAIM_ACCOUNT);
if (ext4_pspace_cachep == NULL)
goto out;
ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
SLAB_RECLAIM_ACCOUNT);
if (ext4_ac_cachep == NULL)
goto out_pa_free;
ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
SLAB_RECLAIM_ACCOUNT);
if (ext4_free_data_cachep == NULL)
goto out_ac_free;
return 0;
out_ac_free:
kmem_cache_destroy(ext4_ac_cachep);
out_pa_free:
kmem_cache_destroy(ext4_pspace_cachep);
out:
return -ENOMEM;
}
void ext4_exit_mballoc(void)
{
/*
* Wait for completion of call_rcu()'s on ext4_pspace_cachep
* before destroying the slab cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_pspace_cachep);
kmem_cache_destroy(ext4_ac_cachep);
kmem_cache_destroy(ext4_free_data_cachep);
ext4_groupinfo_destroy_slabs();
}
/*
* Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
* Returns 0 if success or error code
*/
static noinline_for_stack int
ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
handle_t *handle, unsigned int reserv_clstrs)
{
struct buffer_head *bitmap_bh = NULL;
struct ext4_group_desc *gdp;
struct buffer_head *gdp_bh;
struct ext4_sb_info *sbi;
struct super_block *sb;
ext4_fsblk_t block;
int err, len;
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(ac->ac_b_ex.fe_len <= 0);
sb = ac->ac_sb;
sbi = EXT4_SB(sb);
bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
if (IS_ERR(bitmap_bh)) {
return PTR_ERR(bitmap_bh);
}
BUFFER_TRACE(bitmap_bh, "getting write access");
err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
EXT4_JTR_NONE);
if (err)
goto out_err;
err = -EIO;
gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
if (!gdp)
goto out_err;
ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
ext4_free_group_clusters(sb, gdp));
BUFFER_TRACE(gdp_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
if (err)
goto out_err;
block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
"fs metadata", block, block+len);
/* File system mounted not to panic on error
* Fix the bitmap and return EFSCORRUPTED
* We leak some of the blocks here.
*/
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
ac->ac_b_ex.fe_len);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
if (!err)
err = -EFSCORRUPTED;
goto out_err;
}
ext4_lock_group(sb, ac->ac_b_ex.fe_group);
#ifdef AGGRESSIVE_CHECK
{
int i;
for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
bitmap_bh->b_data));
}
}
#endif
mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
ac->ac_b_ex.fe_len);
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
ext4_free_group_clusters_set(sb, gdp,
ext4_free_clusters_after_init(sb,
ac->ac_b_ex.fe_group, gdp));
}
len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
ext4_free_group_clusters_set(sb, gdp, len);
ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
/*
* Now reduce the dirty block count also. Should not go negative
*/
if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
/* release all the reserved blocks if non delalloc */
percpu_counter_sub(&sbi->s_dirtyclusters_counter,
reserv_clstrs);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi,
ac->ac_b_ex.fe_group);
atomic64_sub(ac->ac_b_ex.fe_len,
&sbi_array_rcu_deref(sbi, s_flex_groups,
flex_group)->free_clusters);
}
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
if (err)
goto out_err;
err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
out_err:
brelse(bitmap_bh);
return err;
}
/*
* Idempotent helper for Ext4 fast commit replay path to set the state of
* blocks in bitmaps and update counters.
*/
void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
int len, int state)
{
struct buffer_head *bitmap_bh = NULL;
struct ext4_group_desc *gdp;
struct buffer_head *gdp_bh;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t group;
ext4_grpblk_t blkoff;
int i, err = 0;
int already;
unsigned int clen, clen_changed, thisgrp_len;
while (len > 0) {
ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
/*
* Check to see if we are freeing blocks across a group
* boundary.
* In case of flex_bg, this can happen that (block, len) may
* span across more than one group. In that case we need to
* get the corresponding group metadata to work with.
* For this we have goto again loop.
*/
thisgrp_len = min_t(unsigned int, (unsigned int)len,
EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
clen = EXT4_NUM_B2C(sbi, thisgrp_len);
if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
ext4_error(sb, "Marking blocks in system zone - "
"Block = %llu, len = %u",
block, thisgrp_len);
bitmap_bh = NULL;
break;
}
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(bitmap_bh)) {
err = PTR_ERR(bitmap_bh);
bitmap_bh = NULL;
break;
}
err = -EIO;
gdp = ext4_get_group_desc(sb, group, &gdp_bh);
if (!gdp)
break;
ext4_lock_group(sb, group);
already = 0;
for (i = 0; i < clen; i++)
if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
!state)
already++;
clen_changed = clen - already;
if (state)
mb_set_bits(bitmap_bh->b_data, blkoff, clen);
else
mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
ext4_free_group_clusters_set(sb, gdp,
ext4_free_clusters_after_init(sb, group, gdp));
}
if (state)
clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
else
clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
ext4_free_group_clusters_set(sb, gdp, clen);
ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
ext4_group_desc_csum_set(sb, group, gdp);
ext4_unlock_group(sb, group);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi, group);
struct flex_groups *fg = sbi_array_rcu_deref(sbi,
s_flex_groups, flex_group);
if (state)
atomic64_sub(clen_changed, &fg->free_clusters);
else
atomic64_add(clen_changed, &fg->free_clusters);
}
err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
if (err)
break;
sync_dirty_buffer(bitmap_bh);
err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
sync_dirty_buffer(gdp_bh);
if (err)
break;
block += thisgrp_len;
len -= thisgrp_len;
brelse(bitmap_bh);
BUG_ON(len < 0);
}
if (err)
brelse(bitmap_bh);
}
/*
* here we normalize request for locality group
* Group request are normalized to s_mb_group_prealloc, which goes to
* s_strip if we set the same via mount option.
* s_mb_group_prealloc can be configured via
* /sys/fs/ext4/<partition>/mb_group_prealloc
*
* XXX: should we try to preallocate more than the group has now?
*/
static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg = ac->ac_lg;
BUG_ON(lg == NULL);
ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
}
/*
* This function returns the next element to look at during inode
* PA rbtree walk. We assume that we have held the inode PA rbtree lock
* (ei->i_prealloc_lock)
*
* new_start The start of the range we want to compare
* cur_start The existing start that we are comparing against
* node The node of the rb_tree
*/
static inline struct rb_node*
ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
{
if (new_start < cur_start)
return node->rb_left;
else
return node->rb_right;
}
static inline void
ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
ext4_lblk_t start, loff_t end)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
struct ext4_prealloc_space *tmp_pa;
ext4_lblk_t tmp_pa_start;
loff_t tmp_pa_end;
struct rb_node *iter;
read_lock(&ei->i_prealloc_lock);
for (iter = ei->i_prealloc_node.rb_node; iter;
iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
tmp_pa_start = tmp_pa->pa_lstart;
tmp_pa_end = pa_logical_end(sbi, tmp_pa);
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0)
BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
spin_unlock(&tmp_pa->pa_lock);
}
read_unlock(&ei->i_prealloc_lock);
}
/*
* Given an allocation context "ac" and a range "start", "end", check
* and adjust boundaries if the range overlaps with any of the existing
* preallocatoins stored in the corresponding inode of the allocation context.
*
* Parameters:
* ac allocation context
* start start of the new range
* end end of the new range
*/
static inline void
ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
ext4_lblk_t *start, loff_t *end)
{
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
struct rb_node *iter;
ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
loff_t new_end, tmp_pa_end, left_pa_end = -1;
new_start = *start;
new_end = *end;
/*
* Adjust the normalized range so that it doesn't overlap with any
* existing preallocated blocks(PAs). Make sure to hold the rbtree lock
* so it doesn't change underneath us.
*/
read_lock(&ei->i_prealloc_lock);
/* Step 1: find any one immediate neighboring PA of the normalized range */
for (iter = ei->i_prealloc_node.rb_node; iter;
iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
tmp_pa_start, iter)) {
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
tmp_pa_start = tmp_pa->pa_lstart;
tmp_pa_end = pa_logical_end(sbi, tmp_pa);
/* PA must not overlap original request */
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0)
BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
ac->ac_o_ex.fe_logical < tmp_pa_start));
spin_unlock(&tmp_pa->pa_lock);
}
/*
* Step 2: check if the found PA is left or right neighbor and
* get the other neighbor
*/
if (tmp_pa) {
if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
struct rb_node *tmp;
left_pa = tmp_pa;
tmp = rb_next(&left_pa->pa_node.inode_node);
if (tmp) {
right_pa = rb_entry(tmp,
struct ext4_prealloc_space,
pa_node.inode_node);
}
} else {
struct rb_node *tmp;
right_pa = tmp_pa;
tmp = rb_prev(&right_pa->pa_node.inode_node);
if (tmp) {
left_pa = rb_entry(tmp,
struct ext4_prealloc_space,
pa_node.inode_node);
}
}
}
/* Step 3: get the non deleted neighbors */
if (left_pa) {
for (iter = &left_pa->pa_node.inode_node;;
iter = rb_prev(iter)) {
if (!iter) {
left_pa = NULL;
break;
}
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
left_pa = tmp_pa;
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0) {
spin_unlock(&tmp_pa->pa_lock);
break;
}
spin_unlock(&tmp_pa->pa_lock);
}
}
if (right_pa) {
for (iter = &right_pa->pa_node.inode_node;;
iter = rb_next(iter)) {
if (!iter) {
right_pa = NULL;
break;
}
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
right_pa = tmp_pa;
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0) {
spin_unlock(&tmp_pa->pa_lock);
break;
}
spin_unlock(&tmp_pa->pa_lock);
}
}
if (left_pa) {
left_pa_end = pa_logical_end(sbi, left_pa);
BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
}
if (right_pa) {
right_pa_start = right_pa->pa_lstart;
BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
}
/* Step 4: trim our normalized range to not overlap with the neighbors */
if (left_pa) {
if (left_pa_end > new_start)
new_start = left_pa_end;
}
if (right_pa) {
if (right_pa_start < new_end)
new_end = right_pa_start;
}
read_unlock(&ei->i_prealloc_lock);
/* XXX: extra loop to check we really don't overlap preallocations */
ext4_mb_pa_assert_overlap(ac, new_start, new_end);
*start = new_start;
*end = new_end;
}
/*
* Normalization means making request better in terms of
* size and alignment
*/
static noinline_for_stack void
ext4_mb_normalize_request(struct ext4_allocation_context *ac,
struct ext4_allocation_request *ar)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_super_block *es = sbi->s_es;
int bsbits, max;
loff_t size, start_off, end;
loff_t orig_size __maybe_unused;
ext4_lblk_t start;
/* do normalize only data requests, metadata requests
do not need preallocation */
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return;
/* sometime caller may want exact blocks */
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
return;
/* caller may indicate that preallocation isn't
* required (it's a tail, for example) */
if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
return;
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
ext4_mb_normalize_group_request(ac);
return ;
}
bsbits = ac->ac_sb->s_blocksize_bits;
/* first, let's learn actual file size
* given current request is allocated */
size = extent_logical_end(sbi, &ac->ac_o_ex);
size = size << bsbits;
if (size < i_size_read(ac->ac_inode))
size = i_size_read(ac->ac_inode);
orig_size = size;
/* max size of free chunks */
max = 2 << bsbits;
#define NRL_CHECK_SIZE(req, size, max, chunk_size) \
(req <= (size) || max <= (chunk_size))
/* first, try to predict filesize */
/* XXX: should this table be tunable? */
start_off = 0;
if (size <= 16 * 1024) {
size = 16 * 1024;
} else if (size <= 32 * 1024) {
size = 32 * 1024;
} else if (size <= 64 * 1024) {
size = 64 * 1024;
} else if (size <= 128 * 1024) {
size = 128 * 1024;
} else if (size <= 256 * 1024) {
size = 256 * 1024;
} else if (size <= 512 * 1024) {
size = 512 * 1024;
} else if (size <= 1024 * 1024) {
size = 1024 * 1024;
} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(21 - bsbits)) << 21;
size = 2 * 1024 * 1024;
} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(22 - bsbits)) << 22;
size = 4 * 1024 * 1024;
} else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
(8<<20)>>bsbits, max, 8 * 1024)) {
start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
(23 - bsbits)) << 23;
size = 8 * 1024 * 1024;
} else {
start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
size = (loff_t) EXT4_C2B(sbi,
ac->ac_o_ex.fe_len) << bsbits;
}
size = size >> bsbits;
start = start_off >> bsbits;
/*
* For tiny groups (smaller than 8MB) the chosen allocation
* alignment may be larger than group size. Make sure the
* alignment does not move allocation to a different group which
* makes mballoc fail assertions later.
*/
start = max(start, rounddown(ac->ac_o_ex.fe_logical,
(ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
/* don't cover already allocated blocks in selected range */
if (ar->pleft && start <= ar->lleft) {
size -= ar->lleft + 1 - start;
start = ar->lleft + 1;
}
if (ar->pright && start + size - 1 >= ar->lright)
size -= start + size - ar->lright;
/*
* Trim allocation request for filesystems with artificially small
* groups.
*/
if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
end = start + size;
ext4_mb_pa_adjust_overlap(ac, &start, &end);
size = end - start;
/*
* In this function "start" and "size" are normalized for better
* alignment and length such that we could preallocate more blocks.
* This normalization is done such that original request of
* ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
* "size" boundaries.
* (Note fe_len can be relaxed since FS block allocation API does not
* provide gurantee on number of contiguous blocks allocation since that
* depends upon free space left, etc).
* In case of inode pa, later we use the allocated blocks
* [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
* range of goal/best blocks [start, size] to put it at the
* ac_o_ex.fe_logical extent of this inode.
* (See ext4_mb_use_inode_pa() for more details)
*/
if (start + size <= ac->ac_o_ex.fe_logical ||
start > ac->ac_o_ex.fe_logical) {
ext4_msg(ac->ac_sb, KERN_ERR,
"start %lu, size %lu, fe_logical %lu",
(unsigned long) start, (unsigned long) size,
(unsigned long) ac->ac_o_ex.fe_logical);
BUG();
}
BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
/* now prepare goal request */
/* XXX: is it better to align blocks WRT to logical
* placement or satisfy big request as is */
ac->ac_g_ex.fe_logical = start;
ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
/* define goal start in order to merge */
if (ar->pright && (ar->lright == (start + size)) &&
ar->pright >= size &&
ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
/* merge to the right */
ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
&ac->ac_g_ex.fe_group,
&ac->ac_g_ex.fe_start);
ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
}
if (ar->pleft && (ar->lleft + 1 == start) &&
ar->pleft + 1 < ext4_blocks_count(es)) {
/* merge to the left */
ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
&ac->ac_g_ex.fe_group,
&ac->ac_g_ex.fe_start);
ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
}
mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
orig_size, start);
}
static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
atomic_inc(&sbi->s_bal_reqs);
atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
atomic_inc(&sbi->s_bal_success);
atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
}
atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
atomic_inc(&sbi->s_bal_goals);
/* did we allocate as much as normalizer originally wanted? */
if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
atomic_inc(&sbi->s_bal_len_goals);
if (ac->ac_found > sbi->s_mb_max_to_scan)
atomic_inc(&sbi->s_bal_breaks);
}
if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
trace_ext4_mballoc_alloc(ac);
else
trace_ext4_mballoc_prealloc(ac);
}
/*
* Called on failure; free up any blocks from the inode PA for this
* context. We don't need this for MB_GROUP_PA because we only change
* pa_free in ext4_mb_release_context(), but on failure, we've already
* zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
*/
static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
{
struct ext4_prealloc_space *pa = ac->ac_pa;
struct ext4_buddy e4b;
int err;
if (pa == NULL) {
if (ac->ac_f_ex.fe_len == 0)
return;
err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
if (WARN_RATELIMIT(err,
"ext4: mb_load_buddy failed (%d)", err))
/*
* This should never happen since we pin the
* pages in the ext4_allocation_context so
* ext4_mb_load_buddy() should never fail.
*/
return;
ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
ac->ac_f_ex.fe_len);
ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
ext4_mb_unload_buddy(&e4b);
return;
}
if (pa->pa_type == MB_INODE_PA) {
spin_lock(&pa->pa_lock);
pa->pa_free += ac->ac_b_ex.fe_len;
spin_unlock(&pa->pa_lock);
}
}
/*
* use blocks preallocated to inode
*/
static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
struct ext4_prealloc_space *pa)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
ext4_fsblk_t start;
ext4_fsblk_t end;
int len;
/* found preallocated blocks, use them */
start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
len = EXT4_NUM_B2C(sbi, end - start);
ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
&ac->ac_b_ex.fe_start);
ac->ac_b_ex.fe_len = len;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_pa = pa;
BUG_ON(start < pa->pa_pstart);
BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
BUG_ON(pa->pa_free < len);
BUG_ON(ac->ac_b_ex.fe_len <= 0);
pa->pa_free -= len;
mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
}
/*
* use blocks preallocated to locality group
*/
static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
struct ext4_prealloc_space *pa)
{
unsigned int len = ac->ac_o_ex.fe_len;
ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
&ac->ac_b_ex.fe_group,
&ac->ac_b_ex.fe_start);
ac->ac_b_ex.fe_len = len;
ac->ac_status = AC_STATUS_FOUND;
ac->ac_pa = pa;
/* we don't correct pa_pstart or pa_len here to avoid
* possible race when the group is being loaded concurrently
* instead we correct pa later, after blocks are marked
* in on-disk bitmap -- see ext4_mb_release_context()
* Other CPUs are prevented from allocating from this pa by lg_mutex
*/
mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
pa->pa_lstart, len, pa);
}
/*
* Return the prealloc space that have minimal distance
* from the goal block. @cpa is the prealloc
* space that is having currently known minimal distance
* from the goal block.
*/
static struct ext4_prealloc_space *
ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
struct ext4_prealloc_space *pa,
struct ext4_prealloc_space *cpa)
{
ext4_fsblk_t cur_distance, new_distance;
if (cpa == NULL) {
atomic_inc(&pa->pa_count);
return pa;
}
cur_distance = abs(goal_block - cpa->pa_pstart);
new_distance = abs(goal_block - pa->pa_pstart);
if (cur_distance <= new_distance)
return cpa;
/* drop the previous reference */
atomic_dec(&cpa->pa_count);
atomic_inc(&pa->pa_count);
return pa;
}
/*
* check if found pa meets EXT4_MB_HINT_GOAL_ONLY
*/
static bool
ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
struct ext4_prealloc_space *pa)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
ext4_fsblk_t start;
if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
return true;
/*
* If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
* in ext4_mb_normalize_request and will keep same with ac_o_ex
* from ext4_mb_initialize_context. Choose ac_g_ex here to keep
* consistent with ext4_mb_find_by_goal.
*/
start = pa->pa_pstart +
(ac->ac_g_ex.fe_logical - pa->pa_lstart);
if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
return false;
if (ac->ac_g_ex.fe_len > pa->pa_len -
EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
return false;
return true;
}
/*
* search goal blocks in preallocated space
*/
static noinline_for_stack bool
ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int order, i;
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
struct ext4_locality_group *lg;
struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
struct rb_node *iter;
ext4_fsblk_t goal_block;
/* only data can be preallocated */
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return false;
/*
* first, try per-file preallocation by searching the inode pa rbtree.
*
* Here, we can't do a direct traversal of the tree because
* ext4_mb_discard_group_preallocation() can paralelly mark the pa
* deleted and that can cause direct traversal to skip some entries.
*/
read_lock(&ei->i_prealloc_lock);
if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
goto try_group_pa;
}
/*
* Step 1: Find a pa with logical start immediately adjacent to the
* original logical start. This could be on the left or right.
*
* (tmp_pa->pa_lstart never changes so we can skip locking for it).
*/
for (iter = ei->i_prealloc_node.rb_node; iter;
iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
tmp_pa->pa_lstart, iter)) {
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
}
/*
* Step 2: The adjacent pa might be to the right of logical start, find
* the left adjacent pa. After this step we'd have a valid tmp_pa whose
* logical start is towards the left of original request's logical start
*/
if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
struct rb_node *tmp;
tmp = rb_prev(&tmp_pa->pa_node.inode_node);
if (tmp) {
tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
pa_node.inode_node);
} else {
/*
* If there is no adjacent pa to the left then finding
* an overlapping pa is not possible hence stop searching
* inode pa tree
*/
goto try_group_pa;
}
}
BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
/*
* Step 3: If the left adjacent pa is deleted, keep moving left to find
* the first non deleted adjacent pa. After this step we should have a
* valid tmp_pa which is guaranteed to be non deleted.
*/
for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
if (!iter) {
/*
* no non deleted left adjacent pa, so stop searching
* inode pa tree
*/
goto try_group_pa;
}
tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0) {
/*
* We will keep holding the pa_lock from
* this point on because we don't want group discard
* to delete this pa underneath us. Since group
* discard is anyways an ENOSPC operation it
* should be okay for it to wait a few more cycles.
*/
break;
} else {
spin_unlock(&tmp_pa->pa_lock);
}
}
BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
BUG_ON(tmp_pa->pa_deleted == 1);
/*
* Step 4: We now have the non deleted left adjacent pa. Only this
* pa can possibly satisfy the request hence check if it overlaps
* original logical start and stop searching if it doesn't.
*/
if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
spin_unlock(&tmp_pa->pa_lock);
goto try_group_pa;
}
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
(tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
EXT4_MAX_BLOCK_FILE_PHYS)) {
/*
* Since PAs don't overlap, we won't find any other PA to
* satisfy this.
*/
spin_unlock(&tmp_pa->pa_lock);
goto try_group_pa;
}
if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
atomic_inc(&tmp_pa->pa_count);
ext4_mb_use_inode_pa(ac, tmp_pa);
spin_unlock(&tmp_pa->pa_lock);
read_unlock(&ei->i_prealloc_lock);
return true;
} else {
/*
* We found a valid overlapping pa but couldn't use it because
* it had no free blocks. This should ideally never happen
* because:
*
* 1. When a new inode pa is added to rbtree it must have
* pa_free > 0 since otherwise we won't actually need
* preallocation.
*
* 2. An inode pa that is in the rbtree can only have it's
* pa_free become zero when another thread calls:
* ext4_mb_new_blocks
* ext4_mb_use_preallocated
* ext4_mb_use_inode_pa
*
* 3. Further, after the above calls make pa_free == 0, we will
* immediately remove it from the rbtree in:
* ext4_mb_new_blocks
* ext4_mb_release_context
* ext4_mb_put_pa
*
* 4. Since the pa_free becoming 0 and pa_free getting removed
* from tree both happen in ext4_mb_new_blocks, which is always
* called with i_data_sem held for data allocations, we can be
* sure that another process will never see a pa in rbtree with
* pa_free == 0.
*/
WARN_ON_ONCE(tmp_pa->pa_free == 0);
}
spin_unlock(&tmp_pa->pa_lock);
try_group_pa:
read_unlock(&ei->i_prealloc_lock);
/* can we use group allocation? */
if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
return false;
/* inode may have no locality group for some reason */
lg = ac->ac_lg;
if (lg == NULL)
return false;
order = fls(ac->ac_o_ex.fe_len) - 1;
if (order > PREALLOC_TB_SIZE - 1)
/* The max size of hash table is PREALLOC_TB_SIZE */
order = PREALLOC_TB_SIZE - 1;
goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
/*
* search for the prealloc space that is having
* minimal distance from the goal block.
*/
for (i = order; i < PREALLOC_TB_SIZE; i++) {
rcu_read_lock();
list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
pa_node.lg_list) {
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted == 0 &&
tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
cpa = ext4_mb_check_group_pa(goal_block,
tmp_pa, cpa);
}
spin_unlock(&tmp_pa->pa_lock);
}
rcu_read_unlock();
}
if (cpa) {
ext4_mb_use_group_pa(ac, cpa);
return true;
}
return false;
}
/*
* the function goes through all block freed in the group
* but not yet committed and marks them used in in-core bitmap.
* buddy must be generated from this bitmap
* Need to be called with the ext4 group lock held
*/
static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
ext4_group_t group)
{
struct rb_node *n;
struct ext4_group_info *grp;
struct ext4_free_data *entry;
grp = ext4_get_group_info(sb, group);
if (!grp)
return;
n = rb_first(&(grp->bb_free_root));
while (n) {
entry = rb_entry(n, struct ext4_free_data, efd_node);
mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
n = rb_next(n);
}
}
/*
* the function goes through all preallocation in this group and marks them
* used in in-core bitmap. buddy must be generated from this bitmap
* Need to be called with ext4 group lock held
*/
static noinline_for_stack
void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
ext4_group_t group)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct ext4_prealloc_space *pa;
struct list_head *cur;
ext4_group_t groupnr;
ext4_grpblk_t start;
int preallocated = 0;
int len;
if (!grp)
return;
/* all form of preallocation discards first load group,
* so the only competing code is preallocation use.
* we don't need any locking here
* notice we do NOT ignore preallocations with pa_deleted
* otherwise we could leave used blocks available for
* allocation in buddy when concurrent ext4_mb_put_pa()
* is dropping preallocation
*/
list_for_each(cur, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
spin_lock(&pa->pa_lock);
ext4_get_group_no_and_offset(sb, pa->pa_pstart,
&groupnr, &start);
len = pa->pa_len;
spin_unlock(&pa->pa_lock);
if (unlikely(len == 0))
continue;
BUG_ON(groupnr != group);
mb_set_bits(bitmap, start, len);
preallocated += len;
}
mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
}
static void ext4_mb_mark_pa_deleted(struct super_block *sb,
struct ext4_prealloc_space *pa)
{
struct ext4_inode_info *ei;
if (pa->pa_deleted) {
ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
pa->pa_type, pa->pa_pstart, pa->pa_lstart,
pa->pa_len);
return;
}
pa->pa_deleted = 1;
if (pa->pa_type == MB_INODE_PA) {
ei = EXT4_I(pa->pa_inode);
atomic_dec(&ei->i_prealloc_active);
}
}
static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
{
BUG_ON(!pa);
BUG_ON(atomic_read(&pa->pa_count));
BUG_ON(pa->pa_deleted == 0);
kmem_cache_free(ext4_pspace_cachep, pa);
}
static void ext4_mb_pa_callback(struct rcu_head *head)
{
struct ext4_prealloc_space *pa;
pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
ext4_mb_pa_free(pa);
}
/*
* drops a reference to preallocated space descriptor
* if this was the last reference and the space is consumed
*/
static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
struct super_block *sb, struct ext4_prealloc_space *pa)
{
ext4_group_t grp;
ext4_fsblk_t grp_blk;
struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
/* in this short window concurrent discard can set pa_deleted */
spin_lock(&pa->pa_lock);
if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
spin_unlock(&pa->pa_lock);
return;
}
if (pa->pa_deleted == 1) {
spin_unlock(&pa->pa_lock);
return;
}
ext4_mb_mark_pa_deleted(sb, pa);
spin_unlock(&pa->pa_lock);
grp_blk = pa->pa_pstart;
/*
* If doing group-based preallocation, pa_pstart may be in the
* next group when pa is used up
*/
if (pa->pa_type == MB_GROUP_PA)
grp_blk--;
grp = ext4_get_group_number(sb, grp_blk);
/*
* possible race:
*
* P1 (buddy init) P2 (regular allocation)
* find block B in PA
* copy on-disk bitmap to buddy
* mark B in on-disk bitmap
* drop PA from group
* mark all PAs in buddy
*
* thus, P1 initializes buddy with B available. to prevent this
* we make "copy" and "mark all PAs" atomic and serialize "drop PA"
* against that pair
*/
ext4_lock_group(sb, grp);
list_del(&pa->pa_group_list);
ext4_unlock_group(sb, grp);
if (pa->pa_type == MB_INODE_PA) {
write_lock(pa->pa_node_lock.inode_lock);
rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
write_unlock(pa->pa_node_lock.inode_lock);
ext4_mb_pa_free(pa);
} else {
spin_lock(pa->pa_node_lock.lg_lock);
list_del_rcu(&pa->pa_node.lg_list);
spin_unlock(pa->pa_node_lock.lg_lock);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
}
static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
{
struct rb_node **iter = &root->rb_node, *parent = NULL;
struct ext4_prealloc_space *iter_pa, *new_pa;
ext4_lblk_t iter_start, new_start;
while (*iter) {
iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
pa_node.inode_node);
new_pa = rb_entry(new, struct ext4_prealloc_space,
pa_node.inode_node);
iter_start = iter_pa->pa_lstart;
new_start = new_pa->pa_lstart;
parent = *iter;
if (new_start < iter_start)
iter = &((*iter)->rb_left);
else
iter = &((*iter)->rb_right);
}
rb_link_node(new, parent, iter);
rb_insert_color(new, root);
}
/*
* creates new preallocated space for given inode
*/
static noinline_for_stack void
ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_prealloc_space *pa;
struct ext4_group_info *grp;
struct ext4_inode_info *ei;
/* preallocate only when found space is larger then requested */
BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
BUG_ON(ac->ac_pa == NULL);
pa = ac->ac_pa;
if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
struct ext4_free_extent ex = {
.fe_logical = ac->ac_g_ex.fe_logical,
.fe_len = ac->ac_orig_goal_len,
};
loff_t orig_goal_end = extent_logical_end(sbi, &ex);
/* we can't allocate as much as normalizer wants.
* so, found space must get proper lstart
* to cover original request */
BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
/*
* Use the below logic for adjusting best extent as it keeps
* fragmentation in check while ensuring logical range of best
* extent doesn't overflow out of goal extent:
*
* 1. Check if best ex can be kept at end of goal (before
* cr_best_avail trimmed it) and still cover original start
* 2. Else, check if best ex can be kept at start of goal and
* still cover original start
* 3. Else, keep the best ex at start of original request.
*/
ex.fe_len = ac->ac_b_ex.fe_len;
ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
goto adjust_bex;
ex.fe_logical = ac->ac_g_ex.fe_logical;
if (ac->ac_o_ex.fe_logical < extent_logical_end(sbi, &ex))
goto adjust_bex;
ex.fe_logical = ac->ac_o_ex.fe_logical;
adjust_bex:
ac->ac_b_ex.fe_logical = ex.fe_logical;
BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
}
pa->pa_lstart = ac->ac_b_ex.fe_logical;
pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
pa->pa_len = ac->ac_b_ex.fe_len;
pa->pa_free = pa->pa_len;
spin_lock_init(&pa->pa_lock);
INIT_LIST_HEAD(&pa->pa_group_list);
pa->pa_deleted = 0;
pa->pa_type = MB_INODE_PA;
mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
pa->pa_len, pa->pa_lstart);
trace_ext4_mb_new_inode_pa(ac, pa);
atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
ext4_mb_use_inode_pa(ac, pa);
ei = EXT4_I(ac->ac_inode);
grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
if (!grp)
return;
pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
pa->pa_inode = ac->ac_inode;
list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
write_lock(pa->pa_node_lock.inode_lock);
ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
write_unlock(pa->pa_node_lock.inode_lock);
atomic_inc(&ei->i_prealloc_active);
}
/*
* creates new preallocated space for locality group inodes belongs to
*/
static noinline_for_stack void
ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg;
struct ext4_prealloc_space *pa;
struct ext4_group_info *grp;
/* preallocate only when found space is larger then requested */
BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
BUG_ON(ac->ac_status != AC_STATUS_FOUND);
BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
BUG_ON(ac->ac_pa == NULL);
pa = ac->ac_pa;
pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
pa->pa_lstart = pa->pa_pstart;
pa->pa_len = ac->ac_b_ex.fe_len;
pa->pa_free = pa->pa_len;
spin_lock_init(&pa->pa_lock);
INIT_LIST_HEAD(&pa->pa_node.lg_list);
INIT_LIST_HEAD(&pa->pa_group_list);
pa->pa_deleted = 0;
pa->pa_type = MB_GROUP_PA;
mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
pa->pa_len, pa->pa_lstart);
trace_ext4_mb_new_group_pa(ac, pa);
ext4_mb_use_group_pa(ac, pa);
atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
if (!grp)
return;
lg = ac->ac_lg;
BUG_ON(lg == NULL);
pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
pa->pa_inode = NULL;
list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
/*
* We will later add the new pa to the right bucket
* after updating the pa_free in ext4_mb_release_context
*/
}
static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
{
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
ext4_mb_new_group_pa(ac);
else
ext4_mb_new_inode_pa(ac);
}
/*
* finds all unused blocks in on-disk bitmap, frees them in
* in-core bitmap and buddy.
* @pa must be unlinked from inode and group lists, so that
* nobody else can find/use it.
* the caller MUST hold group/inode locks.
* TODO: optimize the case when there are no in-core structures yet
*/
static noinline_for_stack int
ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
struct ext4_prealloc_space *pa)
{
struct super_block *sb = e4b->bd_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned int end;
unsigned int next;
ext4_group_t group;
ext4_grpblk_t bit;
unsigned long long grp_blk_start;
int free = 0;
BUG_ON(pa->pa_deleted == 0);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
end = bit + pa->pa_len;
while (bit < end) {
bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
if (bit >= end)
break;
next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
mb_debug(sb, "free preallocated %u/%u in group %u\n",
(unsigned) ext4_group_first_block_no(sb, group) + bit,
(unsigned) next - bit, (unsigned) group);
free += next - bit;
trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
EXT4_C2B(sbi, bit)),
next - bit);
mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
bit = next + 1;
}
if (free != pa->pa_free) {
ext4_msg(e4b->bd_sb, KERN_CRIT,
"pa %p: logic %lu, phys. %lu, len %d",
pa, (unsigned long) pa->pa_lstart,
(unsigned long) pa->pa_pstart,
pa->pa_len);
ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
free, pa->pa_free);
/*
* pa is already deleted so we use the value obtained
* from the bitmap and continue.
*/
}
atomic_add(free, &sbi->s_mb_discarded);
return 0;
}
static noinline_for_stack int
ext4_mb_release_group_pa(struct ext4_buddy *e4b,
struct ext4_prealloc_space *pa)
{
struct super_block *sb = e4b->bd_sb;
ext4_group_t group;
ext4_grpblk_t bit;
trace_ext4_mb_release_group_pa(sb, pa);
BUG_ON(pa->pa_deleted == 0);
ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
e4b->bd_group, group, pa->pa_pstart);
return 0;
}
mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
return 0;
}
/*
* releases all preallocations in given group
*
* first, we need to decide discard policy:
* - when do we discard
* 1) ENOSPC
* - how many do we discard
* 1) how many requested
*/
static noinline_for_stack int
ext4_mb_discard_group_preallocations(struct super_block *sb,
ext4_group_t group, int *busy)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct buffer_head *bitmap_bh = NULL;
struct ext4_prealloc_space *pa, *tmp;
LIST_HEAD(list);
struct ext4_buddy e4b;
struct ext4_inode_info *ei;
int err;
int free = 0;
if (!grp)
return 0;
mb_debug(sb, "discard preallocation for group %u\n", group);
if (list_empty(&grp->bb_prealloc_list))
goto out_dbg;
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(bitmap_bh)) {
err = PTR_ERR(bitmap_bh);
ext4_error_err(sb, -err,
"Error %d reading block bitmap for %u",
err, group);
goto out_dbg;
}
err = ext4_mb_load_buddy(sb, group, &e4b);
if (err) {
ext4_warning(sb, "Error %d loading buddy information for %u",
err, group);
put_bh(bitmap_bh);
goto out_dbg;
}
ext4_lock_group(sb, group);
list_for_each_entry_safe(pa, tmp,
&grp->bb_prealloc_list, pa_group_list) {
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
spin_unlock(&pa->pa_lock);
*busy = 1;
continue;
}
if (pa->pa_deleted) {
spin_unlock(&pa->pa_lock);
continue;
}
/* seems this one can be freed ... */
ext4_mb_mark_pa_deleted(sb, pa);
if (!free)
this_cpu_inc(discard_pa_seq);
/* we can trust pa_free ... */
free += pa->pa_free;
spin_unlock(&pa->pa_lock);
list_del(&pa->pa_group_list);
list_add(&pa->u.pa_tmp_list, &list);
}
/* now free all selected PAs */
list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
/* remove from object (inode or locality group) */
if (pa->pa_type == MB_GROUP_PA) {
spin_lock(pa->pa_node_lock.lg_lock);
list_del_rcu(&pa->pa_node.lg_list);
spin_unlock(pa->pa_node_lock.lg_lock);
} else {
write_lock(pa->pa_node_lock.inode_lock);
ei = EXT4_I(pa->pa_inode);
rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
write_unlock(pa->pa_node_lock.inode_lock);
}
list_del(&pa->u.pa_tmp_list);
if (pa->pa_type == MB_GROUP_PA) {
ext4_mb_release_group_pa(&e4b, pa);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
} else {
ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
ext4_mb_pa_free(pa);
}
}
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
put_bh(bitmap_bh);
out_dbg:
mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
free, group, grp->bb_free);
return free;
}
/*
* releases all non-used preallocated blocks for given inode
*
* It's important to discard preallocations under i_data_sem
* We don't want another block to be served from the prealloc
* space when we are discarding the inode prealloc space.
*
* FIXME!! Make sure it is valid at all the call sites
*/
void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct super_block *sb = inode->i_sb;
struct buffer_head *bitmap_bh = NULL;
struct ext4_prealloc_space *pa, *tmp;
ext4_group_t group = 0;
LIST_HEAD(list);
struct ext4_buddy e4b;
struct rb_node *iter;
int err;
if (!S_ISREG(inode->i_mode)) {
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
return;
mb_debug(sb, "discard preallocation for inode %lu\n",
inode->i_ino);
trace_ext4_discard_preallocations(inode,
atomic_read(&ei->i_prealloc_active), needed);
if (needed == 0)
needed = UINT_MAX;
repeat:
/* first, collect all pa's in the inode */
write_lock(&ei->i_prealloc_lock);
for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
iter = rb_next(iter)) {
pa = rb_entry(iter, struct ext4_prealloc_space,
pa_node.inode_node);
BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
/* this shouldn't happen often - nobody should
* use preallocation while we're discarding it */
spin_unlock(&pa->pa_lock);
write_unlock(&ei->i_prealloc_lock);
ext4_msg(sb, KERN_ERR,
"uh-oh! used pa while discarding");
WARN_ON(1);
schedule_timeout_uninterruptible(HZ);
goto repeat;
}
if (pa->pa_deleted == 0) {
ext4_mb_mark_pa_deleted(sb, pa);
spin_unlock(&pa->pa_lock);
rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
list_add(&pa->u.pa_tmp_list, &list);
needed--;
continue;
}
/* someone is deleting pa right now */
spin_unlock(&pa->pa_lock);
write_unlock(&ei->i_prealloc_lock);
/* we have to wait here because pa_deleted
* doesn't mean pa is already unlinked from
* the list. as we might be called from
* ->clear_inode() the inode will get freed
* and concurrent thread which is unlinking
* pa from inode's list may access already
* freed memory, bad-bad-bad */
/* XXX: if this happens too often, we can
* add a flag to force wait only in case
* of ->clear_inode(), but not in case of
* regular truncate */
schedule_timeout_uninterruptible(HZ);
goto repeat;
}
write_unlock(&ei->i_prealloc_lock);
list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
BUG_ON(pa->pa_type != MB_INODE_PA);
group = ext4_get_group_number(sb, pa->pa_pstart);
err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
GFP_NOFS|__GFP_NOFAIL);
if (err) {
ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
err, group);
continue;
}
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(bitmap_bh)) {
err = PTR_ERR(bitmap_bh);
ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
err, group);
ext4_mb_unload_buddy(&e4b);
continue;
}
ext4_lock_group(sb, group);
list_del(&pa->pa_group_list);
ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
put_bh(bitmap_bh);
list_del(&pa->u.pa_tmp_list);
ext4_mb_pa_free(pa);
}
}
static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
{
struct ext4_prealloc_space *pa;
BUG_ON(ext4_pspace_cachep == NULL);
pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
if (!pa)
return -ENOMEM;
atomic_set(&pa->pa_count, 1);
ac->ac_pa = pa;
return 0;
}
static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
{
struct ext4_prealloc_space *pa = ac->ac_pa;
BUG_ON(!pa);
ac->ac_pa = NULL;
WARN_ON(!atomic_dec_and_test(&pa->pa_count));
/*
* current function is only called due to an error or due to
* len of found blocks < len of requested blocks hence the PA has not
* been added to grp->bb_prealloc_list. So we don't need to lock it
*/
pa->pa_deleted = 1;
ext4_mb_pa_free(pa);
}
#ifdef CONFIG_EXT4_DEBUG
static inline void ext4_mb_show_pa(struct super_block *sb)
{
ext4_group_t i, ngroups;
if (ext4_forced_shutdown(sb))
return;
ngroups = ext4_get_groups_count(sb);
mb_debug(sb, "groups: ");
for (i = 0; i < ngroups; i++) {
struct ext4_group_info *grp = ext4_get_group_info(sb, i);
struct ext4_prealloc_space *pa;
ext4_grpblk_t start;
struct list_head *cur;
if (!grp)
continue;
ext4_lock_group(sb, i);
list_for_each(cur, &grp->bb_prealloc_list) {
pa = list_entry(cur, struct ext4_prealloc_space,
pa_group_list);
spin_lock(&pa->pa_lock);
ext4_get_group_no_and_offset(sb, pa->pa_pstart,
NULL, &start);
spin_unlock(&pa->pa_lock);
mb_debug(sb, "PA:%u:%d:%d\n", i, start,
pa->pa_len);
}
ext4_unlock_group(sb, i);
mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
grp->bb_fragments);
}
}
static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
{
struct super_block *sb = ac->ac_sb;
if (ext4_forced_shutdown(sb))
return;
mb_debug(sb, "Can't allocate:"
" Allocation context details:");
mb_debug(sb, "status %u flags 0x%x",
ac->ac_status, ac->ac_flags);
mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
"goal %lu/%lu/%lu@%lu, "
"best %lu/%lu/%lu@%lu cr %d",
(unsigned long)ac->ac_o_ex.fe_group,
(unsigned long)ac->ac_o_ex.fe_start,
(unsigned long)ac->ac_o_ex.fe_len,
(unsigned long)ac->ac_o_ex.fe_logical,
(unsigned long)ac->ac_g_ex.fe_group,
(unsigned long)ac->ac_g_ex.fe_start,
(unsigned long)ac->ac_g_ex.fe_len,
(unsigned long)ac->ac_g_ex.fe_logical,
(unsigned long)ac->ac_b_ex.fe_group,
(unsigned long)ac->ac_b_ex.fe_start,
(unsigned long)ac->ac_b_ex.fe_len,
(unsigned long)ac->ac_b_ex.fe_logical,
(int)ac->ac_criteria);
mb_debug(sb, "%u found", ac->ac_found);
mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
if (ac->ac_pa)
mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
"group pa" : "inode pa");
ext4_mb_show_pa(sb);
}
#else
static inline void ext4_mb_show_pa(struct super_block *sb)
{
}
static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
{
ext4_mb_show_pa(ac->ac_sb);
}
#endif
/*
* We use locality group preallocation for small size file. The size of the
* file is determined by the current size or the resulting size after
* allocation which ever is larger
*
* One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
*/
static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
int bsbits = ac->ac_sb->s_blocksize_bits;
loff_t size, isize;
bool inode_pa_eligible, group_pa_eligible;
if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
return;
if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
return;
group_pa_eligible = sbi->s_mb_group_prealloc > 0;
inode_pa_eligible = true;
size = extent_logical_end(sbi, &ac->ac_o_ex);
isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
>> bsbits;
/* No point in using inode preallocation for closed files */
if ((size == isize) && !ext4_fs_is_busy(sbi) &&
!inode_is_open_for_write(ac->ac_inode))
inode_pa_eligible = false;
size = max(size, isize);
/* Don't use group allocation for large files */
if (size > sbi->s_mb_stream_request)
group_pa_eligible = false;
if (!group_pa_eligible) {
if (inode_pa_eligible)
ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
else
ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
return;
}
BUG_ON(ac->ac_lg != NULL);
/*
* locality group prealloc space are per cpu. The reason for having
* per cpu locality group is to reduce the contention between block
* request from multiple CPUs.
*/
ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
/* we're going to use group allocation */
ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
/* serialize all allocations in the group */
mutex_lock(&ac->ac_lg->lg_mutex);
}
static noinline_for_stack void
ext4_mb_initialize_context(struct ext4_allocation_context *ac,
struct ext4_allocation_request *ar)
{
struct super_block *sb = ar->inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t group;
unsigned int len;
ext4_fsblk_t goal;
ext4_grpblk_t block;
/* we can't allocate > group size */
len = ar->len;
/* just a dirty hack to filter too big requests */
if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
len = EXT4_CLUSTERS_PER_GROUP(sb);
/* start searching from the goal */
goal = ar->goal;
if (goal < le32_to_cpu(es->s_first_data_block) ||
goal >= ext4_blocks_count(es))
goal = le32_to_cpu(es->s_first_data_block);
ext4_get_group_no_and_offset(sb, goal, &group, &block);
/* set up allocation goals */
ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
ac->ac_status = AC_STATUS_CONTINUE;
ac->ac_sb = sb;
ac->ac_inode = ar->inode;
ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
ac->ac_o_ex.fe_group = group;
ac->ac_o_ex.fe_start = block;
ac->ac_o_ex.fe_len = len;
ac->ac_g_ex = ac->ac_o_ex;
ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
ac->ac_flags = ar->flags;
/* we have to define context: we'll work with a file or
* locality group. this is a policy, actually */
ext4_mb_group_or_file(ac);
mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
"left: %u/%u, right %u/%u to %swritable\n",
(unsigned) ar->len, (unsigned) ar->logical,
(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
(unsigned) ar->lleft, (unsigned) ar->pleft,
(unsigned) ar->lright, (unsigned) ar->pright,
inode_is_open_for_write(ar->inode) ? "" : "non-");
}
static noinline_for_stack void
ext4_mb_discard_lg_preallocations(struct super_block *sb,
struct ext4_locality_group *lg,
int order, int total_entries)
{
ext4_group_t group = 0;
struct ext4_buddy e4b;
LIST_HEAD(discard_list);
struct ext4_prealloc_space *pa, *tmp;
mb_debug(sb, "discard locality group preallocation\n");
spin_lock(&lg->lg_prealloc_lock);
list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
pa_node.lg_list,
lockdep_is_held(&lg->lg_prealloc_lock)) {
spin_lock(&pa->pa_lock);
if (atomic_read(&pa->pa_count)) {
/*
* This is the pa that we just used
* for block allocation. So don't
* free that
*/
spin_unlock(&pa->pa_lock);
continue;
}
if (pa->pa_deleted) {
spin_unlock(&pa->pa_lock);
continue;
}
/* only lg prealloc space */
BUG_ON(pa->pa_type != MB_GROUP_PA);
/* seems this one can be freed ... */
ext4_mb_mark_pa_deleted(sb, pa);
spin_unlock(&pa->pa_lock);
list_del_rcu(&pa->pa_node.lg_list);
list_add(&pa->u.pa_tmp_list, &discard_list);
total_entries--;
if (total_entries <= 5) {
/*
* we want to keep only 5 entries
* allowing it to grow to 8. This
* mak sure we don't call discard
* soon for this list.
*/
break;
}
}
spin_unlock(&lg->lg_prealloc_lock);
list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
int err;
group = ext4_get_group_number(sb, pa->pa_pstart);
err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
GFP_NOFS|__GFP_NOFAIL);
if (err) {
ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
err, group);
continue;
}
ext4_lock_group(sb, group);
list_del(&pa->pa_group_list);
ext4_mb_release_group_pa(&e4b, pa);
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
list_del(&pa->u.pa_tmp_list);
call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
}
}
/*
* We have incremented pa_count. So it cannot be freed at this
* point. Also we hold lg_mutex. So no parallel allocation is
* possible from this lg. That means pa_free cannot be updated.
*
* A parallel ext4_mb_discard_group_preallocations is possible.
* which can cause the lg_prealloc_list to be updated.
*/
static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
{
int order, added = 0, lg_prealloc_count = 1;
struct super_block *sb = ac->ac_sb;
struct ext4_locality_group *lg = ac->ac_lg;
struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
order = fls(pa->pa_free) - 1;
if (order > PREALLOC_TB_SIZE - 1)
/* The max size of hash table is PREALLOC_TB_SIZE */
order = PREALLOC_TB_SIZE - 1;
/* Add the prealloc space to lg */
spin_lock(&lg->lg_prealloc_lock);
list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
pa_node.lg_list,
lockdep_is_held(&lg->lg_prealloc_lock)) {
spin_lock(&tmp_pa->pa_lock);
if (tmp_pa->pa_deleted) {
spin_unlock(&tmp_pa->pa_lock);
continue;
}
if (!added && pa->pa_free < tmp_pa->pa_free) {
/* Add to the tail of the previous entry */
list_add_tail_rcu(&pa->pa_node.lg_list,
&tmp_pa->pa_node.lg_list);
added = 1;
/*
* we want to count the total
* number of entries in the list
*/
}
spin_unlock(&tmp_pa->pa_lock);
lg_prealloc_count++;
}
if (!added)
list_add_tail_rcu(&pa->pa_node.lg_list,
&lg->lg_prealloc_list[order]);
spin_unlock(&lg->lg_prealloc_lock);
/* Now trim the list to be not more than 8 elements */
if (lg_prealloc_count > 8)
ext4_mb_discard_lg_preallocations(sb, lg,
order, lg_prealloc_count);
}
/*
* release all resource we used in allocation
*/
static int ext4_mb_release_context(struct ext4_allocation_context *ac)
{
struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
struct ext4_prealloc_space *pa = ac->ac_pa;
if (pa) {
if (pa->pa_type == MB_GROUP_PA) {
/* see comment in ext4_mb_use_group_pa() */
spin_lock(&pa->pa_lock);
pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
pa->pa_free -= ac->ac_b_ex.fe_len;
pa->pa_len -= ac->ac_b_ex.fe_len;
spin_unlock(&pa->pa_lock);
/*
* We want to add the pa to the right bucket.
* Remove it from the list and while adding
* make sure the list to which we are adding
* doesn't grow big.
*/
if (likely(pa->pa_free)) {
spin_lock(pa->pa_node_lock.lg_lock);
list_del_rcu(&pa->pa_node.lg_list);
spin_unlock(pa->pa_node_lock.lg_lock);
ext4_mb_add_n_trim(ac);
}
}
ext4_mb_put_pa(ac, ac->ac_sb, pa);
}
if (ac->ac_bitmap_page)
put_page(ac->ac_bitmap_page);
if (ac->ac_buddy_page)
put_page(ac->ac_buddy_page);
if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
mutex_unlock(&ac->ac_lg->lg_mutex);
ext4_mb_collect_stats(ac);
return 0;
}
static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
{
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int ret;
int freed = 0, busy = 0;
int retry = 0;
trace_ext4_mb_discard_preallocations(sb, needed);
if (needed == 0)
needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
repeat:
for (i = 0; i < ngroups && needed > 0; i++) {
ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
freed += ret;
needed -= ret;
cond_resched();
}
if (needed > 0 && busy && ++retry < 3) {
busy = 0;
goto repeat;
}
return freed;
}
static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
struct ext4_allocation_context *ac, u64 *seq)
{
int freed;
u64 seq_retry = 0;
bool ret = false;
freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
if (freed) {
ret = true;
goto out_dbg;
}
seq_retry = ext4_get_discard_pa_seq_sum();
if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
ac->ac_flags |= EXT4_MB_STRICT_CHECK;
*seq = seq_retry;
ret = true;
}
out_dbg:
mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
return ret;
}
/*
* Simple allocator for Ext4 fast commit replay path. It searches for blocks
* linearly starting at the goal block and also excludes the blocks which
* are going to be in use after fast commit replay.
*/
static ext4_fsblk_t
ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
{
struct buffer_head *bitmap_bh;
struct super_block *sb = ar->inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t group, nr;
ext4_grpblk_t blkoff;
ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
ext4_grpblk_t i = 0;
ext4_fsblk_t goal, block;
struct ext4_super_block *es = sbi->s_es;
goal = ar->goal;
if (goal < le32_to_cpu(es->s_first_data_block) ||
goal >= ext4_blocks_count(es))
goal = le32_to_cpu(es->s_first_data_block);
ar->len = 0;
ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(bitmap_bh)) {
*errp = PTR_ERR(bitmap_bh);
pr_warn("Failed to read block bitmap\n");
return 0;
}
while (1) {
i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
blkoff);
if (i >= max)
break;
if (ext4_fc_replay_check_excluded(sb,
ext4_group_first_block_no(sb, group) +
EXT4_C2B(sbi, i))) {
blkoff = i + 1;
} else
break;
}
brelse(bitmap_bh);
if (i < max)
break;
if (++group >= ext4_get_groups_count(sb))
group = 0;
blkoff = 0;
}
if (i >= max) {
*errp = -ENOSPC;
return 0;
}
block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
ext4_mb_mark_bb(sb, block, 1, 1);
ar->len = 1;
return block;
}
/*
* Main entry point into mballoc to allocate blocks
* it tries to use preallocation first, then falls back
* to usual allocation
*/
ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
struct ext4_allocation_request *ar, int *errp)
{
struct ext4_allocation_context *ac = NULL;
struct ext4_sb_info *sbi;
struct super_block *sb;
ext4_fsblk_t block = 0;
unsigned int inquota = 0;
unsigned int reserv_clstrs = 0;
int retries = 0;
u64 seq;
might_sleep();
sb = ar->inode->i_sb;
sbi = EXT4_SB(sb);
trace_ext4_request_blocks(ar);
if (sbi->s_mount_state & EXT4_FC_REPLAY)
return ext4_mb_new_blocks_simple(ar, errp);
/* Allow to use superuser reservation for quota file */
if (ext4_is_quota_file(ar->inode))
ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
/* Without delayed allocation we need to verify
* there is enough free blocks to do block allocation
* and verify allocation doesn't exceed the quota limits.
*/
while (ar->len &&
ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
/* let others to free the space */
cond_resched();
ar->len = ar->len >> 1;
}
if (!ar->len) {
ext4_mb_show_pa(sb);
*errp = -ENOSPC;
return 0;
}
reserv_clstrs = ar->len;
if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
dquot_alloc_block_nofail(ar->inode,
EXT4_C2B(sbi, ar->len));
} else {
while (ar->len &&
dquot_alloc_block(ar->inode,
EXT4_C2B(sbi, ar->len))) {
ar->flags |= EXT4_MB_HINT_NOPREALLOC;
ar->len--;
}
}
inquota = ar->len;
if (ar->len == 0) {
*errp = -EDQUOT;
goto out;
}
}
ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
if (!ac) {
ar->len = 0;
*errp = -ENOMEM;
goto out;
}
ext4_mb_initialize_context(ac, ar);
ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
seq = this_cpu_read(discard_pa_seq);
if (!ext4_mb_use_preallocated(ac)) {
ac->ac_op = EXT4_MB_HISTORY_ALLOC;
ext4_mb_normalize_request(ac, ar);
*errp = ext4_mb_pa_alloc(ac);
if (*errp)
goto errout;
repeat:
/* allocate space in core */
*errp = ext4_mb_regular_allocator(ac);
/*
* pa allocated above is added to grp->bb_prealloc_list only
* when we were able to allocate some block i.e. when
* ac->ac_status == AC_STATUS_FOUND.
* And error from above mean ac->ac_status != AC_STATUS_FOUND
* So we have to free this pa here itself.
*/
if (*errp) {
ext4_mb_pa_put_free(ac);
ext4_discard_allocated_blocks(ac);
goto errout;
}
if (ac->ac_status == AC_STATUS_FOUND &&
ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
ext4_mb_pa_put_free(ac);
}
if (likely(ac->ac_status == AC_STATUS_FOUND)) {
*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
if (*errp) {
ext4_discard_allocated_blocks(ac);
goto errout;
} else {
block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
ar->len = ac->ac_b_ex.fe_len;
}
} else {
if (++retries < 3 &&
ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
goto repeat;
/*
* If block allocation fails then the pa allocated above
* needs to be freed here itself.
*/
ext4_mb_pa_put_free(ac);
*errp = -ENOSPC;
}
if (*errp) {
errout:
ac->ac_b_ex.fe_len = 0;
ar->len = 0;
ext4_mb_show_ac(ac);
}
ext4_mb_release_context(ac);
kmem_cache_free(ext4_ac_cachep, ac);
out:
if (inquota && ar->len < inquota)
dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
if (!ar->len) {
if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
/* release all the reserved blocks if non delalloc */
percpu_counter_sub(&sbi->s_dirtyclusters_counter,
reserv_clstrs);
}
trace_ext4_allocate_blocks(ar, (unsigned long long)block);
return block;
}
/*
* We can merge two free data extents only if the physical blocks
* are contiguous, AND the extents were freed by the same transaction,
* AND the blocks are associated with the same group.
*/
static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
struct ext4_free_data *entry,
struct ext4_free_data *new_entry,
struct rb_root *entry_rb_root)
{
if ((entry->efd_tid != new_entry->efd_tid) ||
(entry->efd_group != new_entry->efd_group))
return;
if (entry->efd_start_cluster + entry->efd_count ==
new_entry->efd_start_cluster) {
new_entry->efd_start_cluster = entry->efd_start_cluster;
new_entry->efd_count += entry->efd_count;
} else if (new_entry->efd_start_cluster + new_entry->efd_count ==
entry->efd_start_cluster) {
new_entry->efd_count += entry->efd_count;
} else
return;
spin_lock(&sbi->s_md_lock);
list_del(&entry->efd_list);
spin_unlock(&sbi->s_md_lock);
rb_erase(&entry->efd_node, entry_rb_root);
kmem_cache_free(ext4_free_data_cachep, entry);
}
static noinline_for_stack void
ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
struct ext4_free_data *new_entry)
{
ext4_group_t group = e4b->bd_group;
ext4_grpblk_t cluster;
ext4_grpblk_t clusters = new_entry->efd_count;
struct ext4_free_data *entry;
struct ext4_group_info *db = e4b->bd_info;
struct super_block *sb = e4b->bd_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct rb_node **n = &db->bb_free_root.rb_node, *node;
struct rb_node *parent = NULL, *new_node;
BUG_ON(!ext4_handle_valid(handle));
BUG_ON(e4b->bd_bitmap_page == NULL);
BUG_ON(e4b->bd_buddy_page == NULL);
new_node = &new_entry->efd_node;
cluster = new_entry->efd_start_cluster;
if (!*n) {
/* first free block exent. We need to
protect buddy cache from being freed,
* otherwise we'll refresh it from
* on-disk bitmap and lose not-yet-available
* blocks */
get_page(e4b->bd_buddy_page);
get_page(e4b->bd_bitmap_page);
}
while (*n) {
parent = *n;
entry = rb_entry(parent, struct ext4_free_data, efd_node);
if (cluster < entry->efd_start_cluster)
n = &(*n)->rb_left;
else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
n = &(*n)->rb_right;
else {
ext4_grp_locked_error(sb, group, 0,
ext4_group_first_block_no(sb, group) +
EXT4_C2B(sbi, cluster),
"Block already on to-be-freed list");
kmem_cache_free(ext4_free_data_cachep, new_entry);
return;
}
}
rb_link_node(new_node, parent, n);
rb_insert_color(new_node, &db->bb_free_root);
/* Now try to see the extent can be merged to left and right */
node = rb_prev(new_node);
if (node) {
entry = rb_entry(node, struct ext4_free_data, efd_node);
ext4_try_merge_freed_extent(sbi, entry, new_entry,
&(db->bb_free_root));
}
node = rb_next(new_node);
if (node) {
entry = rb_entry(node, struct ext4_free_data, efd_node);
ext4_try_merge_freed_extent(sbi, entry, new_entry,
&(db->bb_free_root));
}
spin_lock(&sbi->s_md_lock);
list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
sbi->s_mb_free_pending += clusters;
spin_unlock(&sbi->s_md_lock);
}
static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
unsigned long count)
{
struct buffer_head *bitmap_bh;
struct super_block *sb = inode->i_sb;
struct ext4_group_desc *gdp;
struct buffer_head *gdp_bh;
ext4_group_t group;
ext4_grpblk_t blkoff;
int already_freed = 0, err, i;
ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(bitmap_bh)) {
pr_warn("Failed to read block bitmap\n");
return;
}
gdp = ext4_get_group_desc(sb, group, &gdp_bh);
if (!gdp)
goto err_out;
for (i = 0; i < count; i++) {
if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
already_freed++;
}
mb_clear_bits(bitmap_bh->b_data, blkoff, count);
err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
if (err)
goto err_out;
ext4_free_group_clusters_set(
sb, gdp, ext4_free_group_clusters(sb, gdp) +
count - already_freed);
ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
ext4_group_desc_csum_set(sb, group, gdp);
ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
sync_dirty_buffer(bitmap_bh);
sync_dirty_buffer(gdp_bh);
err_out:
brelse(bitmap_bh);
}
/**
* ext4_mb_clear_bb() -- helper function for freeing blocks.
* Used by ext4_free_blocks()
* @handle: handle for this transaction
* @inode: inode
* @block: starting physical block to be freed
* @count: number of blocks to be freed
* @flags: flags used by ext4_free_blocks
*/
static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
ext4_fsblk_t block, unsigned long count,
int flags)
{
struct buffer_head *bitmap_bh = NULL;
struct super_block *sb = inode->i_sb;
struct ext4_group_desc *gdp;
struct ext4_group_info *grp;
unsigned int overflow;
ext4_grpblk_t bit;
struct buffer_head *gd_bh;
ext4_group_t block_group;
struct ext4_sb_info *sbi;
struct ext4_buddy e4b;
unsigned int count_clusters;
int err = 0;
int ret;
sbi = EXT4_SB(sb);
if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
!ext4_inode_block_valid(inode, block, count)) {
ext4_error(sb, "Freeing blocks in system zone - "
"Block = %llu, count = %lu", block, count);
/* err = 0. ext4_std_error should be a no op */
goto error_return;
}
flags |= EXT4_FREE_BLOCKS_VALIDATED;
do_more:
overflow = 0;
ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
grp = ext4_get_group_info(sb, block_group);
if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
return;
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
overflow = EXT4_C2B(sbi, bit) + count -
EXT4_BLOCKS_PER_GROUP(sb);
count -= overflow;
/* The range changed so it's no longer validated */
flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
}
count_clusters = EXT4_NUM_B2C(sbi, count);
bitmap_bh = ext4_read_block_bitmap(sb, block_group);
if (IS_ERR(bitmap_bh)) {
err = PTR_ERR(bitmap_bh);
bitmap_bh = NULL;
goto error_return;
}
gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
if (!gdp) {
err = -EIO;
goto error_return;
}
if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
!ext4_inode_block_valid(inode, block, count)) {
ext4_error(sb, "Freeing blocks in system zone - "
"Block = %llu, count = %lu", block, count);
/* err = 0. ext4_std_error should be a no op */
goto error_return;
}
BUFFER_TRACE(bitmap_bh, "getting write access");
err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
EXT4_JTR_NONE);
if (err)
goto error_return;
/*
* We are about to modify some metadata. Call the journal APIs
* to unshare ->b_data if a currently-committing transaction is
* using it
*/
BUFFER_TRACE(gd_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
if (err)
goto error_return;
#ifdef AGGRESSIVE_CHECK
{
int i;
for (i = 0; i < count_clusters; i++)
BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
}
#endif
trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
/* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
GFP_NOFS|__GFP_NOFAIL);
if (err)
goto error_return;
/*
* We need to make sure we don't reuse the freed block until after the
* transaction is committed. We make an exception if the inode is to be
* written in writeback mode since writeback mode has weak data
* consistency guarantees.
*/
if (ext4_handle_valid(handle) &&
((flags & EXT4_FREE_BLOCKS_METADATA) ||
!ext4_should_writeback_data(inode))) {
struct ext4_free_data *new_entry;
/*
* We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
* to fail.
*/
new_entry = kmem_cache_alloc(ext4_free_data_cachep,
GFP_NOFS|__GFP_NOFAIL);
new_entry->efd_start_cluster = bit;
new_entry->efd_group = block_group;
new_entry->efd_count = count_clusters;
new_entry->efd_tid = handle->h_transaction->t_tid;
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
ext4_mb_free_metadata(handle, &e4b, new_entry);
} else {
/* need to update group_info->bb_free and bitmap
* with group lock held. generate_buddy look at
* them with group lock_held
*/
if (test_opt(sb, DISCARD)) {
err = ext4_issue_discard(sb, block_group, bit,
count_clusters, NULL);
if (err && err != -EOPNOTSUPP)
ext4_msg(sb, KERN_WARNING, "discard request in"
" group:%u block:%d count:%lu failed"
" with %d", block_group, bit, count,
err);
} else
EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
mb_free_blocks(inode, &e4b, bit, count_clusters);
}
ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
ext4_free_group_clusters_set(sb, gdp, ret);
ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
ext4_group_desc_csum_set(sb, block_group, gdp);
ext4_unlock_group(sb, block_group);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
atomic64_add(count_clusters,
&sbi_array_rcu_deref(sbi, s_flex_groups,
flex_group)->free_clusters);
}
/*
* on a bigalloc file system, defer the s_freeclusters_counter
* update to the caller (ext4_remove_space and friends) so they
* can determine if a cluster freed here should be rereserved
*/
if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
percpu_counter_add(&sbi->s_freeclusters_counter,
count_clusters);
}
ext4_mb_unload_buddy(&e4b);
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
/* And the group descriptor block */
BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
if (!err)
err = ret;
if (overflow && !err) {
block += count;
count = overflow;
put_bh(bitmap_bh);
/* The range changed so it's no longer validated */
flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
goto do_more;
}
error_return:
brelse(bitmap_bh);
ext4_std_error(sb, err);
}
/**
* ext4_free_blocks() -- Free given blocks and update quota
* @handle: handle for this transaction
* @inode: inode
* @bh: optional buffer of the block to be freed
* @block: starting physical block to be freed
* @count: number of blocks to be freed
* @flags: flags used by ext4_free_blocks
*/
void ext4_free_blocks(handle_t *handle, struct inode *inode,
struct buffer_head *bh, ext4_fsblk_t block,
unsigned long count, int flags)
{
struct super_block *sb = inode->i_sb;
unsigned int overflow;
struct ext4_sb_info *sbi;
sbi = EXT4_SB(sb);
if (bh) {
if (block)
BUG_ON(block != bh->b_blocknr);
else
block = bh->b_blocknr;
}
if (sbi->s_mount_state & EXT4_FC_REPLAY) {
ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
return;
}
might_sleep();
if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
!ext4_inode_block_valid(inode, block, count)) {
ext4_error(sb, "Freeing blocks not in datazone - "
"block = %llu, count = %lu", block, count);
return;
}
flags |= EXT4_FREE_BLOCKS_VALIDATED;
ext4_debug("freeing block %llu\n", block);
trace_ext4_free_blocks(inode, block, count, flags);
if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
BUG_ON(count > 1);
ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
inode, bh, block);
}
/*
* If the extent to be freed does not begin on a cluster
* boundary, we need to deal with partial clusters at the
* beginning and end of the extent. Normally we will free
* blocks at the beginning or the end unless we are explicitly
* requested to avoid doing so.
*/
overflow = EXT4_PBLK_COFF(sbi, block);
if (overflow) {
if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
overflow = sbi->s_cluster_ratio - overflow;
block += overflow;
if (count > overflow)
count -= overflow;
else
return;
} else {
block -= overflow;
count += overflow;
}
/* The range changed so it's no longer validated */
flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
}
overflow = EXT4_LBLK_COFF(sbi, count);
if (overflow) {
if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
if (count > overflow)
count -= overflow;
else
return;
} else
count += sbi->s_cluster_ratio - overflow;
/* The range changed so it's no longer validated */
flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
}
if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
int i;
int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
for (i = 0; i < count; i++) {
cond_resched();
if (is_metadata)
bh = sb_find_get_block(inode->i_sb, block + i);
ext4_forget(handle, is_metadata, inode, bh, block + i);
}
}
ext4_mb_clear_bb(handle, inode, block, count, flags);
}
/**
* ext4_group_add_blocks() -- Add given blocks to an existing group
* @handle: handle to this transaction
* @sb: super block
* @block: start physical block to add to the block group
* @count: number of blocks to free
*
* This marks the blocks as free in the bitmap and buddy.
*/
int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
ext4_fsblk_t block, unsigned long count)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *gd_bh;
ext4_group_t block_group;
ext4_grpblk_t bit;
unsigned int i;
struct ext4_group_desc *desc;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_buddy e4b;
int err = 0, ret, free_clusters_count;
ext4_grpblk_t clusters_freed;
ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
unsigned long cluster_count = last_cluster - first_cluster + 1;
ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
if (count == 0)
return 0;
ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
ext4_warning(sb, "too many blocks added to group %u",
block_group);
err = -EINVAL;
goto error_return;
}
bitmap_bh = ext4_read_block_bitmap(sb, block_group);
if (IS_ERR(bitmap_bh)) {
err = PTR_ERR(bitmap_bh);
bitmap_bh = NULL;
goto error_return;
}
desc = ext4_get_group_desc(sb, block_group, &gd_bh);
if (!desc) {
err = -EIO;
goto error_return;
}
if (!ext4_sb_block_valid(sb, NULL, block, count)) {
ext4_error(sb, "Adding blocks in system zones - "
"Block = %llu, count = %lu",
block, count);
err = -EINVAL;
goto error_return;
}
BUFFER_TRACE(bitmap_bh, "getting write access");
err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
EXT4_JTR_NONE);
if (err)
goto error_return;
/*
* We are about to modify some metadata. Call the journal APIs
* to unshare ->b_data if a currently-committing transaction is
* using it
*/
BUFFER_TRACE(gd_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
if (err)
goto error_return;
for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
BUFFER_TRACE(bitmap_bh, "clear bit");
if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
ext4_error(sb, "bit already cleared for block %llu",
(ext4_fsblk_t)(block + i));
BUFFER_TRACE(bitmap_bh, "bit already cleared");
} else {
clusters_freed++;
}
}
err = ext4_mb_load_buddy(sb, block_group, &e4b);
if (err)
goto error_return;
/*
* need to update group_info->bb_free and bitmap
* with group lock held. generate_buddy look at
* them with group lock_held
*/
ext4_lock_group(sb, block_group);
mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
mb_free_blocks(NULL, &e4b, bit, cluster_count);
free_clusters_count = clusters_freed +
ext4_free_group_clusters(sb, desc);
ext4_free_group_clusters_set(sb, desc, free_clusters_count);
ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
ext4_group_desc_csum_set(sb, block_group, desc);
ext4_unlock_group(sb, block_group);
percpu_counter_add(&sbi->s_freeclusters_counter,
clusters_freed);
if (sbi->s_log_groups_per_flex) {
ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
atomic64_add(clusters_freed,
&sbi_array_rcu_deref(sbi, s_flex_groups,
flex_group)->free_clusters);
}
ext4_mb_unload_buddy(&e4b);
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
/* And the group descriptor block */
BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
if (!err)
err = ret;
error_return:
brelse(bitmap_bh);
ext4_std_error(sb, err);
return err;
}
/**
* ext4_trim_extent -- function to TRIM one single free extent in the group
* @sb: super block for the file system
* @start: starting block of the free extent in the alloc. group
* @count: number of blocks to TRIM
* @e4b: ext4 buddy for the group
*
* Trim "count" blocks starting at "start" in the "group". To assure that no
* one will allocate those blocks, mark it as used in buddy bitmap. This must
* be called with under the group lock.
*/
static int ext4_trim_extent(struct super_block *sb,
int start, int count, struct ext4_buddy *e4b)
__releases(bitlock)
__acquires(bitlock)
{
struct ext4_free_extent ex;
ext4_group_t group = e4b->bd_group;
int ret = 0;
trace_ext4_trim_extent(sb, group, start, count);
assert_spin_locked(ext4_group_lock_ptr(sb, group));
ex.fe_start = start;
ex.fe_group = group;
ex.fe_len = count;
/*
* Mark blocks used, so no one can reuse them while
* being trimmed.
*/
mb_mark_used(e4b, &ex);
ext4_unlock_group(sb, group);
ret = ext4_issue_discard(sb, group, start, count, NULL);
ext4_lock_group(sb, group);
mb_free_blocks(NULL, e4b, start, ex.fe_len);
return ret;
}
static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
ext4_group_t grp)
{
if (grp < ext4_get_groups_count(sb))
return EXT4_CLUSTERS_PER_GROUP(sb) - 1;
return (ext4_blocks_count(EXT4_SB(sb)->s_es) -
ext4_group_first_block_no(sb, grp) - 1) >>
EXT4_CLUSTER_BITS(sb);
}
static bool ext4_trim_interrupted(void)
{
return fatal_signal_pending(current) || freezing(current);
}
static int ext4_try_to_trim_range(struct super_block *sb,
struct ext4_buddy *e4b, ext4_grpblk_t start,
ext4_grpblk_t max, ext4_grpblk_t minblocks)
__acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
__releases(ext4_group_lock_ptr(sb, e4b->bd_group))
{
ext4_grpblk_t next, count, free_count;
bool set_trimmed = false;
void *bitmap;
bitmap = e4b->bd_bitmap;
if (start == 0 && max >= ext4_last_grp_cluster(sb, e4b->bd_group))
set_trimmed = true;
start = max(e4b->bd_info->bb_first_free, start);
count = 0;
free_count = 0;
while (start <= max) {
start = mb_find_next_zero_bit(bitmap, max + 1, start);
if (start > max)
break;
next = mb_find_next_bit(bitmap, max + 1, start);
if ((next - start) >= minblocks) {
int ret = ext4_trim_extent(sb, start, next - start, e4b);
if (ret && ret != -EOPNOTSUPP)
return count;
count += next - start;
}
free_count += next - start;
start = next + 1;
if (ext4_trim_interrupted())
return count;
if (need_resched()) {
ext4_unlock_group(sb, e4b->bd_group);
cond_resched();
ext4_lock_group(sb, e4b->bd_group);
}
if ((e4b->bd_info->bb_free - free_count) < minblocks)
break;
}
if (set_trimmed)
EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
return count;
}
/**
* ext4_trim_all_free -- function to trim all free space in alloc. group
* @sb: super block for file system
* @group: group to be trimmed
* @start: first group block to examine
* @max: last group block to examine
* @minblocks: minimum extent block count
*
* ext4_trim_all_free walks through group's block bitmap searching for free
* extents. When the free extent is found, mark it as used in group buddy
* bitmap. Then issue a TRIM command on this extent and free the extent in
* the group buddy bitmap.
*/
static ext4_grpblk_t
ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
ext4_grpblk_t start, ext4_grpblk_t max,
ext4_grpblk_t minblocks)
{
struct ext4_buddy e4b;
int ret;
trace_ext4_trim_all_free(sb, group, start, max);
ret = ext4_mb_load_buddy(sb, group, &e4b);
if (ret) {
ext4_warning(sb, "Error %d loading buddy information for %u",
ret, group);
return ret;
}
ext4_lock_group(sb, group);
if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
minblocks < EXT4_SB(sb)->s_last_trim_minblks)
ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
else
ret = 0;
ext4_unlock_group(sb, group);
ext4_mb_unload_buddy(&e4b);
ext4_debug("trimmed %d blocks in the group %d\n",
ret, group);
return ret;
}
/**
* ext4_trim_fs() -- trim ioctl handle function
* @sb: superblock for filesystem
* @range: fstrim_range structure
*
* start: First Byte to trim
* len: number of Bytes to trim from start
* minlen: minimum extent length in Bytes
* ext4_trim_fs goes through all allocation groups containing Bytes from
* start to start+len. For each such a group ext4_trim_all_free function
* is invoked to trim all free space.
*/
int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
{
unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
struct ext4_group_info *grp;
ext4_group_t group, first_group, last_group;
ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
uint64_t start, end, minlen, trimmed = 0;
ext4_fsblk_t first_data_blk =
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
int ret = 0;
start = range->start >> sb->s_blocksize_bits;
end = start + (range->len >> sb->s_blocksize_bits) - 1;
minlen = EXT4_NUM_B2C(EXT4_SB(sb),
range->minlen >> sb->s_blocksize_bits);
if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
start >= max_blks ||
range->len < sb->s_blocksize)
return -EINVAL;
/* No point to try to trim less than discard granularity */
if (range->minlen < discard_granularity) {
minlen = EXT4_NUM_B2C(EXT4_SB(sb),
discard_granularity >> sb->s_blocksize_bits);
if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
goto out;
}
if (end >= max_blks - 1)
end = max_blks - 1;
if (end <= first_data_blk)
goto out;
if (start < first_data_blk)
start = first_data_blk;
/* Determine first and last group to examine based on start and end */
ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
&first_group, &first_cluster);
ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
&last_group, &last_cluster);
/* end now represents the last cluster to discard in this group */
end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
for (group = first_group; group <= last_group; group++) {
if (ext4_trim_interrupted())
break;
grp = ext4_get_group_info(sb, group);
if (!grp)
continue;
/* We only do this if the grp has never been initialized */
if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
ret = ext4_mb_init_group(sb, group, GFP_NOFS);
if (ret)
break;
}
/*
* For all the groups except the last one, last cluster will
* always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
* change it for the last group, note that last_cluster is
* already computed earlier by ext4_get_group_no_and_offset()
*/
if (group == last_group)
end = last_cluster;
if (grp->bb_free >= minlen) {
cnt = ext4_trim_all_free(sb, group, first_cluster,
end, minlen);
if (cnt < 0) {
ret = cnt;
break;
}
trimmed += cnt;
}
/*
* For every group except the first one, we are sure
* that the first cluster to discard will be cluster #0.
*/
first_cluster = 0;
}
if (!ret)
EXT4_SB(sb)->s_last_trim_minblks = minlen;
out:
range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
return ret;
}
/* Iterate all the free extents in the group. */
int
ext4_mballoc_query_range(
struct super_block *sb,
ext4_group_t group,
ext4_grpblk_t start,
ext4_grpblk_t end,
ext4_mballoc_query_range_fn formatter,
void *priv)
{
void *bitmap;
ext4_grpblk_t next;
struct ext4_buddy e4b;
int error;
error = ext4_mb_load_buddy(sb, group, &e4b);
if (error)
return error;
bitmap = e4b.bd_bitmap;
ext4_lock_group(sb, group);
start = max(e4b.bd_info->bb_first_free, start);
if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
while (start <= end) {
start = mb_find_next_zero_bit(bitmap, end + 1, start);
if (start > end)
break;
next = mb_find_next_bit(bitmap, end + 1, start);
ext4_unlock_group(sb, group);
error = formatter(sb, group, start, next - start, priv);
if (error)
goto out_unload;
ext4_lock_group(sb, group);
start = next + 1;
}
ext4_unlock_group(sb, group);
out_unload:
ext4_mb_unload_buddy(&e4b);
return error;
}
| linux-master | fs/ext4/mballoc.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/resize.c
*
* Support for resizing an ext4 filesystem while it is mounted.
*
* Copyright (C) 2001, 2002 Andreas Dilger <[email protected]>
*
* This could probably be made into a module, because it is not often in use.
*/
#define EXT4FS_DEBUG
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include "ext4_jbd2.h"
struct ext4_rcu_ptr {
struct rcu_head rcu;
void *ptr;
};
static void ext4_rcu_ptr_callback(struct rcu_head *head)
{
struct ext4_rcu_ptr *ptr;
ptr = container_of(head, struct ext4_rcu_ptr, rcu);
kvfree(ptr->ptr);
kfree(ptr);
}
void ext4_kvfree_array_rcu(void *to_free)
{
struct ext4_rcu_ptr *ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
if (ptr) {
ptr->ptr = to_free;
call_rcu(&ptr->rcu, ext4_rcu_ptr_callback);
return;
}
synchronize_rcu();
kvfree(to_free);
}
int ext4_resize_begin(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int ret = 0;
if (!capable(CAP_SYS_RESOURCE))
return -EPERM;
/*
* If the reserved GDT blocks is non-zero, the resize_inode feature
* should always be set.
*/
if (EXT4_SB(sb)->s_es->s_reserved_gdt_blocks &&
!ext4_has_feature_resize_inode(sb)) {
ext4_error(sb, "resize_inode disabled but reserved GDT blocks non-zero");
return -EFSCORRUPTED;
}
/*
* If we are not using the primary superblock/GDT copy don't resize,
* because the user tools have no way of handling this. Probably a
* bad time to do it anyways.
*/
if (EXT4_B2C(sbi, sbi->s_sbh->b_blocknr) !=
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) {
ext4_warning(sb, "won't resize using backup superblock at %llu",
(unsigned long long)EXT4_SB(sb)->s_sbh->b_blocknr);
return -EPERM;
}
/*
* We are not allowed to do online-resizing on a filesystem mounted
* with error, because it can destroy the filesystem easily.
*/
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
ext4_warning(sb, "There are errors in the filesystem, "
"so online resizing is not allowed");
return -EPERM;
}
if (ext4_has_feature_sparse_super2(sb)) {
ext4_msg(sb, KERN_ERR, "Online resizing not supported with sparse_super2");
return -EOPNOTSUPP;
}
if (test_and_set_bit_lock(EXT4_FLAGS_RESIZING,
&EXT4_SB(sb)->s_ext4_flags))
ret = -EBUSY;
return ret;
}
int ext4_resize_end(struct super_block *sb, bool update_backups)
{
clear_bit_unlock(EXT4_FLAGS_RESIZING, &EXT4_SB(sb)->s_ext4_flags);
smp_mb__after_atomic();
if (update_backups)
return ext4_update_overhead(sb, true);
return 0;
}
static ext4_group_t ext4_meta_bg_first_group(struct super_block *sb,
ext4_group_t group) {
return (group >> EXT4_DESC_PER_BLOCK_BITS(sb)) <<
EXT4_DESC_PER_BLOCK_BITS(sb);
}
static ext4_fsblk_t ext4_meta_bg_first_block_no(struct super_block *sb,
ext4_group_t group) {
group = ext4_meta_bg_first_group(sb, group);
return ext4_group_first_block_no(sb, group);
}
static ext4_grpblk_t ext4_group_overhead_blocks(struct super_block *sb,
ext4_group_t group) {
ext4_grpblk_t overhead;
overhead = ext4_bg_num_gdb(sb, group);
if (ext4_bg_has_super(sb, group))
overhead += 1 +
le16_to_cpu(EXT4_SB(sb)->s_es->s_reserved_gdt_blocks);
return overhead;
}
#define outside(b, first, last) ((b) < (first) || (b) >= (last))
#define inside(b, first, last) ((b) >= (first) && (b) < (last))
static int verify_group_input(struct super_block *sb,
struct ext4_new_group_data *input)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t start = ext4_blocks_count(es);
ext4_fsblk_t end = start + input->blocks_count;
ext4_group_t group = input->group;
ext4_fsblk_t itend = input->inode_table + sbi->s_itb_per_group;
unsigned overhead;
ext4_fsblk_t metaend;
struct buffer_head *bh = NULL;
ext4_grpblk_t free_blocks_count, offset;
int err = -EINVAL;
if (group != sbi->s_groups_count) {
ext4_warning(sb, "Cannot add at group %u (only %u groups)",
input->group, sbi->s_groups_count);
return -EINVAL;
}
overhead = ext4_group_overhead_blocks(sb, group);
metaend = start + overhead;
input->free_clusters_count = free_blocks_count =
input->blocks_count - 2 - overhead - sbi->s_itb_per_group;
if (test_opt(sb, DEBUG))
printk(KERN_DEBUG "EXT4-fs: adding %s group %u: %u blocks "
"(%d free, %u reserved)\n",
ext4_bg_has_super(sb, input->group) ? "normal" :
"no-super", input->group, input->blocks_count,
free_blocks_count, input->reserved_blocks);
ext4_get_group_no_and_offset(sb, start, NULL, &offset);
if (offset != 0)
ext4_warning(sb, "Last group not full");
else if (input->reserved_blocks > input->blocks_count / 5)
ext4_warning(sb, "Reserved blocks too high (%u)",
input->reserved_blocks);
else if (free_blocks_count < 0)
ext4_warning(sb, "Bad blocks count %u",
input->blocks_count);
else if (IS_ERR(bh = ext4_sb_bread(sb, end - 1, 0))) {
err = PTR_ERR(bh);
bh = NULL;
ext4_warning(sb, "Cannot read last block (%llu)",
end - 1);
} else if (outside(input->block_bitmap, start, end))
ext4_warning(sb, "Block bitmap not in group (block %llu)",
(unsigned long long)input->block_bitmap);
else if (outside(input->inode_bitmap, start, end))
ext4_warning(sb, "Inode bitmap not in group (block %llu)",
(unsigned long long)input->inode_bitmap);
else if (outside(input->inode_table, start, end) ||
outside(itend - 1, start, end))
ext4_warning(sb, "Inode table not in group (blocks %llu-%llu)",
(unsigned long long)input->inode_table, itend - 1);
else if (input->inode_bitmap == input->block_bitmap)
ext4_warning(sb, "Block bitmap same as inode bitmap (%llu)",
(unsigned long long)input->block_bitmap);
else if (inside(input->block_bitmap, input->inode_table, itend))
ext4_warning(sb, "Block bitmap (%llu) in inode table "
"(%llu-%llu)",
(unsigned long long)input->block_bitmap,
(unsigned long long)input->inode_table, itend - 1);
else if (inside(input->inode_bitmap, input->inode_table, itend))
ext4_warning(sb, "Inode bitmap (%llu) in inode table "
"(%llu-%llu)",
(unsigned long long)input->inode_bitmap,
(unsigned long long)input->inode_table, itend - 1);
else if (inside(input->block_bitmap, start, metaend))
ext4_warning(sb, "Block bitmap (%llu) in GDT table (%llu-%llu)",
(unsigned long long)input->block_bitmap,
start, metaend - 1);
else if (inside(input->inode_bitmap, start, metaend))
ext4_warning(sb, "Inode bitmap (%llu) in GDT table (%llu-%llu)",
(unsigned long long)input->inode_bitmap,
start, metaend - 1);
else if (inside(input->inode_table, start, metaend) ||
inside(itend - 1, start, metaend))
ext4_warning(sb, "Inode table (%llu-%llu) overlaps GDT table "
"(%llu-%llu)",
(unsigned long long)input->inode_table,
itend - 1, start, metaend - 1);
else
err = 0;
brelse(bh);
return err;
}
/*
* ext4_new_flex_group_data is used by 64bit-resize interface to add a flex
* group each time.
*/
struct ext4_new_flex_group_data {
struct ext4_new_group_data *groups; /* new_group_data for groups
in the flex group */
__u16 *bg_flags; /* block group flags of groups
in @groups */
ext4_group_t count; /* number of groups in @groups
*/
};
/*
* alloc_flex_gd() allocates a ext4_new_flex_group_data with size of
* @flexbg_size.
*
* Returns NULL on failure otherwise address of the allocated structure.
*/
static struct ext4_new_flex_group_data *alloc_flex_gd(unsigned long flexbg_size)
{
struct ext4_new_flex_group_data *flex_gd;
flex_gd = kmalloc(sizeof(*flex_gd), GFP_NOFS);
if (flex_gd == NULL)
goto out3;
if (flexbg_size >= UINT_MAX / sizeof(struct ext4_new_group_data))
goto out2;
flex_gd->count = flexbg_size;
flex_gd->groups = kmalloc_array(flexbg_size,
sizeof(struct ext4_new_group_data),
GFP_NOFS);
if (flex_gd->groups == NULL)
goto out2;
flex_gd->bg_flags = kmalloc_array(flexbg_size, sizeof(__u16),
GFP_NOFS);
if (flex_gd->bg_flags == NULL)
goto out1;
return flex_gd;
out1:
kfree(flex_gd->groups);
out2:
kfree(flex_gd);
out3:
return NULL;
}
static void free_flex_gd(struct ext4_new_flex_group_data *flex_gd)
{
kfree(flex_gd->bg_flags);
kfree(flex_gd->groups);
kfree(flex_gd);
}
/*
* ext4_alloc_group_tables() allocates block bitmaps, inode bitmaps
* and inode tables for a flex group.
*
* This function is used by 64bit-resize. Note that this function allocates
* group tables from the 1st group of groups contained by @flexgd, which may
* be a partial of a flex group.
*
* @sb: super block of fs to which the groups belongs
*
* Returns 0 on a successful allocation of the metadata blocks in the
* block group.
*/
static int ext4_alloc_group_tables(struct super_block *sb,
struct ext4_new_flex_group_data *flex_gd,
int flexbg_size)
{
struct ext4_new_group_data *group_data = flex_gd->groups;
ext4_fsblk_t start_blk;
ext4_fsblk_t last_blk;
ext4_group_t src_group;
ext4_group_t bb_index = 0;
ext4_group_t ib_index = 0;
ext4_group_t it_index = 0;
ext4_group_t group;
ext4_group_t last_group;
unsigned overhead;
__u16 uninit_mask = (flexbg_size > 1) ? ~EXT4_BG_BLOCK_UNINIT : ~0;
int i;
BUG_ON(flex_gd->count == 0 || group_data == NULL);
src_group = group_data[0].group;
last_group = src_group + flex_gd->count - 1;
BUG_ON((flexbg_size > 1) && ((src_group & ~(flexbg_size - 1)) !=
(last_group & ~(flexbg_size - 1))));
next_group:
group = group_data[0].group;
if (src_group >= group_data[0].group + flex_gd->count)
return -ENOSPC;
start_blk = ext4_group_first_block_no(sb, src_group);
last_blk = start_blk + group_data[src_group - group].blocks_count;
overhead = ext4_group_overhead_blocks(sb, src_group);
start_blk += overhead;
/* We collect contiguous blocks as much as possible. */
src_group++;
for (; src_group <= last_group; src_group++) {
overhead = ext4_group_overhead_blocks(sb, src_group);
if (overhead == 0)
last_blk += group_data[src_group - group].blocks_count;
else
break;
}
/* Allocate block bitmaps */
for (; bb_index < flex_gd->count; bb_index++) {
if (start_blk >= last_blk)
goto next_group;
group_data[bb_index].block_bitmap = start_blk++;
group = ext4_get_group_number(sb, start_blk - 1);
group -= group_data[0].group;
group_data[group].mdata_blocks++;
flex_gd->bg_flags[group] &= uninit_mask;
}
/* Allocate inode bitmaps */
for (; ib_index < flex_gd->count; ib_index++) {
if (start_blk >= last_blk)
goto next_group;
group_data[ib_index].inode_bitmap = start_blk++;
group = ext4_get_group_number(sb, start_blk - 1);
group -= group_data[0].group;
group_data[group].mdata_blocks++;
flex_gd->bg_flags[group] &= uninit_mask;
}
/* Allocate inode tables */
for (; it_index < flex_gd->count; it_index++) {
unsigned int itb = EXT4_SB(sb)->s_itb_per_group;
ext4_fsblk_t next_group_start;
if (start_blk + itb > last_blk)
goto next_group;
group_data[it_index].inode_table = start_blk;
group = ext4_get_group_number(sb, start_blk);
next_group_start = ext4_group_first_block_no(sb, group + 1);
group -= group_data[0].group;
if (start_blk + itb > next_group_start) {
flex_gd->bg_flags[group + 1] &= uninit_mask;
overhead = start_blk + itb - next_group_start;
group_data[group + 1].mdata_blocks += overhead;
itb -= overhead;
}
group_data[group].mdata_blocks += itb;
flex_gd->bg_flags[group] &= uninit_mask;
start_blk += EXT4_SB(sb)->s_itb_per_group;
}
/* Update free clusters count to exclude metadata blocks */
for (i = 0; i < flex_gd->count; i++) {
group_data[i].free_clusters_count -=
EXT4_NUM_B2C(EXT4_SB(sb),
group_data[i].mdata_blocks);
}
if (test_opt(sb, DEBUG)) {
int i;
group = group_data[0].group;
printk(KERN_DEBUG "EXT4-fs: adding a flex group with "
"%d groups, flexbg size is %d:\n", flex_gd->count,
flexbg_size);
for (i = 0; i < flex_gd->count; i++) {
ext4_debug(
"adding %s group %u: %u blocks (%d free, %d mdata blocks)\n",
ext4_bg_has_super(sb, group + i) ? "normal" :
"no-super", group + i,
group_data[i].blocks_count,
group_data[i].free_clusters_count,
group_data[i].mdata_blocks);
}
}
return 0;
}
static struct buffer_head *bclean(handle_t *handle, struct super_block *sb,
ext4_fsblk_t blk)
{
struct buffer_head *bh;
int err;
bh = sb_getblk(sb, blk);
if (unlikely(!bh))
return ERR_PTR(-ENOMEM);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, bh, EXT4_JTR_NONE);
if (err) {
brelse(bh);
bh = ERR_PTR(err);
} else {
memset(bh->b_data, 0, sb->s_blocksize);
set_buffer_uptodate(bh);
}
return bh;
}
static int ext4_resize_ensure_credits_batch(handle_t *handle, int credits)
{
return ext4_journal_ensure_credits_fn(handle, credits,
EXT4_MAX_TRANS_DATA, 0, 0);
}
/*
* set_flexbg_block_bitmap() mark clusters [@first_cluster, @last_cluster] used.
*
* Helper function for ext4_setup_new_group_blocks() which set .
*
* @sb: super block
* @handle: journal handle
* @flex_gd: flex group data
*/
static int set_flexbg_block_bitmap(struct super_block *sb, handle_t *handle,
struct ext4_new_flex_group_data *flex_gd,
ext4_fsblk_t first_cluster, ext4_fsblk_t last_cluster)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t count = last_cluster - first_cluster + 1;
ext4_group_t count2;
ext4_debug("mark clusters [%llu-%llu] used\n", first_cluster,
last_cluster);
for (count2 = count; count > 0;
count -= count2, first_cluster += count2) {
ext4_fsblk_t start;
struct buffer_head *bh;
ext4_group_t group;
int err;
group = ext4_get_group_number(sb, EXT4_C2B(sbi, first_cluster));
start = EXT4_B2C(sbi, ext4_group_first_block_no(sb, group));
group -= flex_gd->groups[0].group;
count2 = EXT4_CLUSTERS_PER_GROUP(sb) - (first_cluster - start);
if (count2 > count)
count2 = count;
if (flex_gd->bg_flags[group] & EXT4_BG_BLOCK_UNINIT) {
BUG_ON(flex_gd->count > 1);
continue;
}
err = ext4_resize_ensure_credits_batch(handle, 1);
if (err < 0)
return err;
bh = sb_getblk(sb, flex_gd->groups[group].block_bitmap);
if (unlikely(!bh))
return -ENOMEM;
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, bh,
EXT4_JTR_NONE);
if (err) {
brelse(bh);
return err;
}
ext4_debug("mark block bitmap %#04llx (+%llu/%u)\n",
first_cluster, first_cluster - start, count2);
mb_set_bits(bh->b_data, first_cluster - start, count2);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
if (unlikely(err))
return err;
}
return 0;
}
/*
* Set up the block and inode bitmaps, and the inode table for the new groups.
* This doesn't need to be part of the main transaction, since we are only
* changing blocks outside the actual filesystem. We still do journaling to
* ensure the recovery is correct in case of a failure just after resize.
* If any part of this fails, we simply abort the resize.
*
* setup_new_flex_group_blocks handles a flex group as follow:
* 1. copy super block and GDT, and initialize group tables if necessary.
* In this step, we only set bits in blocks bitmaps for blocks taken by
* super block and GDT.
* 2. allocate group tables in block bitmaps, that is, set bits in block
* bitmap for blocks taken by group tables.
*/
static int setup_new_flex_group_blocks(struct super_block *sb,
struct ext4_new_flex_group_data *flex_gd)
{
int group_table_count[] = {1, 1, EXT4_SB(sb)->s_itb_per_group};
ext4_fsblk_t start;
ext4_fsblk_t block;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct ext4_new_group_data *group_data = flex_gd->groups;
__u16 *bg_flags = flex_gd->bg_flags;
handle_t *handle;
ext4_group_t group, count;
struct buffer_head *bh = NULL;
int reserved_gdb, i, j, err = 0, err2;
int meta_bg;
BUG_ON(!flex_gd->count || !group_data ||
group_data[0].group != sbi->s_groups_count);
reserved_gdb = le16_to_cpu(es->s_reserved_gdt_blocks);
meta_bg = ext4_has_feature_meta_bg(sb);
/* This transaction may be extended/restarted along the way */
handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, EXT4_MAX_TRANS_DATA);
if (IS_ERR(handle))
return PTR_ERR(handle);
group = group_data[0].group;
for (i = 0; i < flex_gd->count; i++, group++) {
unsigned long gdblocks;
ext4_grpblk_t overhead;
gdblocks = ext4_bg_num_gdb(sb, group);
start = ext4_group_first_block_no(sb, group);
if (meta_bg == 0 && !ext4_bg_has_super(sb, group))
goto handle_itb;
if (meta_bg == 1) {
ext4_group_t first_group;
first_group = ext4_meta_bg_first_group(sb, group);
if (first_group != group + 1 &&
first_group != group + EXT4_DESC_PER_BLOCK(sb) - 1)
goto handle_itb;
}
block = start + ext4_bg_has_super(sb, group);
/* Copy all of the GDT blocks into the backup in this group */
for (j = 0; j < gdblocks; j++, block++) {
struct buffer_head *gdb;
ext4_debug("update backup group %#04llx\n", block);
err = ext4_resize_ensure_credits_batch(handle, 1);
if (err < 0)
goto out;
gdb = sb_getblk(sb, block);
if (unlikely(!gdb)) {
err = -ENOMEM;
goto out;
}
BUFFER_TRACE(gdb, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gdb,
EXT4_JTR_NONE);
if (err) {
brelse(gdb);
goto out;
}
memcpy(gdb->b_data, sbi_array_rcu_deref(sbi,
s_group_desc, j)->b_data, gdb->b_size);
set_buffer_uptodate(gdb);
err = ext4_handle_dirty_metadata(handle, NULL, gdb);
if (unlikely(err)) {
brelse(gdb);
goto out;
}
brelse(gdb);
}
/* Zero out all of the reserved backup group descriptor
* table blocks
*/
if (ext4_bg_has_super(sb, group)) {
err = sb_issue_zeroout(sb, gdblocks + start + 1,
reserved_gdb, GFP_NOFS);
if (err)
goto out;
}
handle_itb:
/* Initialize group tables of the grop @group */
if (!(bg_flags[i] & EXT4_BG_INODE_ZEROED))
goto handle_bb;
/* Zero out all of the inode table blocks */
block = group_data[i].inode_table;
ext4_debug("clear inode table blocks %#04llx -> %#04lx\n",
block, sbi->s_itb_per_group);
err = sb_issue_zeroout(sb, block, sbi->s_itb_per_group,
GFP_NOFS);
if (err)
goto out;
handle_bb:
if (bg_flags[i] & EXT4_BG_BLOCK_UNINIT)
goto handle_ib;
/* Initialize block bitmap of the @group */
block = group_data[i].block_bitmap;
err = ext4_resize_ensure_credits_batch(handle, 1);
if (err < 0)
goto out;
bh = bclean(handle, sb, block);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
goto out;
}
overhead = ext4_group_overhead_blocks(sb, group);
if (overhead != 0) {
ext4_debug("mark backup superblock %#04llx (+0)\n",
start);
mb_set_bits(bh->b_data, 0,
EXT4_NUM_B2C(sbi, overhead));
}
ext4_mark_bitmap_end(EXT4_B2C(sbi, group_data[i].blocks_count),
sb->s_blocksize * 8, bh->b_data);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
if (err)
goto out;
handle_ib:
if (bg_flags[i] & EXT4_BG_INODE_UNINIT)
continue;
/* Initialize inode bitmap of the @group */
block = group_data[i].inode_bitmap;
err = ext4_resize_ensure_credits_batch(handle, 1);
if (err < 0)
goto out;
/* Mark unused entries in inode bitmap used */
bh = bclean(handle, sb, block);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
goto out;
}
ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
sb->s_blocksize * 8, bh->b_data);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
if (err)
goto out;
}
/* Mark group tables in block bitmap */
for (j = 0; j < GROUP_TABLE_COUNT; j++) {
count = group_table_count[j];
start = (&group_data[0].block_bitmap)[j];
block = start;
for (i = 1; i < flex_gd->count; i++) {
block += group_table_count[j];
if (block == (&group_data[i].block_bitmap)[j]) {
count += group_table_count[j];
continue;
}
err = set_flexbg_block_bitmap(sb, handle,
flex_gd,
EXT4_B2C(sbi, start),
EXT4_B2C(sbi,
start + count
- 1));
if (err)
goto out;
count = group_table_count[j];
start = (&group_data[i].block_bitmap)[j];
block = start;
}
if (count) {
err = set_flexbg_block_bitmap(sb, handle,
flex_gd,
EXT4_B2C(sbi, start),
EXT4_B2C(sbi,
start + count
- 1));
if (err)
goto out;
}
}
out:
err2 = ext4_journal_stop(handle);
if (err2 && !err)
err = err2;
return err;
}
/*
* Iterate through the groups which hold BACKUP superblock/GDT copies in an
* ext4 filesystem. The counters should be initialized to 1, 5, and 7 before
* calling this for the first time. In a sparse filesystem it will be the
* sequence of powers of 3, 5, and 7: 1, 3, 5, 7, 9, 25, 27, 49, 81, ...
* For a non-sparse filesystem it will be every group: 1, 2, 3, 4, ...
*/
unsigned int ext4_list_backups(struct super_block *sb, unsigned int *three,
unsigned int *five, unsigned int *seven)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
unsigned int *min = three;
int mult = 3;
unsigned int ret;
if (ext4_has_feature_sparse_super2(sb)) {
do {
if (*min > 2)
return UINT_MAX;
ret = le32_to_cpu(es->s_backup_bgs[*min - 1]);
*min += 1;
} while (!ret);
return ret;
}
if (!ext4_has_feature_sparse_super(sb)) {
ret = *min;
*min += 1;
return ret;
}
if (*five < *min) {
min = five;
mult = 5;
}
if (*seven < *min) {
min = seven;
mult = 7;
}
ret = *min;
*min *= mult;
return ret;
}
/*
* Check that all of the backup GDT blocks are held in the primary GDT block.
* It is assumed that they are stored in group order. Returns the number of
* groups in current filesystem that have BACKUPS, or -ve error code.
*/
static int verify_reserved_gdb(struct super_block *sb,
ext4_group_t end,
struct buffer_head *primary)
{
const ext4_fsblk_t blk = primary->b_blocknr;
unsigned three = 1;
unsigned five = 5;
unsigned seven = 7;
unsigned grp;
__le32 *p = (__le32 *)primary->b_data;
int gdbackups = 0;
while ((grp = ext4_list_backups(sb, &three, &five, &seven)) < end) {
if (le32_to_cpu(*p++) !=
grp * EXT4_BLOCKS_PER_GROUP(sb) + blk){
ext4_warning(sb, "reserved GDT %llu"
" missing grp %d (%llu)",
blk, grp,
grp *
(ext4_fsblk_t)EXT4_BLOCKS_PER_GROUP(sb) +
blk);
return -EINVAL;
}
if (++gdbackups > EXT4_ADDR_PER_BLOCK(sb))
return -EFBIG;
}
return gdbackups;
}
/*
* Called when we need to bring a reserved group descriptor table block into
* use from the resize inode. The primary copy of the new GDT block currently
* is an indirect block (under the double indirect block in the resize inode).
* The new backup GDT blocks will be stored as leaf blocks in this indirect
* block, in group order. Even though we know all the block numbers we need,
* we check to ensure that the resize inode has actually reserved these blocks.
*
* Don't need to update the block bitmaps because the blocks are still in use.
*
* We get all of the error cases out of the way, so that we are sure to not
* fail once we start modifying the data on disk, because JBD has no rollback.
*/
static int add_new_gdb(handle_t *handle, struct inode *inode,
ext4_group_t group)
{
struct super_block *sb = inode->i_sb;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
unsigned long gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
ext4_fsblk_t gdblock = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + gdb_num;
struct buffer_head **o_group_desc, **n_group_desc = NULL;
struct buffer_head *dind = NULL;
struct buffer_head *gdb_bh = NULL;
int gdbackups;
struct ext4_iloc iloc = { .bh = NULL };
__le32 *data;
int err;
if (test_opt(sb, DEBUG))
printk(KERN_DEBUG
"EXT4-fs: ext4_add_new_gdb: adding group block %lu\n",
gdb_num);
gdb_bh = ext4_sb_bread(sb, gdblock, 0);
if (IS_ERR(gdb_bh))
return PTR_ERR(gdb_bh);
gdbackups = verify_reserved_gdb(sb, group, gdb_bh);
if (gdbackups < 0) {
err = gdbackups;
goto errout;
}
data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
dind = ext4_sb_bread(sb, le32_to_cpu(*data), 0);
if (IS_ERR(dind)) {
err = PTR_ERR(dind);
dind = NULL;
goto errout;
}
data = (__le32 *)dind->b_data;
if (le32_to_cpu(data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)]) != gdblock) {
ext4_warning(sb, "new group %u GDT block %llu not reserved",
group, gdblock);
err = -EINVAL;
goto errout;
}
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
EXT4_JTR_NONE);
if (unlikely(err))
goto errout;
BUFFER_TRACE(gdb_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gdb_bh, EXT4_JTR_NONE);
if (unlikely(err))
goto errout;
BUFFER_TRACE(dind, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, dind, EXT4_JTR_NONE);
if (unlikely(err)) {
ext4_std_error(sb, err);
goto errout;
}
/* ext4_reserve_inode_write() gets a reference on the iloc */
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (unlikely(err))
goto errout;
n_group_desc = kvmalloc((gdb_num + 1) * sizeof(struct buffer_head *),
GFP_KERNEL);
if (!n_group_desc) {
err = -ENOMEM;
ext4_warning(sb, "not enough memory for %lu groups",
gdb_num + 1);
goto errout;
}
/*
* Finally, we have all of the possible failures behind us...
*
* Remove new GDT block from inode double-indirect block and clear out
* the new GDT block for use (which also "frees" the backup GDT blocks
* from the reserved inode). We don't need to change the bitmaps for
* these blocks, because they are marked as in-use from being in the
* reserved inode, and will become GDT blocks (primary and backup).
*/
data[gdb_num % EXT4_ADDR_PER_BLOCK(sb)] = 0;
err = ext4_handle_dirty_metadata(handle, NULL, dind);
if (unlikely(err)) {
ext4_std_error(sb, err);
goto errout;
}
inode->i_blocks -= (gdbackups + 1) * sb->s_blocksize >>
(9 - EXT4_SB(sb)->s_cluster_bits);
ext4_mark_iloc_dirty(handle, inode, &iloc);
memset(gdb_bh->b_data, 0, sb->s_blocksize);
err = ext4_handle_dirty_metadata(handle, NULL, gdb_bh);
if (unlikely(err)) {
ext4_std_error(sb, err);
iloc.bh = NULL;
goto errout;
}
brelse(dind);
rcu_read_lock();
o_group_desc = rcu_dereference(EXT4_SB(sb)->s_group_desc);
memcpy(n_group_desc, o_group_desc,
EXT4_SB(sb)->s_gdb_count * sizeof(struct buffer_head *));
rcu_read_unlock();
n_group_desc[gdb_num] = gdb_bh;
rcu_assign_pointer(EXT4_SB(sb)->s_group_desc, n_group_desc);
EXT4_SB(sb)->s_gdb_count++;
ext4_kvfree_array_rcu(o_group_desc);
lock_buffer(EXT4_SB(sb)->s_sbh);
le16_add_cpu(&es->s_reserved_gdt_blocks, -1);
ext4_superblock_csum_set(sb);
unlock_buffer(EXT4_SB(sb)->s_sbh);
err = ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
if (err)
ext4_std_error(sb, err);
return err;
errout:
kvfree(n_group_desc);
brelse(iloc.bh);
brelse(dind);
brelse(gdb_bh);
ext4_debug("leaving with error %d\n", err);
return err;
}
/*
* add_new_gdb_meta_bg is the sister of add_new_gdb.
*/
static int add_new_gdb_meta_bg(struct super_block *sb,
handle_t *handle, ext4_group_t group) {
ext4_fsblk_t gdblock;
struct buffer_head *gdb_bh;
struct buffer_head **o_group_desc, **n_group_desc;
unsigned long gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
int err;
gdblock = ext4_meta_bg_first_block_no(sb, group) +
ext4_bg_has_super(sb, group);
gdb_bh = ext4_sb_bread(sb, gdblock, 0);
if (IS_ERR(gdb_bh))
return PTR_ERR(gdb_bh);
n_group_desc = kvmalloc((gdb_num + 1) * sizeof(struct buffer_head *),
GFP_KERNEL);
if (!n_group_desc) {
brelse(gdb_bh);
err = -ENOMEM;
ext4_warning(sb, "not enough memory for %lu groups",
gdb_num + 1);
return err;
}
rcu_read_lock();
o_group_desc = rcu_dereference(EXT4_SB(sb)->s_group_desc);
memcpy(n_group_desc, o_group_desc,
EXT4_SB(sb)->s_gdb_count * sizeof(struct buffer_head *));
rcu_read_unlock();
n_group_desc[gdb_num] = gdb_bh;
BUFFER_TRACE(gdb_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gdb_bh, EXT4_JTR_NONE);
if (err) {
kvfree(n_group_desc);
brelse(gdb_bh);
return err;
}
rcu_assign_pointer(EXT4_SB(sb)->s_group_desc, n_group_desc);
EXT4_SB(sb)->s_gdb_count++;
ext4_kvfree_array_rcu(o_group_desc);
return err;
}
/*
* Called when we are adding a new group which has a backup copy of each of
* the GDT blocks (i.e. sparse group) and there are reserved GDT blocks.
* We need to add these reserved backup GDT blocks to the resize inode, so
* that they are kept for future resizing and not allocated to files.
*
* Each reserved backup GDT block will go into a different indirect block.
* The indirect blocks are actually the primary reserved GDT blocks,
* so we know in advance what their block numbers are. We only get the
* double-indirect block to verify it is pointing to the primary reserved
* GDT blocks so we don't overwrite a data block by accident. The reserved
* backup GDT blocks are stored in their reserved primary GDT block.
*/
static int reserve_backup_gdb(handle_t *handle, struct inode *inode,
ext4_group_t group)
{
struct super_block *sb = inode->i_sb;
int reserved_gdb =le16_to_cpu(EXT4_SB(sb)->s_es->s_reserved_gdt_blocks);
int cluster_bits = EXT4_SB(sb)->s_cluster_bits;
struct buffer_head **primary;
struct buffer_head *dind;
struct ext4_iloc iloc;
ext4_fsblk_t blk;
__le32 *data, *end;
int gdbackups = 0;
int res, i;
int err;
primary = kmalloc_array(reserved_gdb, sizeof(*primary), GFP_NOFS);
if (!primary)
return -ENOMEM;
data = EXT4_I(inode)->i_data + EXT4_DIND_BLOCK;
dind = ext4_sb_bread(sb, le32_to_cpu(*data), 0);
if (IS_ERR(dind)) {
err = PTR_ERR(dind);
dind = NULL;
goto exit_free;
}
blk = EXT4_SB(sb)->s_sbh->b_blocknr + 1 + EXT4_SB(sb)->s_gdb_count;
data = (__le32 *)dind->b_data + (EXT4_SB(sb)->s_gdb_count %
EXT4_ADDR_PER_BLOCK(sb));
end = (__le32 *)dind->b_data + EXT4_ADDR_PER_BLOCK(sb);
/* Get each reserved primary GDT block and verify it holds backups */
for (res = 0; res < reserved_gdb; res++, blk++) {
if (le32_to_cpu(*data) != blk) {
ext4_warning(sb, "reserved block %llu"
" not at offset %ld",
blk,
(long)(data - (__le32 *)dind->b_data));
err = -EINVAL;
goto exit_bh;
}
primary[res] = ext4_sb_bread(sb, blk, 0);
if (IS_ERR(primary[res])) {
err = PTR_ERR(primary[res]);
primary[res] = NULL;
goto exit_bh;
}
gdbackups = verify_reserved_gdb(sb, group, primary[res]);
if (gdbackups < 0) {
brelse(primary[res]);
err = gdbackups;
goto exit_bh;
}
if (++data >= end)
data = (__le32 *)dind->b_data;
}
for (i = 0; i < reserved_gdb; i++) {
BUFFER_TRACE(primary[i], "get_write_access");
if ((err = ext4_journal_get_write_access(handle, sb, primary[i],
EXT4_JTR_NONE)))
goto exit_bh;
}
if ((err = ext4_reserve_inode_write(handle, inode, &iloc)))
goto exit_bh;
/*
* Finally we can add each of the reserved backup GDT blocks from
* the new group to its reserved primary GDT block.
*/
blk = group * EXT4_BLOCKS_PER_GROUP(sb);
for (i = 0; i < reserved_gdb; i++) {
int err2;
data = (__le32 *)primary[i]->b_data;
/* printk("reserving backup %lu[%u] = %lu\n",
primary[i]->b_blocknr, gdbackups,
blk + primary[i]->b_blocknr); */
data[gdbackups] = cpu_to_le32(blk + primary[i]->b_blocknr);
err2 = ext4_handle_dirty_metadata(handle, NULL, primary[i]);
if (!err)
err = err2;
}
inode->i_blocks += reserved_gdb * sb->s_blocksize >> (9 - cluster_bits);
ext4_mark_iloc_dirty(handle, inode, &iloc);
exit_bh:
while (--res >= 0)
brelse(primary[res]);
brelse(dind);
exit_free:
kfree(primary);
return err;
}
static inline void ext4_set_block_group_nr(struct super_block *sb, char *data,
ext4_group_t group)
{
struct ext4_super_block *es = (struct ext4_super_block *) data;
es->s_block_group_nr = cpu_to_le16(group);
if (ext4_has_metadata_csum(sb))
es->s_checksum = ext4_superblock_csum(sb, es);
}
/*
* Update the backup copies of the ext4 metadata. These don't need to be part
* of the main resize transaction, because e2fsck will re-write them if there
* is a problem (basically only OOM will cause a problem). However, we
* _should_ update the backups if possible, in case the primary gets trashed
* for some reason and we need to run e2fsck from a backup superblock. The
* important part is that the new block and inode counts are in the backup
* superblocks, and the location of the new group metadata in the GDT backups.
*
* We do not need take the s_resize_lock for this, because these
* blocks are not otherwise touched by the filesystem code when it is
* mounted. We don't need to worry about last changing from
* sbi->s_groups_count, because the worst that can happen is that we
* do not copy the full number of backups at this time. The resize
* which changed s_groups_count will backup again.
*/
static void update_backups(struct super_block *sb, sector_t blk_off, char *data,
int size, int meta_bg)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t last;
const int bpg = EXT4_BLOCKS_PER_GROUP(sb);
unsigned three = 1;
unsigned five = 5;
unsigned seven = 7;
ext4_group_t group = 0;
int rest = sb->s_blocksize - size;
handle_t *handle;
int err = 0, err2;
handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, EXT4_MAX_TRANS_DATA);
if (IS_ERR(handle)) {
group = 1;
err = PTR_ERR(handle);
goto exit_err;
}
if (meta_bg == 0) {
group = ext4_list_backups(sb, &three, &five, &seven);
last = sbi->s_groups_count;
} else {
group = ext4_get_group_number(sb, blk_off) + 1;
last = (ext4_group_t)(group + EXT4_DESC_PER_BLOCK(sb) - 2);
}
while (group < sbi->s_groups_count) {
struct buffer_head *bh;
ext4_fsblk_t backup_block;
int has_super = ext4_bg_has_super(sb, group);
ext4_fsblk_t first_block = ext4_group_first_block_no(sb, group);
/* Out of journal space, and can't get more - abort - so sad */
err = ext4_resize_ensure_credits_batch(handle, 1);
if (err < 0)
break;
if (meta_bg == 0)
backup_block = ((ext4_fsblk_t)group) * bpg + blk_off;
else
backup_block = first_block + has_super;
bh = sb_getblk(sb, backup_block);
if (unlikely(!bh)) {
err = -ENOMEM;
break;
}
ext4_debug("update metadata backup %llu(+%llu)\n",
backup_block, backup_block -
ext4_group_first_block_no(sb, group));
BUFFER_TRACE(bh, "get_write_access");
if ((err = ext4_journal_get_write_access(handle, sb, bh,
EXT4_JTR_NONE)))
break;
lock_buffer(bh);
memcpy(bh->b_data, data, size);
if (rest)
memset(bh->b_data + size, 0, rest);
if (has_super && (backup_block == first_block))
ext4_set_block_group_nr(sb, bh->b_data, group);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
if (unlikely(err))
ext4_std_error(sb, err);
brelse(bh);
if (meta_bg == 0)
group = ext4_list_backups(sb, &three, &five, &seven);
else if (group == last)
break;
else
group = last;
}
if ((err2 = ext4_journal_stop(handle)) && !err)
err = err2;
/*
* Ugh! Need to have e2fsck write the backup copies. It is too
* late to revert the resize, we shouldn't fail just because of
* the backup copies (they are only needed in case of corruption).
*
* However, if we got here we have a journal problem too, so we
* can't really start a transaction to mark the superblock.
* Chicken out and just set the flag on the hope it will be written
* to disk, and if not - we will simply wait until next fsck.
*/
exit_err:
if (err) {
ext4_warning(sb, "can't update backup for group %u (err %d), "
"forcing fsck on next reboot", group, err);
sbi->s_mount_state &= ~EXT4_VALID_FS;
sbi->s_es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
mark_buffer_dirty(sbi->s_sbh);
}
}
/*
* ext4_add_new_descs() adds @count group descriptor of groups
* starting at @group
*
* @handle: journal handle
* @sb: super block
* @group: the group no. of the first group desc to be added
* @resize_inode: the resize inode
* @count: number of group descriptors to be added
*/
static int ext4_add_new_descs(handle_t *handle, struct super_block *sb,
ext4_group_t group, struct inode *resize_inode,
ext4_group_t count)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct buffer_head *gdb_bh;
int i, gdb_off, gdb_num, err = 0;
int meta_bg;
meta_bg = ext4_has_feature_meta_bg(sb);
for (i = 0; i < count; i++, group++) {
int reserved_gdb = ext4_bg_has_super(sb, group) ?
le16_to_cpu(es->s_reserved_gdt_blocks) : 0;
gdb_off = group % EXT4_DESC_PER_BLOCK(sb);
gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
/*
* We will only either add reserved group blocks to a backup group
* or remove reserved blocks for the first group in a new group block.
* Doing both would be mean more complex code, and sane people don't
* use non-sparse filesystems anymore. This is already checked above.
*/
if (gdb_off) {
gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc,
gdb_num);
BUFFER_TRACE(gdb_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, gdb_bh,
EXT4_JTR_NONE);
if (!err && reserved_gdb && ext4_bg_num_gdb(sb, group))
err = reserve_backup_gdb(handle, resize_inode, group);
} else if (meta_bg != 0) {
err = add_new_gdb_meta_bg(sb, handle, group);
} else {
err = add_new_gdb(handle, resize_inode, group);
}
if (err)
break;
}
return err;
}
static struct buffer_head *ext4_get_bitmap(struct super_block *sb, __u64 block)
{
struct buffer_head *bh = sb_getblk(sb, block);
if (unlikely(!bh))
return NULL;
if (!bh_uptodate_or_lock(bh)) {
if (ext4_read_bh(bh, 0, NULL) < 0) {
brelse(bh);
return NULL;
}
}
return bh;
}
static int ext4_set_bitmap_checksums(struct super_block *sb,
struct ext4_group_desc *gdp,
struct ext4_new_group_data *group_data)
{
struct buffer_head *bh;
if (!ext4_has_metadata_csum(sb))
return 0;
bh = ext4_get_bitmap(sb, group_data->inode_bitmap);
if (!bh)
return -EIO;
ext4_inode_bitmap_csum_set(sb, gdp, bh,
EXT4_INODES_PER_GROUP(sb) / 8);
brelse(bh);
bh = ext4_get_bitmap(sb, group_data->block_bitmap);
if (!bh)
return -EIO;
ext4_block_bitmap_csum_set(sb, gdp, bh);
brelse(bh);
return 0;
}
/*
* ext4_setup_new_descs() will set up the group descriptor descriptors of a flex bg
*/
static int ext4_setup_new_descs(handle_t *handle, struct super_block *sb,
struct ext4_new_flex_group_data *flex_gd)
{
struct ext4_new_group_data *group_data = flex_gd->groups;
struct ext4_group_desc *gdp;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *gdb_bh;
ext4_group_t group;
__u16 *bg_flags = flex_gd->bg_flags;
int i, gdb_off, gdb_num, err = 0;
for (i = 0; i < flex_gd->count; i++, group_data++, bg_flags++) {
group = group_data->group;
gdb_off = group % EXT4_DESC_PER_BLOCK(sb);
gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
/*
* get_write_access() has been called on gdb_bh by ext4_add_new_desc().
*/
gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc, gdb_num);
/* Update group descriptor block for new group */
gdp = (struct ext4_group_desc *)(gdb_bh->b_data +
gdb_off * EXT4_DESC_SIZE(sb));
memset(gdp, 0, EXT4_DESC_SIZE(sb));
ext4_block_bitmap_set(sb, gdp, group_data->block_bitmap);
ext4_inode_bitmap_set(sb, gdp, group_data->inode_bitmap);
err = ext4_set_bitmap_checksums(sb, gdp, group_data);
if (err) {
ext4_std_error(sb, err);
break;
}
ext4_inode_table_set(sb, gdp, group_data->inode_table);
ext4_free_group_clusters_set(sb, gdp,
group_data->free_clusters_count);
ext4_free_inodes_set(sb, gdp, EXT4_INODES_PER_GROUP(sb));
if (ext4_has_group_desc_csum(sb))
ext4_itable_unused_set(sb, gdp,
EXT4_INODES_PER_GROUP(sb));
gdp->bg_flags = cpu_to_le16(*bg_flags);
ext4_group_desc_csum_set(sb, group, gdp);
err = ext4_handle_dirty_metadata(handle, NULL, gdb_bh);
if (unlikely(err)) {
ext4_std_error(sb, err);
break;
}
/*
* We can allocate memory for mb_alloc based on the new group
* descriptor
*/
err = ext4_mb_add_groupinfo(sb, group, gdp);
if (err)
break;
}
return err;
}
static void ext4_add_overhead(struct super_block *sb,
const ext4_fsblk_t overhead)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
sbi->s_overhead += overhead;
es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead);
smp_wmb();
}
/*
* ext4_update_super() updates the super block so that the newly added
* groups can be seen by the filesystem.
*
* @sb: super block
* @flex_gd: new added groups
*/
static void ext4_update_super(struct super_block *sb,
struct ext4_new_flex_group_data *flex_gd)
{
ext4_fsblk_t blocks_count = 0;
ext4_fsblk_t free_blocks = 0;
ext4_fsblk_t reserved_blocks = 0;
struct ext4_new_group_data *group_data = flex_gd->groups;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i;
BUG_ON(flex_gd->count == 0 || group_data == NULL);
/*
* Make the new blocks and inodes valid next. We do this before
* increasing the group count so that once the group is enabled,
* all of its blocks and inodes are already valid.
*
* We always allocate group-by-group, then block-by-block or
* inode-by-inode within a group, so enabling these
* blocks/inodes before the group is live won't actually let us
* allocate the new space yet.
*/
for (i = 0; i < flex_gd->count; i++) {
blocks_count += group_data[i].blocks_count;
free_blocks += EXT4_C2B(sbi, group_data[i].free_clusters_count);
}
reserved_blocks = ext4_r_blocks_count(es) * 100;
reserved_blocks = div64_u64(reserved_blocks, ext4_blocks_count(es));
reserved_blocks *= blocks_count;
do_div(reserved_blocks, 100);
lock_buffer(sbi->s_sbh);
ext4_blocks_count_set(es, ext4_blocks_count(es) + blocks_count);
ext4_free_blocks_count_set(es, ext4_free_blocks_count(es) + free_blocks);
le32_add_cpu(&es->s_inodes_count, EXT4_INODES_PER_GROUP(sb) *
flex_gd->count);
le32_add_cpu(&es->s_free_inodes_count, EXT4_INODES_PER_GROUP(sb) *
flex_gd->count);
ext4_debug("free blocks count %llu", ext4_free_blocks_count(es));
/*
* We need to protect s_groups_count against other CPUs seeing
* inconsistent state in the superblock.
*
* The precise rules we use are:
*
* * Writers must perform a smp_wmb() after updating all
* dependent data and before modifying the groups count
*
* * Readers must perform an smp_rmb() after reading the groups
* count and before reading any dependent data.
*
* NB. These rules can be relaxed when checking the group count
* while freeing data, as we can only allocate from a block
* group after serialising against the group count, and we can
* only then free after serialising in turn against that
* allocation.
*/
smp_wmb();
/* Update the global fs size fields */
sbi->s_groups_count += flex_gd->count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
/* Update the reserved block counts only once the new group is
* active. */
ext4_r_blocks_count_set(es, ext4_r_blocks_count(es) +
reserved_blocks);
/* Update the free space counts */
percpu_counter_add(&sbi->s_freeclusters_counter,
EXT4_NUM_B2C(sbi, free_blocks));
percpu_counter_add(&sbi->s_freeinodes_counter,
EXT4_INODES_PER_GROUP(sb) * flex_gd->count);
ext4_debug("free blocks count %llu",
percpu_counter_read(&sbi->s_freeclusters_counter));
if (ext4_has_feature_flex_bg(sb) && sbi->s_log_groups_per_flex) {
ext4_group_t flex_group;
struct flex_groups *fg;
flex_group = ext4_flex_group(sbi, group_data[0].group);
fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
atomic64_add(EXT4_NUM_B2C(sbi, free_blocks),
&fg->free_clusters);
atomic_add(EXT4_INODES_PER_GROUP(sb) * flex_gd->count,
&fg->free_inodes);
}
/*
* Update the fs overhead information.
*
* For bigalloc, if the superblock already has a properly calculated
* overhead, update it with a value based on numbers already computed
* above for the newly allocated capacity.
*/
if (ext4_has_feature_bigalloc(sb) && (sbi->s_overhead != 0))
ext4_add_overhead(sb,
EXT4_NUM_B2C(sbi, blocks_count - free_blocks));
else
ext4_calculate_overhead(sb);
es->s_overhead_clusters = cpu_to_le32(sbi->s_overhead);
ext4_superblock_csum_set(sb);
unlock_buffer(sbi->s_sbh);
if (test_opt(sb, DEBUG))
printk(KERN_DEBUG "EXT4-fs: added group %u:"
"%llu blocks(%llu free %llu reserved)\n", flex_gd->count,
blocks_count, free_blocks, reserved_blocks);
}
/* Add a flex group to an fs. Ensure we handle all possible error conditions
* _before_ we start modifying the filesystem, because we cannot abort the
* transaction and not have it write the data to disk.
*/
static int ext4_flex_group_add(struct super_block *sb,
struct inode *resize_inode,
struct ext4_new_flex_group_data *flex_gd)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t o_blocks_count;
ext4_grpblk_t last;
ext4_group_t group;
handle_t *handle;
unsigned reserved_gdb;
int err = 0, err2 = 0, credit;
BUG_ON(!flex_gd->count || !flex_gd->groups || !flex_gd->bg_flags);
reserved_gdb = le16_to_cpu(es->s_reserved_gdt_blocks);
o_blocks_count = ext4_blocks_count(es);
ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
BUG_ON(last);
err = setup_new_flex_group_blocks(sb, flex_gd);
if (err)
goto exit;
/*
* We will always be modifying at least the superblock and GDT
* blocks. If we are adding a group past the last current GDT block,
* we will also modify the inode and the dindirect block. If we
* are adding a group with superblock/GDT backups we will also
* modify each of the reserved GDT dindirect blocks.
*/
credit = 3; /* sb, resize inode, resize inode dindirect */
/* GDT blocks */
credit += 1 + DIV_ROUND_UP(flex_gd->count, EXT4_DESC_PER_BLOCK(sb));
credit += reserved_gdb; /* Reserved GDT dindirect blocks */
handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, credit);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto exit;
}
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
EXT4_JTR_NONE);
if (err)
goto exit_journal;
group = flex_gd->groups[0].group;
BUG_ON(group != sbi->s_groups_count);
err = ext4_add_new_descs(handle, sb, group,
resize_inode, flex_gd->count);
if (err)
goto exit_journal;
err = ext4_setup_new_descs(handle, sb, flex_gd);
if (err)
goto exit_journal;
ext4_update_super(sb, flex_gd);
err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
exit_journal:
err2 = ext4_journal_stop(handle);
if (!err)
err = err2;
if (!err) {
int gdb_num = group / EXT4_DESC_PER_BLOCK(sb);
int gdb_num_end = ((group + flex_gd->count - 1) /
EXT4_DESC_PER_BLOCK(sb));
int meta_bg = ext4_has_feature_meta_bg(sb);
sector_t old_gdb = 0;
update_backups(sb, ext4_group_first_block_no(sb, 0),
(char *)es, sizeof(struct ext4_super_block), 0);
for (; gdb_num <= gdb_num_end; gdb_num++) {
struct buffer_head *gdb_bh;
gdb_bh = sbi_array_rcu_deref(sbi, s_group_desc,
gdb_num);
if (old_gdb == gdb_bh->b_blocknr)
continue;
update_backups(sb, gdb_bh->b_blocknr, gdb_bh->b_data,
gdb_bh->b_size, meta_bg);
old_gdb = gdb_bh->b_blocknr;
}
}
exit:
return err;
}
static int ext4_setup_next_flex_gd(struct super_block *sb,
struct ext4_new_flex_group_data *flex_gd,
ext4_fsblk_t n_blocks_count,
unsigned long flexbg_size)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct ext4_new_group_data *group_data = flex_gd->groups;
ext4_fsblk_t o_blocks_count;
ext4_group_t n_group;
ext4_group_t group;
ext4_group_t last_group;
ext4_grpblk_t last;
ext4_grpblk_t clusters_per_group;
unsigned long i;
clusters_per_group = EXT4_CLUSTERS_PER_GROUP(sb);
o_blocks_count = ext4_blocks_count(es);
if (o_blocks_count == n_blocks_count)
return 0;
ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
BUG_ON(last);
ext4_get_group_no_and_offset(sb, n_blocks_count - 1, &n_group, &last);
last_group = group | (flexbg_size - 1);
if (last_group > n_group)
last_group = n_group;
flex_gd->count = last_group - group + 1;
for (i = 0; i < flex_gd->count; i++) {
int overhead;
group_data[i].group = group + i;
group_data[i].blocks_count = EXT4_BLOCKS_PER_GROUP(sb);
overhead = ext4_group_overhead_blocks(sb, group + i);
group_data[i].mdata_blocks = overhead;
group_data[i].free_clusters_count = EXT4_CLUSTERS_PER_GROUP(sb);
if (ext4_has_group_desc_csum(sb)) {
flex_gd->bg_flags[i] = EXT4_BG_BLOCK_UNINIT |
EXT4_BG_INODE_UNINIT;
if (!test_opt(sb, INIT_INODE_TABLE))
flex_gd->bg_flags[i] |= EXT4_BG_INODE_ZEROED;
} else
flex_gd->bg_flags[i] = EXT4_BG_INODE_ZEROED;
}
if (last_group == n_group && ext4_has_group_desc_csum(sb))
/* We need to initialize block bitmap of last group. */
flex_gd->bg_flags[i - 1] &= ~EXT4_BG_BLOCK_UNINIT;
if ((last_group == n_group) && (last != clusters_per_group - 1)) {
group_data[i - 1].blocks_count = EXT4_C2B(sbi, last + 1);
group_data[i - 1].free_clusters_count -= clusters_per_group -
last - 1;
}
return 1;
}
/* Add group descriptor data to an existing or new group descriptor block.
* Ensure we handle all possible error conditions _before_ we start modifying
* the filesystem, because we cannot abort the transaction and not have it
* write the data to disk.
*
* If we are on a GDT block boundary, we need to get the reserved GDT block.
* Otherwise, we may need to add backup GDT blocks for a sparse group.
*
* We only need to hold the superblock lock while we are actually adding
* in the new group's counts to the superblock. Prior to that we have
* not really "added" the group at all. We re-check that we are still
* adding in the last group in case things have changed since verifying.
*/
int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input)
{
struct ext4_new_flex_group_data flex_gd;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int reserved_gdb = ext4_bg_has_super(sb, input->group) ?
le16_to_cpu(es->s_reserved_gdt_blocks) : 0;
struct inode *inode = NULL;
int gdb_off;
int err;
__u16 bg_flags = 0;
gdb_off = input->group % EXT4_DESC_PER_BLOCK(sb);
if (gdb_off == 0 && !ext4_has_feature_sparse_super(sb)) {
ext4_warning(sb, "Can't resize non-sparse filesystem further");
return -EPERM;
}
if (ext4_blocks_count(es) + input->blocks_count <
ext4_blocks_count(es)) {
ext4_warning(sb, "blocks_count overflow");
return -EINVAL;
}
if (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) <
le32_to_cpu(es->s_inodes_count)) {
ext4_warning(sb, "inodes_count overflow");
return -EINVAL;
}
if (reserved_gdb || gdb_off == 0) {
if (!ext4_has_feature_resize_inode(sb) ||
!le16_to_cpu(es->s_reserved_gdt_blocks)) {
ext4_warning(sb,
"No reserved GDT blocks, can't resize");
return -EPERM;
}
inode = ext4_iget(sb, EXT4_RESIZE_INO, EXT4_IGET_SPECIAL);
if (IS_ERR(inode)) {
ext4_warning(sb, "Error opening resize inode");
return PTR_ERR(inode);
}
}
err = verify_group_input(sb, input);
if (err)
goto out;
err = ext4_alloc_flex_bg_array(sb, input->group + 1);
if (err)
goto out;
err = ext4_mb_alloc_groupinfo(sb, input->group + 1);
if (err)
goto out;
flex_gd.count = 1;
flex_gd.groups = input;
flex_gd.bg_flags = &bg_flags;
err = ext4_flex_group_add(sb, inode, &flex_gd);
out:
iput(inode);
return err;
} /* ext4_group_add */
/*
* extend a group without checking assuming that checking has been done.
*/
static int ext4_group_extend_no_check(struct super_block *sb,
ext4_fsblk_t o_blocks_count, ext4_grpblk_t add)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
handle_t *handle;
int err = 0, err2;
/* We will update the superblock, one block bitmap, and
* one group descriptor via ext4_group_add_blocks().
*/
handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, 3);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
ext4_warning(sb, "error %d on journal start", err);
return err;
}
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
EXT4_JTR_NONE);
if (err) {
ext4_warning(sb, "error %d on journal write access", err);
goto errout;
}
lock_buffer(EXT4_SB(sb)->s_sbh);
ext4_blocks_count_set(es, o_blocks_count + add);
ext4_free_blocks_count_set(es, ext4_free_blocks_count(es) + add);
ext4_superblock_csum_set(sb);
unlock_buffer(EXT4_SB(sb)->s_sbh);
ext4_debug("freeing blocks %llu through %llu\n", o_blocks_count,
o_blocks_count + add);
/* We add the blocks to the bitmap and set the group need init bit */
err = ext4_group_add_blocks(handle, sb, o_blocks_count, add);
if (err)
goto errout;
ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
ext4_debug("freed blocks %llu through %llu\n", o_blocks_count,
o_blocks_count + add);
errout:
err2 = ext4_journal_stop(handle);
if (err2 && !err)
err = err2;
if (!err) {
if (test_opt(sb, DEBUG))
printk(KERN_DEBUG "EXT4-fs: extended group to %llu "
"blocks\n", ext4_blocks_count(es));
update_backups(sb, ext4_group_first_block_no(sb, 0),
(char *)es, sizeof(struct ext4_super_block), 0);
}
return err;
}
/*
* Extend the filesystem to the new number of blocks specified. This entry
* point is only used to extend the current filesystem to the end of the last
* existing group. It can be accessed via ioctl, or by "remount,resize=<size>"
* for emergencies (because it has no dependencies on reserved blocks).
*
* If we _really_ wanted, we could use default values to call ext4_group_add()
* allow the "remount" trick to work for arbitrary resizing, assuming enough
* GDT blocks are reserved to grow to the desired size.
*/
int ext4_group_extend(struct super_block *sb, struct ext4_super_block *es,
ext4_fsblk_t n_blocks_count)
{
ext4_fsblk_t o_blocks_count;
ext4_grpblk_t last;
ext4_grpblk_t add;
struct buffer_head *bh;
ext4_group_t group;
o_blocks_count = ext4_blocks_count(es);
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"extending last group from %llu to %llu blocks",
o_blocks_count, n_blocks_count);
if (n_blocks_count == 0 || n_blocks_count == o_blocks_count)
return 0;
if (n_blocks_count > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) {
ext4_msg(sb, KERN_ERR,
"filesystem too large to resize to %llu blocks safely",
n_blocks_count);
return -EINVAL;
}
if (n_blocks_count < o_blocks_count) {
ext4_warning(sb, "can't shrink FS - resize aborted");
return -EINVAL;
}
/* Handle the remaining blocks in the last group only. */
ext4_get_group_no_and_offset(sb, o_blocks_count, &group, &last);
if (last == 0) {
ext4_warning(sb, "need to use ext2online to resize further");
return -EPERM;
}
add = EXT4_BLOCKS_PER_GROUP(sb) - last;
if (o_blocks_count + add < o_blocks_count) {
ext4_warning(sb, "blocks_count overflow");
return -EINVAL;
}
if (o_blocks_count + add > n_blocks_count)
add = n_blocks_count - o_blocks_count;
if (o_blocks_count + add < n_blocks_count)
ext4_warning(sb, "will only finish group (%llu blocks, %u new)",
o_blocks_count + add, add);
/* See if the device is actually as big as what was requested */
bh = ext4_sb_bread(sb, o_blocks_count + add - 1, 0);
if (IS_ERR(bh)) {
ext4_warning(sb, "can't read last block, resize aborted");
return -ENOSPC;
}
brelse(bh);
return ext4_group_extend_no_check(sb, o_blocks_count, add);
} /* ext4_group_extend */
static int num_desc_blocks(struct super_block *sb, ext4_group_t groups)
{
return (groups + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb);
}
/*
* Release the resize inode and drop the resize_inode feature if there
* are no more reserved gdt blocks, and then convert the file system
* to enable meta_bg
*/
static int ext4_convert_meta_bg(struct super_block *sb, struct inode *inode)
{
handle_t *handle;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_fsblk_t nr;
int i, ret, err = 0;
int credits = 1;
ext4_msg(sb, KERN_INFO, "Converting file system to meta_bg");
if (inode) {
if (es->s_reserved_gdt_blocks) {
ext4_error(sb, "Unexpected non-zero "
"s_reserved_gdt_blocks");
return -EPERM;
}
/* Do a quick sanity check of the resize inode */
if (inode->i_blocks != 1 << (inode->i_blkbits -
(9 - sbi->s_cluster_bits)))
goto invalid_resize_inode;
for (i = 0; i < EXT4_N_BLOCKS; i++) {
if (i == EXT4_DIND_BLOCK) {
if (ei->i_data[i])
continue;
else
goto invalid_resize_inode;
}
if (ei->i_data[i])
goto invalid_resize_inode;
}
credits += 3; /* block bitmap, bg descriptor, resize inode */
}
handle = ext4_journal_start_sb(sb, EXT4_HT_RESIZE, credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
EXT4_JTR_NONE);
if (err)
goto errout;
lock_buffer(sbi->s_sbh);
ext4_clear_feature_resize_inode(sb);
ext4_set_feature_meta_bg(sb);
sbi->s_es->s_first_meta_bg =
cpu_to_le32(num_desc_blocks(sb, sbi->s_groups_count));
ext4_superblock_csum_set(sb);
unlock_buffer(sbi->s_sbh);
err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
if (err) {
ext4_std_error(sb, err);
goto errout;
}
if (inode) {
nr = le32_to_cpu(ei->i_data[EXT4_DIND_BLOCK]);
ext4_free_blocks(handle, inode, NULL, nr, 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
ei->i_data[EXT4_DIND_BLOCK] = 0;
inode->i_blocks = 0;
err = ext4_mark_inode_dirty(handle, inode);
if (err)
ext4_std_error(sb, err);
}
errout:
ret = ext4_journal_stop(handle);
if (!err)
err = ret;
return ret;
invalid_resize_inode:
ext4_error(sb, "corrupted/inconsistent resize inode");
return -EINVAL;
}
/*
* ext4_resize_fs() resizes a fs to new size specified by @n_blocks_count
*
* @sb: super block of the fs to be resized
* @n_blocks_count: the number of blocks resides in the resized fs
*/
int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count)
{
struct ext4_new_flex_group_data *flex_gd = NULL;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct buffer_head *bh;
struct inode *resize_inode = NULL;
ext4_grpblk_t add, offset;
unsigned long n_desc_blocks;
unsigned long o_desc_blocks;
ext4_group_t o_group;
ext4_group_t n_group;
ext4_fsblk_t o_blocks_count;
ext4_fsblk_t n_blocks_count_retry = 0;
unsigned long last_update_time = 0;
int err = 0, flexbg_size = 1 << sbi->s_log_groups_per_flex;
int meta_bg;
/* See if the device is actually as big as what was requested */
bh = ext4_sb_bread(sb, n_blocks_count - 1, 0);
if (IS_ERR(bh)) {
ext4_warning(sb, "can't read last block, resize aborted");
return -ENOSPC;
}
brelse(bh);
/*
* For bigalloc, trim the requested size to the nearest cluster
* boundary to avoid creating an unusable filesystem. We do this
* silently, instead of returning an error, to avoid breaking
* callers that blindly resize the filesystem to the full size of
* the underlying block device.
*/
if (ext4_has_feature_bigalloc(sb))
n_blocks_count &= ~((1 << EXT4_CLUSTER_BITS(sb)) - 1);
retry:
o_blocks_count = ext4_blocks_count(es);
ext4_msg(sb, KERN_INFO, "resizing filesystem from %llu "
"to %llu blocks", o_blocks_count, n_blocks_count);
if (n_blocks_count < o_blocks_count) {
/* On-line shrinking not supported */
ext4_warning(sb, "can't shrink FS - resize aborted");
return -EINVAL;
}
if (n_blocks_count == o_blocks_count)
/* Nothing need to do */
return 0;
n_group = ext4_get_group_number(sb, n_blocks_count - 1);
if (n_group >= (0xFFFFFFFFUL / EXT4_INODES_PER_GROUP(sb))) {
ext4_warning(sb, "resize would cause inodes_count overflow");
return -EINVAL;
}
ext4_get_group_no_and_offset(sb, o_blocks_count - 1, &o_group, &offset);
n_desc_blocks = num_desc_blocks(sb, n_group + 1);
o_desc_blocks = num_desc_blocks(sb, sbi->s_groups_count);
meta_bg = ext4_has_feature_meta_bg(sb);
if (ext4_has_feature_resize_inode(sb)) {
if (meta_bg) {
ext4_error(sb, "resize_inode and meta_bg enabled "
"simultaneously");
return -EINVAL;
}
if (n_desc_blocks > o_desc_blocks +
le16_to_cpu(es->s_reserved_gdt_blocks)) {
n_blocks_count_retry = n_blocks_count;
n_desc_blocks = o_desc_blocks +
le16_to_cpu(es->s_reserved_gdt_blocks);
n_group = n_desc_blocks * EXT4_DESC_PER_BLOCK(sb);
n_blocks_count = (ext4_fsblk_t)n_group *
EXT4_BLOCKS_PER_GROUP(sb) +
le32_to_cpu(es->s_first_data_block);
n_group--; /* set to last group number */
}
if (!resize_inode)
resize_inode = ext4_iget(sb, EXT4_RESIZE_INO,
EXT4_IGET_SPECIAL);
if (IS_ERR(resize_inode)) {
ext4_warning(sb, "Error opening resize inode");
return PTR_ERR(resize_inode);
}
}
if ((!resize_inode && !meta_bg) || n_blocks_count == o_blocks_count) {
err = ext4_convert_meta_bg(sb, resize_inode);
if (err)
goto out;
if (resize_inode) {
iput(resize_inode);
resize_inode = NULL;
}
if (n_blocks_count_retry) {
n_blocks_count = n_blocks_count_retry;
n_blocks_count_retry = 0;
goto retry;
}
}
/*
* Make sure the last group has enough space so that it's
* guaranteed to have enough space for all metadata blocks
* that it might need to hold. (We might not need to store
* the inode table blocks in the last block group, but there
* will be cases where this might be needed.)
*/
if ((ext4_group_first_block_no(sb, n_group) +
ext4_group_overhead_blocks(sb, n_group) + 2 +
sbi->s_itb_per_group + sbi->s_cluster_ratio) >= n_blocks_count) {
n_blocks_count = ext4_group_first_block_no(sb, n_group);
n_group--;
n_blocks_count_retry = 0;
if (resize_inode) {
iput(resize_inode);
resize_inode = NULL;
}
goto retry;
}
/* extend the last group */
if (n_group == o_group)
add = n_blocks_count - o_blocks_count;
else
add = EXT4_C2B(sbi, EXT4_CLUSTERS_PER_GROUP(sb) - (offset + 1));
if (add > 0) {
err = ext4_group_extend_no_check(sb, o_blocks_count, add);
if (err)
goto out;
}
if (ext4_blocks_count(es) == n_blocks_count && n_blocks_count_retry == 0)
goto out;
err = ext4_alloc_flex_bg_array(sb, n_group + 1);
if (err)
goto out;
err = ext4_mb_alloc_groupinfo(sb, n_group + 1);
if (err)
goto out;
flex_gd = alloc_flex_gd(flexbg_size);
if (flex_gd == NULL) {
err = -ENOMEM;
goto out;
}
/* Add flex groups. Note that a regular group is a
* flex group with 1 group.
*/
while (ext4_setup_next_flex_gd(sb, flex_gd, n_blocks_count,
flexbg_size)) {
if (time_is_before_jiffies(last_update_time + HZ * 10)) {
if (last_update_time)
ext4_msg(sb, KERN_INFO,
"resized to %llu blocks",
ext4_blocks_count(es));
last_update_time = jiffies;
}
if (ext4_alloc_group_tables(sb, flex_gd, flexbg_size) != 0)
break;
err = ext4_flex_group_add(sb, resize_inode, flex_gd);
if (unlikely(err))
break;
}
if (!err && n_blocks_count_retry) {
n_blocks_count = n_blocks_count_retry;
n_blocks_count_retry = 0;
free_flex_gd(flex_gd);
flex_gd = NULL;
if (resize_inode) {
iput(resize_inode);
resize_inode = NULL;
}
goto retry;
}
out:
if (flex_gd)
free_flex_gd(flex_gd);
if (resize_inode != NULL)
iput(resize_inode);
if (err)
ext4_warning(sb, "error (%d) occurred during "
"file system resize", err);
ext4_msg(sb, KERN_INFO, "resized filesystem to %llu",
ext4_blocks_count(es));
return err;
}
| linux-master | fs/ext4/resize.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/sysfs.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Theodore Ts'o ([email protected])
*
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include <linux/part_stat.h>
#include "ext4.h"
#include "ext4_jbd2.h"
typedef enum {
attr_noop,
attr_delayed_allocation_blocks,
attr_session_write_kbytes,
attr_lifetime_write_kbytes,
attr_reserved_clusters,
attr_sra_exceeded_retry_limit,
attr_inode_readahead,
attr_trigger_test_error,
attr_first_error_time,
attr_last_error_time,
attr_feature,
attr_pointer_ui,
attr_pointer_ul,
attr_pointer_u64,
attr_pointer_u8,
attr_pointer_string,
attr_pointer_atomic,
attr_journal_task,
} attr_id_t;
typedef enum {
ptr_explicit,
ptr_ext4_sb_info_offset,
ptr_ext4_super_block_offset,
} attr_ptr_t;
static const char proc_dirname[] = "fs/ext4";
static struct proc_dir_entry *ext4_proc_root;
struct ext4_attr {
struct attribute attr;
short attr_id;
short attr_ptr;
unsigned short attr_size;
union {
int offset;
void *explicit_ptr;
} u;
};
static ssize_t session_write_kbytes_show(struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
return sysfs_emit(buf, "%lu\n",
(part_stat_read(sb->s_bdev, sectors[STAT_WRITE]) -
sbi->s_sectors_written_start) >> 1);
}
static ssize_t lifetime_write_kbytes_show(struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
return sysfs_emit(buf, "%llu\n",
(unsigned long long)(sbi->s_kbytes_written +
((part_stat_read(sb->s_bdev, sectors[STAT_WRITE]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1)));
}
static ssize_t inode_readahead_blks_store(struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long t;
int ret;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
if (t && (!is_power_of_2(t) || t > 0x40000000))
return -EINVAL;
sbi->s_inode_readahead_blks = t;
return count;
}
static ssize_t reserved_clusters_store(struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long long val;
ext4_fsblk_t clusters = (ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits);
int ret;
ret = kstrtoull(skip_spaces(buf), 0, &val);
if (ret || val >= clusters)
return -EINVAL;
atomic64_set(&sbi->s_resv_clusters, val);
return count;
}
static ssize_t trigger_test_error(struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
int len = count;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (len && buf[len-1] == '\n')
len--;
if (len)
ext4_error(sbi->s_sb, "%.*s", len, buf);
return count;
}
static ssize_t journal_task_show(struct ext4_sb_info *sbi, char *buf)
{
if (!sbi->s_journal)
return sysfs_emit(buf, "<none>\n");
return sysfs_emit(buf, "%d\n",
task_pid_vnr(sbi->s_journal->j_task));
}
#define EXT4_ATTR(_name,_mode,_id) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.attr_id = attr_##_id, \
}
#define EXT4_ATTR_FUNC(_name,_mode) EXT4_ATTR(_name,_mode,_name)
#define EXT4_ATTR_FEATURE(_name) EXT4_ATTR(_name, 0444, feature)
#define EXT4_ATTR_OFFSET(_name,_mode,_id,_struct,_elname) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.attr_id = attr_##_id, \
.attr_ptr = ptr_##_struct##_offset, \
.u = { \
.offset = offsetof(struct _struct, _elname),\
}, \
}
#define EXT4_ATTR_STRING(_name,_mode,_size,_struct,_elname) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.attr_id = attr_pointer_string, \
.attr_size = _size, \
.attr_ptr = ptr_##_struct##_offset, \
.u = { \
.offset = offsetof(struct _struct, _elname),\
}, \
}
#define EXT4_RO_ATTR_ES_UI(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0444, pointer_ui, ext4_super_block, _elname)
#define EXT4_RO_ATTR_ES_U8(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0444, pointer_u8, ext4_super_block, _elname)
#define EXT4_RO_ATTR_ES_U64(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0444, pointer_u64, ext4_super_block, _elname)
#define EXT4_RO_ATTR_ES_STRING(_name,_elname,_size) \
EXT4_ATTR_STRING(_name, 0444, _size, ext4_super_block, _elname)
#define EXT4_RW_ATTR_SBI_UI(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0644, pointer_ui, ext4_sb_info, _elname)
#define EXT4_RW_ATTR_SBI_UL(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0644, pointer_ul, ext4_sb_info, _elname)
#define EXT4_RO_ATTR_SBI_ATOMIC(_name,_elname) \
EXT4_ATTR_OFFSET(_name, 0444, pointer_atomic, ext4_sb_info, _elname)
#define EXT4_ATTR_PTR(_name,_mode,_id,_ptr) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.attr_id = attr_##_id, \
.attr_ptr = ptr_explicit, \
.u = { \
.explicit_ptr = _ptr, \
}, \
}
#define ATTR_LIST(name) &ext4_attr_##name.attr
EXT4_ATTR_FUNC(delayed_allocation_blocks, 0444);
EXT4_ATTR_FUNC(session_write_kbytes, 0444);
EXT4_ATTR_FUNC(lifetime_write_kbytes, 0444);
EXT4_ATTR_FUNC(reserved_clusters, 0644);
EXT4_ATTR_FUNC(sra_exceeded_retry_limit, 0444);
EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, inode_readahead,
ext4_sb_info, s_inode_readahead_blks);
EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs);
EXT4_RW_ATTR_SBI_UI(mb_stream_req, s_mb_stream_request);
EXT4_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc);
EXT4_RW_ATTR_SBI_UI(mb_max_linear_groups, s_mb_max_linear_groups);
EXT4_RW_ATTR_SBI_UI(extent_max_zeroout_kb, s_extent_max_zeroout_kb);
EXT4_ATTR(trigger_fs_error, 0200, trigger_test_error);
EXT4_RW_ATTR_SBI_UI(err_ratelimit_interval_ms, s_err_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(err_ratelimit_burst, s_err_ratelimit_state.burst);
EXT4_RW_ATTR_SBI_UI(warning_ratelimit_interval_ms, s_warning_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(warning_ratelimit_burst, s_warning_ratelimit_state.burst);
EXT4_RW_ATTR_SBI_UI(msg_ratelimit_interval_ms, s_msg_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(msg_ratelimit_burst, s_msg_ratelimit_state.burst);
EXT4_RW_ATTR_SBI_UI(mb_best_avail_max_trim_order, s_mb_best_avail_max_trim_order);
#ifdef CONFIG_EXT4_DEBUG
EXT4_RW_ATTR_SBI_UL(simulate_fail, s_simulate_fail);
#endif
EXT4_RO_ATTR_SBI_ATOMIC(warning_count, s_warning_count);
EXT4_RO_ATTR_SBI_ATOMIC(msg_count, s_msg_count);
EXT4_RO_ATTR_ES_UI(errors_count, s_error_count);
EXT4_RO_ATTR_ES_U8(first_error_errcode, s_first_error_errcode);
EXT4_RO_ATTR_ES_U8(last_error_errcode, s_last_error_errcode);
EXT4_RO_ATTR_ES_UI(first_error_ino, s_first_error_ino);
EXT4_RO_ATTR_ES_UI(last_error_ino, s_last_error_ino);
EXT4_RO_ATTR_ES_U64(first_error_block, s_first_error_block);
EXT4_RO_ATTR_ES_U64(last_error_block, s_last_error_block);
EXT4_RO_ATTR_ES_UI(first_error_line, s_first_error_line);
EXT4_RO_ATTR_ES_UI(last_error_line, s_last_error_line);
EXT4_RO_ATTR_ES_STRING(first_error_func, s_first_error_func, 32);
EXT4_RO_ATTR_ES_STRING(last_error_func, s_last_error_func, 32);
EXT4_ATTR(first_error_time, 0444, first_error_time);
EXT4_ATTR(last_error_time, 0444, last_error_time);
EXT4_ATTR(journal_task, 0444, journal_task);
EXT4_RW_ATTR_SBI_UI(mb_prefetch, s_mb_prefetch);
EXT4_RW_ATTR_SBI_UI(mb_prefetch_limit, s_mb_prefetch_limit);
EXT4_RW_ATTR_SBI_UL(last_trim_minblks, s_last_trim_minblks);
static unsigned int old_bump_val = 128;
EXT4_ATTR_PTR(max_writeback_mb_bump, 0444, pointer_ui, &old_bump_val);
static struct attribute *ext4_attrs[] = {
ATTR_LIST(delayed_allocation_blocks),
ATTR_LIST(session_write_kbytes),
ATTR_LIST(lifetime_write_kbytes),
ATTR_LIST(reserved_clusters),
ATTR_LIST(sra_exceeded_retry_limit),
ATTR_LIST(inode_readahead_blks),
ATTR_LIST(inode_goal),
ATTR_LIST(mb_stats),
ATTR_LIST(mb_max_to_scan),
ATTR_LIST(mb_min_to_scan),
ATTR_LIST(mb_order2_req),
ATTR_LIST(mb_stream_req),
ATTR_LIST(mb_group_prealloc),
ATTR_LIST(mb_max_linear_groups),
ATTR_LIST(max_writeback_mb_bump),
ATTR_LIST(extent_max_zeroout_kb),
ATTR_LIST(trigger_fs_error),
ATTR_LIST(err_ratelimit_interval_ms),
ATTR_LIST(err_ratelimit_burst),
ATTR_LIST(warning_ratelimit_interval_ms),
ATTR_LIST(warning_ratelimit_burst),
ATTR_LIST(msg_ratelimit_interval_ms),
ATTR_LIST(msg_ratelimit_burst),
ATTR_LIST(mb_best_avail_max_trim_order),
ATTR_LIST(errors_count),
ATTR_LIST(warning_count),
ATTR_LIST(msg_count),
ATTR_LIST(first_error_ino),
ATTR_LIST(last_error_ino),
ATTR_LIST(first_error_block),
ATTR_LIST(last_error_block),
ATTR_LIST(first_error_line),
ATTR_LIST(last_error_line),
ATTR_LIST(first_error_func),
ATTR_LIST(last_error_func),
ATTR_LIST(first_error_errcode),
ATTR_LIST(last_error_errcode),
ATTR_LIST(first_error_time),
ATTR_LIST(last_error_time),
ATTR_LIST(journal_task),
#ifdef CONFIG_EXT4_DEBUG
ATTR_LIST(simulate_fail),
#endif
ATTR_LIST(mb_prefetch),
ATTR_LIST(mb_prefetch_limit),
ATTR_LIST(last_trim_minblks),
NULL,
};
ATTRIBUTE_GROUPS(ext4);
/* Features this copy of ext4 supports */
EXT4_ATTR_FEATURE(lazy_itable_init);
EXT4_ATTR_FEATURE(batched_discard);
EXT4_ATTR_FEATURE(meta_bg_resize);
#ifdef CONFIG_FS_ENCRYPTION
EXT4_ATTR_FEATURE(encryption);
EXT4_ATTR_FEATURE(test_dummy_encryption_v2);
#endif
#if IS_ENABLED(CONFIG_UNICODE)
EXT4_ATTR_FEATURE(casefold);
#endif
#ifdef CONFIG_FS_VERITY
EXT4_ATTR_FEATURE(verity);
#endif
EXT4_ATTR_FEATURE(metadata_csum_seed);
EXT4_ATTR_FEATURE(fast_commit);
#if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_FS_ENCRYPTION)
EXT4_ATTR_FEATURE(encrypted_casefold);
#endif
static struct attribute *ext4_feat_attrs[] = {
ATTR_LIST(lazy_itable_init),
ATTR_LIST(batched_discard),
ATTR_LIST(meta_bg_resize),
#ifdef CONFIG_FS_ENCRYPTION
ATTR_LIST(encryption),
ATTR_LIST(test_dummy_encryption_v2),
#endif
#if IS_ENABLED(CONFIG_UNICODE)
ATTR_LIST(casefold),
#endif
#ifdef CONFIG_FS_VERITY
ATTR_LIST(verity),
#endif
ATTR_LIST(metadata_csum_seed),
ATTR_LIST(fast_commit),
#if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_FS_ENCRYPTION)
ATTR_LIST(encrypted_casefold),
#endif
NULL,
};
ATTRIBUTE_GROUPS(ext4_feat);
static void *calc_ptr(struct ext4_attr *a, struct ext4_sb_info *sbi)
{
switch (a->attr_ptr) {
case ptr_explicit:
return a->u.explicit_ptr;
case ptr_ext4_sb_info_offset:
return (void *) (((char *) sbi) + a->u.offset);
case ptr_ext4_super_block_offset:
return (void *) (((char *) sbi->s_es) + a->u.offset);
}
return NULL;
}
static ssize_t __print_tstamp(char *buf, __le32 lo, __u8 hi)
{
return sysfs_emit(buf, "%lld\n",
((time64_t)hi << 32) + le32_to_cpu(lo));
}
#define print_tstamp(buf, es, tstamp) \
__print_tstamp(buf, (es)->tstamp, (es)->tstamp ## _hi)
static ssize_t ext4_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
void *ptr = calc_ptr(a, sbi);
switch (a->attr_id) {
case attr_delayed_allocation_blocks:
return sysfs_emit(buf, "%llu\n",
(s64) EXT4_C2B(sbi,
percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
case attr_session_write_kbytes:
return session_write_kbytes_show(sbi, buf);
case attr_lifetime_write_kbytes:
return lifetime_write_kbytes_show(sbi, buf);
case attr_reserved_clusters:
return sysfs_emit(buf, "%llu\n",
(unsigned long long)
atomic64_read(&sbi->s_resv_clusters));
case attr_sra_exceeded_retry_limit:
return sysfs_emit(buf, "%llu\n",
(unsigned long long)
percpu_counter_sum(&sbi->s_sra_exceeded_retry_limit));
case attr_inode_readahead:
case attr_pointer_ui:
if (!ptr)
return 0;
if (a->attr_ptr == ptr_ext4_super_block_offset)
return sysfs_emit(buf, "%u\n",
le32_to_cpup(ptr));
else
return sysfs_emit(buf, "%u\n",
*((unsigned int *) ptr));
case attr_pointer_ul:
if (!ptr)
return 0;
return sysfs_emit(buf, "%lu\n",
*((unsigned long *) ptr));
case attr_pointer_u8:
if (!ptr)
return 0;
return sysfs_emit(buf, "%u\n",
*((unsigned char *) ptr));
case attr_pointer_u64:
if (!ptr)
return 0;
if (a->attr_ptr == ptr_ext4_super_block_offset)
return sysfs_emit(buf, "%llu\n",
le64_to_cpup(ptr));
else
return sysfs_emit(buf, "%llu\n",
*((unsigned long long *) ptr));
case attr_pointer_string:
if (!ptr)
return 0;
return sysfs_emit(buf, "%.*s\n", a->attr_size,
(char *) ptr);
case attr_pointer_atomic:
if (!ptr)
return 0;
return sysfs_emit(buf, "%d\n",
atomic_read((atomic_t *) ptr));
case attr_feature:
return sysfs_emit(buf, "supported\n");
case attr_first_error_time:
return print_tstamp(buf, sbi->s_es, s_first_error_time);
case attr_last_error_time:
return print_tstamp(buf, sbi->s_es, s_last_error_time);
case attr_journal_task:
return journal_task_show(sbi, buf);
}
return 0;
}
static ssize_t ext4_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf, size_t len)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
void *ptr = calc_ptr(a, sbi);
unsigned long t;
int ret;
switch (a->attr_id) {
case attr_reserved_clusters:
return reserved_clusters_store(sbi, buf, len);
case attr_pointer_ui:
if (!ptr)
return 0;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
if (a->attr_ptr == ptr_ext4_super_block_offset)
*((__le32 *) ptr) = cpu_to_le32(t);
else
*((unsigned int *) ptr) = t;
return len;
case attr_pointer_ul:
if (!ptr)
return 0;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
*((unsigned long *) ptr) = t;
return len;
case attr_inode_readahead:
return inode_readahead_blks_store(sbi, buf, len);
case attr_trigger_test_error:
return trigger_test_error(sbi, buf, len);
}
return 0;
}
static void ext4_sb_release(struct kobject *kobj)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
complete(&sbi->s_kobj_unregister);
}
static void ext4_feat_release(struct kobject *kobj)
{
kfree(kobj);
}
static const struct sysfs_ops ext4_attr_ops = {
.show = ext4_attr_show,
.store = ext4_attr_store,
};
static const struct kobj_type ext4_sb_ktype = {
.default_groups = ext4_groups,
.sysfs_ops = &ext4_attr_ops,
.release = ext4_sb_release,
};
static const struct kobj_type ext4_feat_ktype = {
.default_groups = ext4_feat_groups,
.sysfs_ops = &ext4_attr_ops,
.release = ext4_feat_release,
};
void ext4_notify_error_sysfs(struct ext4_sb_info *sbi)
{
sysfs_notify(&sbi->s_kobj, NULL, "errors_count");
}
static struct kobject *ext4_root;
static struct kobject *ext4_feat;
int ext4_register_sysfs(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err;
init_completion(&sbi->s_kobj_unregister);
err = kobject_init_and_add(&sbi->s_kobj, &ext4_sb_ktype, ext4_root,
"%s", sb->s_id);
if (err) {
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
return err;
}
if (ext4_proc_root)
sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root);
if (sbi->s_proc) {
proc_create_single_data("options", S_IRUGO, sbi->s_proc,
ext4_seq_options_show, sb);
proc_create_single_data("es_shrinker_info", S_IRUGO,
sbi->s_proc, ext4_seq_es_shrinker_info_show,
sb);
proc_create_single_data("fc_info", 0444, sbi->s_proc,
ext4_fc_info_show, sb);
proc_create_seq_data("mb_groups", S_IRUGO, sbi->s_proc,
&ext4_mb_seq_groups_ops, sb);
proc_create_single_data("mb_stats", 0444, sbi->s_proc,
ext4_seq_mb_stats_show, sb);
proc_create_seq_data("mb_structs_summary", 0444, sbi->s_proc,
&ext4_mb_seq_structs_summary_ops, sb);
}
return 0;
}
void ext4_unregister_sysfs(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_proc)
remove_proc_subtree(sb->s_id, ext4_proc_root);
kobject_del(&sbi->s_kobj);
}
int __init ext4_init_sysfs(void)
{
int ret;
ext4_root = kobject_create_and_add("ext4", fs_kobj);
if (!ext4_root)
return -ENOMEM;
ext4_feat = kzalloc(sizeof(*ext4_feat), GFP_KERNEL);
if (!ext4_feat) {
ret = -ENOMEM;
goto root_err;
}
ret = kobject_init_and_add(ext4_feat, &ext4_feat_ktype,
ext4_root, "features");
if (ret)
goto feat_err;
ext4_proc_root = proc_mkdir(proc_dirname, NULL);
return ret;
feat_err:
kobject_put(ext4_feat);
ext4_feat = NULL;
root_err:
kobject_put(ext4_root);
ext4_root = NULL;
return ret;
}
void ext4_exit_sysfs(void)
{
kobject_put(ext4_feat);
ext4_feat = NULL;
kobject_put(ext4_root);
ext4_root = NULL;
remove_proc_entry(proc_dirname, NULL);
ext4_proc_root = NULL;
}
| linux-master | fs/ext4/sysfs.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/xattr.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <[email protected]>
*
* Fix by Harrison Xing <[email protected]>.
* Ext4 code with a lot of help from Eric Jarman <[email protected]>.
* Extended attributes for symlinks and special files added per
* suggestion of Luka Renko <[email protected]>.
* xattr consolidation Copyright (c) 2004 James Morris <[email protected]>,
* Red Hat Inc.
* ea-in-inode support by Alex Tomas <[email protected]> aka bzzz
* and Andreas Gruenbacher <[email protected]>.
*/
/*
* Extended attributes are stored directly in inodes (on file systems with
* inodes bigger than 128 bytes) and on additional disk blocks. The i_file_acl
* field contains the block number if an inode uses an additional block. All
* attributes must fit in the inode and one additional block. Blocks that
* contain the identical set of attributes may be shared among several inodes.
* Identical blocks are detected by keeping a cache of blocks that have
* recently been accessed.
*
* The attributes in inodes and on blocks have a different header; the entries
* are stored in the same format:
*
* +------------------+
* | header |
* | entry 1 | |
* | entry 2 | | growing downwards
* | entry 3 | v
* | four null bytes |
* | . . . |
* | value 1 | ^
* | value 3 | | growing upwards
* | value 2 | |
* +------------------+
*
* The header is followed by multiple entry descriptors. In disk blocks, the
* entry descriptors are kept sorted. In inodes, they are unsorted. The
* attribute values are aligned to the end of the block in no specific order.
*
* Locking strategy
* ----------------
* EXT4_I(inode)->i_file_acl is protected by EXT4_I(inode)->xattr_sem.
* EA blocks are only changed if they are exclusive to an inode, so
* holding xattr_sem also means that nothing but the EA block's reference
* count can change. Multiple writers to the same block are synchronized
* by the buffer lock.
*/
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/iversion.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#ifdef EXT4_XATTR_DEBUG
# define ea_idebug(inode, fmt, ...) \
printk(KERN_DEBUG "inode %s:%lu: " fmt "\n", \
inode->i_sb->s_id, inode->i_ino, ##__VA_ARGS__)
# define ea_bdebug(bh, fmt, ...) \
printk(KERN_DEBUG "block %pg:%lu: " fmt "\n", \
bh->b_bdev, (unsigned long)bh->b_blocknr, ##__VA_ARGS__)
#else
# define ea_idebug(inode, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
# define ea_bdebug(bh, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#endif
static void ext4_xattr_block_cache_insert(struct mb_cache *,
struct buffer_head *);
static struct buffer_head *
ext4_xattr_block_cache_find(struct inode *, struct ext4_xattr_header *,
struct mb_cache_entry **);
static __le32 ext4_xattr_hash_entry(char *name, size_t name_len, __le32 *value,
size_t value_count);
static __le32 ext4_xattr_hash_entry_signed(char *name, size_t name_len, __le32 *value,
size_t value_count);
static void ext4_xattr_rehash(struct ext4_xattr_header *);
static const struct xattr_handler * const ext4_xattr_handler_map[] = {
[EXT4_XATTR_INDEX_USER] = &ext4_xattr_user_handler,
#ifdef CONFIG_EXT4_FS_POSIX_ACL
[EXT4_XATTR_INDEX_POSIX_ACL_ACCESS] = &nop_posix_acl_access,
[EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT] = &nop_posix_acl_default,
#endif
[EXT4_XATTR_INDEX_TRUSTED] = &ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
[EXT4_XATTR_INDEX_SECURITY] = &ext4_xattr_security_handler,
#endif
[EXT4_XATTR_INDEX_HURD] = &ext4_xattr_hurd_handler,
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&ext4_xattr_user_handler,
&ext4_xattr_trusted_handler,
#ifdef CONFIG_EXT4_FS_SECURITY
&ext4_xattr_security_handler,
#endif
&ext4_xattr_hurd_handler,
NULL
};
#define EA_BLOCK_CACHE(inode) (((struct ext4_sb_info *) \
inode->i_sb->s_fs_info)->s_ea_block_cache)
#define EA_INODE_CACHE(inode) (((struct ext4_sb_info *) \
inode->i_sb->s_fs_info)->s_ea_inode_cache)
static int
ext4_expand_inode_array(struct ext4_xattr_inode_array **ea_inode_array,
struct inode *inode);
#ifdef CONFIG_LOCKDEP
void ext4_xattr_inode_set_class(struct inode *ea_inode)
{
struct ext4_inode_info *ei = EXT4_I(ea_inode);
lockdep_set_subclass(&ea_inode->i_rwsem, 1);
(void) ei; /* shut up clang warning if !CONFIG_LOCKDEP */
lockdep_set_subclass(&ei->i_data_sem, I_DATA_SEM_EA);
}
#endif
static __le32 ext4_xattr_block_csum(struct inode *inode,
sector_t block_nr,
struct ext4_xattr_header *hdr)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__le64 dsk_block_nr = cpu_to_le64(block_nr);
__u32 dummy_csum = 0;
int offset = offsetof(struct ext4_xattr_header, h_checksum);
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&dsk_block_nr,
sizeof(dsk_block_nr));
csum = ext4_chksum(sbi, csum, (__u8 *)hdr, offset);
csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
offset += sizeof(dummy_csum);
csum = ext4_chksum(sbi, csum, (__u8 *)hdr + offset,
EXT4_BLOCK_SIZE(inode->i_sb) - offset);
return cpu_to_le32(csum);
}
static int ext4_xattr_block_csum_verify(struct inode *inode,
struct buffer_head *bh)
{
struct ext4_xattr_header *hdr = BHDR(bh);
int ret = 1;
if (ext4_has_metadata_csum(inode->i_sb)) {
lock_buffer(bh);
ret = (hdr->h_checksum == ext4_xattr_block_csum(inode,
bh->b_blocknr, hdr));
unlock_buffer(bh);
}
return ret;
}
static void ext4_xattr_block_csum_set(struct inode *inode,
struct buffer_head *bh)
{
if (ext4_has_metadata_csum(inode->i_sb))
BHDR(bh)->h_checksum = ext4_xattr_block_csum(inode,
bh->b_blocknr, BHDR(bh));
}
static inline const char *ext4_xattr_prefix(int name_index,
struct dentry *dentry)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(ext4_xattr_handler_map))
handler = ext4_xattr_handler_map[name_index];
if (!xattr_handler_can_list(handler, dentry))
return NULL;
return xattr_prefix(handler);
}
static int
check_xattrs(struct inode *inode, struct buffer_head *bh,
struct ext4_xattr_entry *entry, void *end, void *value_start,
const char *function, unsigned int line)
{
struct ext4_xattr_entry *e = entry;
int err = -EFSCORRUPTED;
char *err_str;
if (bh) {
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
err_str = "invalid header";
goto errout;
}
if (buffer_verified(bh))
return 0;
if (!ext4_xattr_block_csum_verify(inode, bh)) {
err = -EFSBADCRC;
err_str = "invalid checksum";
goto errout;
}
} else {
struct ext4_xattr_ibody_header *header = value_start;
header -= 1;
if (end - (void *)header < sizeof(*header) + sizeof(u32)) {
err_str = "in-inode xattr block too small";
goto errout;
}
if (header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
err_str = "bad magic number in in-inode xattr";
goto errout;
}
}
/* Find the end of the names list */
while (!IS_LAST_ENTRY(e)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(e);
if ((void *)next >= end) {
err_str = "e_name out of bounds";
goto errout;
}
if (strnlen(e->e_name, e->e_name_len) != e->e_name_len) {
err_str = "bad e_name length";
goto errout;
}
e = next;
}
/* Check the values */
while (!IS_LAST_ENTRY(entry)) {
u32 size = le32_to_cpu(entry->e_value_size);
unsigned long ea_ino = le32_to_cpu(entry->e_value_inum);
if (!ext4_has_feature_ea_inode(inode->i_sb) && ea_ino) {
err_str = "ea_inode specified without ea_inode feature enabled";
goto errout;
}
if (ea_ino && ((ea_ino == EXT4_ROOT_INO) ||
!ext4_valid_inum(inode->i_sb, ea_ino))) {
err_str = "invalid ea_ino";
goto errout;
}
if (size > EXT4_XATTR_SIZE_MAX) {
err_str = "e_value size too large";
goto errout;
}
if (size != 0 && entry->e_value_inum == 0) {
u16 offs = le16_to_cpu(entry->e_value_offs);
void *value;
/*
* The value cannot overlap the names, and the value
* with padding cannot extend beyond 'end'. Check both
* the padded and unpadded sizes, since the size may
* overflow to 0 when adding padding.
*/
if (offs > end - value_start) {
err_str = "e_value out of bounds";
goto errout;
}
value = value_start + offs;
if (value < (void *)e + sizeof(u32) ||
size > end - value ||
EXT4_XATTR_SIZE(size) > end - value) {
err_str = "overlapping e_value ";
goto errout;
}
}
entry = EXT4_XATTR_NEXT(entry);
}
if (bh)
set_buffer_verified(bh);
return 0;
errout:
if (bh)
__ext4_error_inode(inode, function, line, 0, -err,
"corrupted xattr block %llu: %s",
(unsigned long long) bh->b_blocknr,
err_str);
else
__ext4_error_inode(inode, function, line, 0, -err,
"corrupted in-inode xattr: %s", err_str);
return err;
}
static inline int
__ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh,
const char *function, unsigned int line)
{
return check_xattrs(inode, bh, BFIRST(bh), bh->b_data + bh->b_size,
bh->b_data, function, line);
}
#define ext4_xattr_check_block(inode, bh) \
__ext4_xattr_check_block((inode), (bh), __func__, __LINE__)
static inline int
__xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header,
void *end, const char *function, unsigned int line)
{
return check_xattrs(inode, NULL, IFIRST(header), end, IFIRST(header),
function, line);
}
#define xattr_check_inode(inode, header, end) \
__xattr_check_inode((inode), (header), (end), __func__, __LINE__)
static int
xattr_find_entry(struct inode *inode, struct ext4_xattr_entry **pentry,
void *end, int name_index, const char *name, int sorted)
{
struct ext4_xattr_entry *entry, *next;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
for (entry = *pentry; !IS_LAST_ENTRY(entry); entry = next) {
next = EXT4_XATTR_NEXT(entry);
if ((void *) next >= end) {
EXT4_ERROR_INODE(inode, "corrupted xattr entries");
return -EFSCORRUPTED;
}
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
return cmp ? -ENODATA : 0;
}
static u32
ext4_xattr_inode_hash(struct ext4_sb_info *sbi, const void *buffer, size_t size)
{
return ext4_chksum(sbi, sbi->s_csum_seed, buffer, size);
}
static u64 ext4_xattr_inode_get_ref(struct inode *ea_inode)
{
return ((u64) inode_get_ctime(ea_inode).tv_sec << 32) |
(u32) inode_peek_iversion_raw(ea_inode);
}
static void ext4_xattr_inode_set_ref(struct inode *ea_inode, u64 ref_count)
{
inode_set_ctime(ea_inode, (u32)(ref_count >> 32), 0);
inode_set_iversion_raw(ea_inode, ref_count & 0xffffffff);
}
static u32 ext4_xattr_inode_get_hash(struct inode *ea_inode)
{
return (u32)ea_inode->i_atime.tv_sec;
}
static void ext4_xattr_inode_set_hash(struct inode *ea_inode, u32 hash)
{
ea_inode->i_atime.tv_sec = hash;
}
/*
* Read the EA value from an inode.
*/
static int ext4_xattr_inode_read(struct inode *ea_inode, void *buf, size_t size)
{
int blocksize = 1 << ea_inode->i_blkbits;
int bh_count = (size + blocksize - 1) >> ea_inode->i_blkbits;
int tail_size = (size % blocksize) ?: blocksize;
struct buffer_head *bhs_inline[8];
struct buffer_head **bhs = bhs_inline;
int i, ret;
if (bh_count > ARRAY_SIZE(bhs_inline)) {
bhs = kmalloc_array(bh_count, sizeof(*bhs), GFP_NOFS);
if (!bhs)
return -ENOMEM;
}
ret = ext4_bread_batch(ea_inode, 0 /* block */, bh_count,
true /* wait */, bhs);
if (ret)
goto free_bhs;
for (i = 0; i < bh_count; i++) {
/* There shouldn't be any holes in ea_inode. */
if (!bhs[i]) {
ret = -EFSCORRUPTED;
goto put_bhs;
}
memcpy((char *)buf + blocksize * i, bhs[i]->b_data,
i < bh_count - 1 ? blocksize : tail_size);
}
ret = 0;
put_bhs:
for (i = 0; i < bh_count; i++)
brelse(bhs[i]);
free_bhs:
if (bhs != bhs_inline)
kfree(bhs);
return ret;
}
#define EXT4_XATTR_INODE_GET_PARENT(inode) ((__u32)(inode)->i_mtime.tv_sec)
static int ext4_xattr_inode_iget(struct inode *parent, unsigned long ea_ino,
u32 ea_inode_hash, struct inode **ea_inode)
{
struct inode *inode;
int err;
/*
* We have to check for this corruption early as otherwise
* iget_locked() could wait indefinitely for the state of our
* parent inode.
*/
if (parent->i_ino == ea_ino) {
ext4_error(parent->i_sb,
"Parent and EA inode have the same ino %lu", ea_ino);
return -EFSCORRUPTED;
}
inode = ext4_iget(parent->i_sb, ea_ino, EXT4_IGET_EA_INODE);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ext4_error(parent->i_sb,
"error while reading EA inode %lu err=%d", ea_ino,
err);
return err;
}
ext4_xattr_inode_set_class(inode);
/*
* Check whether this is an old Lustre-style xattr inode. Lustre
* implementation does not have hash validation, rather it has a
* backpointer from ea_inode to the parent inode.
*/
if (ea_inode_hash != ext4_xattr_inode_get_hash(inode) &&
EXT4_XATTR_INODE_GET_PARENT(inode) == parent->i_ino &&
inode->i_generation == parent->i_generation) {
ext4_set_inode_state(inode, EXT4_STATE_LUSTRE_EA_INODE);
ext4_xattr_inode_set_ref(inode, 1);
} else {
inode_lock(inode);
inode->i_flags |= S_NOQUOTA;
inode_unlock(inode);
}
*ea_inode = inode;
return 0;
}
/* Remove entry from mbcache when EA inode is getting evicted */
void ext4_evict_ea_inode(struct inode *inode)
{
struct mb_cache_entry *oe;
if (!EA_INODE_CACHE(inode))
return;
/* Wait for entry to get unused so that we can remove it */
while ((oe = mb_cache_entry_delete_or_get(EA_INODE_CACHE(inode),
ext4_xattr_inode_get_hash(inode), inode->i_ino))) {
mb_cache_entry_wait_unused(oe);
mb_cache_entry_put(EA_INODE_CACHE(inode), oe);
}
}
static int
ext4_xattr_inode_verify_hashes(struct inode *ea_inode,
struct ext4_xattr_entry *entry, void *buffer,
size_t size)
{
u32 hash;
/* Verify stored hash matches calculated hash. */
hash = ext4_xattr_inode_hash(EXT4_SB(ea_inode->i_sb), buffer, size);
if (hash != ext4_xattr_inode_get_hash(ea_inode))
return -EFSCORRUPTED;
if (entry) {
__le32 e_hash, tmp_data;
/* Verify entry hash. */
tmp_data = cpu_to_le32(hash);
e_hash = ext4_xattr_hash_entry(entry->e_name, entry->e_name_len,
&tmp_data, 1);
/* All good? */
if (e_hash == entry->e_hash)
return 0;
/*
* Not good. Maybe the entry hash was calculated
* using the buggy signed char version?
*/
e_hash = ext4_xattr_hash_entry_signed(entry->e_name, entry->e_name_len,
&tmp_data, 1);
/* Still no match - bad */
if (e_hash != entry->e_hash)
return -EFSCORRUPTED;
/* Let people know about old hash */
pr_warn_once("ext4: filesystem with signed xattr name hash");
}
return 0;
}
/*
* Read xattr value from the EA inode.
*/
static int
ext4_xattr_inode_get(struct inode *inode, struct ext4_xattr_entry *entry,
void *buffer, size_t size)
{
struct mb_cache *ea_inode_cache = EA_INODE_CACHE(inode);
struct inode *ea_inode;
int err;
err = ext4_xattr_inode_iget(inode, le32_to_cpu(entry->e_value_inum),
le32_to_cpu(entry->e_hash), &ea_inode);
if (err) {
ea_inode = NULL;
goto out;
}
if (i_size_read(ea_inode) != size) {
ext4_warning_inode(ea_inode,
"ea_inode file size=%llu entry size=%zu",
i_size_read(ea_inode), size);
err = -EFSCORRUPTED;
goto out;
}
err = ext4_xattr_inode_read(ea_inode, buffer, size);
if (err)
goto out;
if (!ext4_test_inode_state(ea_inode, EXT4_STATE_LUSTRE_EA_INODE)) {
err = ext4_xattr_inode_verify_hashes(ea_inode, entry, buffer,
size);
if (err) {
ext4_warning_inode(ea_inode,
"EA inode hash validation failed");
goto out;
}
if (ea_inode_cache)
mb_cache_entry_create(ea_inode_cache, GFP_NOFS,
ext4_xattr_inode_get_hash(ea_inode),
ea_inode->i_ino, true /* reusable */);
}
out:
iput(ea_inode);
return err;
}
static int
ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
void *end;
int error;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
if (!EXT4_I(inode)->i_file_acl)
return -ENODATA;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh))
return PTR_ERR(bh);
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
error = ext4_xattr_check_block(inode, bh);
if (error)
goto cleanup;
ext4_xattr_block_cache_insert(ea_block_cache, bh);
entry = BFIRST(bh);
end = bh->b_data + bh->b_size;
error = xattr_find_entry(inode, &entry, end, name_index, name, 1);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
error = -ERANGE;
if (unlikely(size > EXT4_XATTR_SIZE_MAX))
goto cleanup;
if (buffer) {
if (size > buffer_size)
goto cleanup;
if (entry->e_value_inum) {
error = ext4_xattr_inode_get(inode, entry, buffer,
size);
if (error)
goto cleanup;
} else {
u16 offset = le16_to_cpu(entry->e_value_offs);
void *p = bh->b_data + offset;
if (unlikely(p + size > end))
goto cleanup;
memcpy(buffer, p, size);
}
}
error = size;
cleanup:
brelse(bh);
return error;
}
int
ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = xattr_check_inode(inode, header, end);
if (error)
goto cleanup;
entry = IFIRST(header);
error = xattr_find_entry(inode, &entry, end, name_index, name, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
error = -ERANGE;
if (unlikely(size > EXT4_XATTR_SIZE_MAX))
goto cleanup;
if (buffer) {
if (size > buffer_size)
goto cleanup;
if (entry->e_value_inum) {
error = ext4_xattr_inode_get(inode, entry, buffer,
size);
if (error)
goto cleanup;
} else {
u16 offset = le16_to_cpu(entry->e_value_offs);
void *p = (void *)IFIRST(header) + offset;
if (unlikely(p + size > end))
goto cleanup;
memcpy(buffer, p, size);
}
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
if (strlen(name) > 255)
return -ERANGE;
down_read(&EXT4_I(inode)->xattr_sem);
error = ext4_xattr_ibody_get(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = ext4_xattr_block_get(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
const char *prefix;
prefix = ext4_xattr_prefix(entry->e_name_index, dentry);
if (prefix) {
size_t prefix_len = strlen(prefix);
size_t size = prefix_len + entry->e_name_len + 1;
if (buffer) {
if (size > rest)
return -ERANGE;
memcpy(buffer, prefix, prefix_len);
buffer += prefix_len;
memcpy(buffer, entry->e_name, entry->e_name_len);
buffer += entry->e_name_len;
*buffer++ = 0;
}
rest -= size;
}
}
return buffer_size - rest; /* total size */
}
static int
ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
if (!EXT4_I(inode)->i_file_acl)
return 0;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh))
return PTR_ERR(bh);
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
error = ext4_xattr_check_block(inode, bh);
if (error)
goto cleanup;
ext4_xattr_block_cache_insert(EA_BLOCK_CACHE(inode), bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer,
buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = xattr_check_inode(inode, header, end);
if (error)
goto cleanup;
error = ext4_xattr_list_entries(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* Inode operation listxattr()
*
* d_inode(dentry)->i_rwsem: don't care
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int ret, ret2;
down_read(&EXT4_I(d_inode(dentry))->xattr_sem);
ret = ret2 = ext4_xattr_ibody_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = ext4_xattr_block_list(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
ret += ret2;
errout:
up_read(&EXT4_I(d_inode(dentry))->xattr_sem);
return ret;
}
/*
* If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
* not set, set it.
*/
static void ext4_xattr_update_super_block(handle_t *handle,
struct super_block *sb)
{
if (ext4_has_feature_xattr(sb))
return;
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
if (ext4_journal_get_write_access(handle, sb, EXT4_SB(sb)->s_sbh,
EXT4_JTR_NONE) == 0) {
lock_buffer(EXT4_SB(sb)->s_sbh);
ext4_set_feature_xattr(sb);
ext4_superblock_csum_set(sb);
unlock_buffer(EXT4_SB(sb)->s_sbh);
ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
}
}
int ext4_get_inode_usage(struct inode *inode, qsize_t *usage)
{
struct ext4_iloc iloc = { .bh = NULL };
struct buffer_head *bh = NULL;
struct ext4_inode *raw_inode;
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
qsize_t ea_inode_refs = 0;
void *end;
int ret;
lockdep_assert_held_read(&EXT4_I(inode)->xattr_sem);
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
goto out;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
ret = xattr_check_inode(inode, header, end);
if (ret)
goto out;
for (entry = IFIRST(header); !IS_LAST_ENTRY(entry);
entry = EXT4_XATTR_NEXT(entry))
if (entry->e_value_inum)
ea_inode_refs++;
}
if (EXT4_I(inode)->i_file_acl) {
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh)) {
ret = PTR_ERR(bh);
bh = NULL;
goto out;
}
ret = ext4_xattr_check_block(inode, bh);
if (ret)
goto out;
for (entry = BFIRST(bh); !IS_LAST_ENTRY(entry);
entry = EXT4_XATTR_NEXT(entry))
if (entry->e_value_inum)
ea_inode_refs++;
}
*usage = ea_inode_refs + 1;
ret = 0;
out:
brelse(iloc.bh);
brelse(bh);
return ret;
}
static inline size_t round_up_cluster(struct inode *inode, size_t length)
{
struct super_block *sb = inode->i_sb;
size_t cluster_size = 1 << (EXT4_SB(sb)->s_cluster_bits +
inode->i_blkbits);
size_t mask = ~(cluster_size - 1);
return (length + cluster_size - 1) & mask;
}
static int ext4_xattr_inode_alloc_quota(struct inode *inode, size_t len)
{
int err;
err = dquot_alloc_inode(inode);
if (err)
return err;
err = dquot_alloc_space_nodirty(inode, round_up_cluster(inode, len));
if (err)
dquot_free_inode(inode);
return err;
}
static void ext4_xattr_inode_free_quota(struct inode *parent,
struct inode *ea_inode,
size_t len)
{
if (ea_inode &&
ext4_test_inode_state(ea_inode, EXT4_STATE_LUSTRE_EA_INODE))
return;
dquot_free_space_nodirty(parent, round_up_cluster(parent, len));
dquot_free_inode(parent);
}
int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
struct buffer_head *block_bh, size_t value_len,
bool is_create)
{
int credits;
int blocks;
/*
* 1) Owner inode update
* 2) Ref count update on old xattr block
* 3) new xattr block
* 4) block bitmap update for new xattr block
* 5) group descriptor for new xattr block
* 6) block bitmap update for old xattr block
* 7) group descriptor for old block
*
* 6 & 7 can happen if we have two racing threads T_a and T_b
* which are each trying to set an xattr on inodes I_a and I_b
* which were both initially sharing an xattr block.
*/
credits = 7;
/* Quota updates. */
credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(sb);
/*
* In case of inline data, we may push out the data to a block,
* so we need to reserve credits for this eventuality
*/
if (inode && ext4_has_inline_data(inode))
credits += ext4_writepage_trans_blocks(inode) + 1;
/* We are done if ea_inode feature is not enabled. */
if (!ext4_has_feature_ea_inode(sb))
return credits;
/* New ea_inode, inode map, block bitmap, group descriptor. */
credits += 4;
/* Data blocks. */
blocks = (value_len + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
/* Indirection block or one level of extent tree. */
blocks += 1;
/* Block bitmap and group descriptor updates for each block. */
credits += blocks * 2;
/* Blocks themselves. */
credits += blocks;
if (!is_create) {
/* Dereference ea_inode holding old xattr value.
* Old ea_inode, inode map, block bitmap, group descriptor.
*/
credits += 4;
/* Data blocks for old ea_inode. */
blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
/* Indirection block or one level of extent tree for old
* ea_inode.
*/
blocks += 1;
/* Block bitmap and group descriptor updates for each block. */
credits += blocks * 2;
}
/* We may need to clone the existing xattr block in which case we need
* to increment ref counts for existing ea_inodes referenced by it.
*/
if (block_bh) {
struct ext4_xattr_entry *entry = BFIRST(block_bh);
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry))
if (entry->e_value_inum)
/* Ref count update on ea_inode. */
credits += 1;
}
return credits;
}
static int ext4_xattr_inode_update_ref(handle_t *handle, struct inode *ea_inode,
int ref_change)
{
struct ext4_iloc iloc;
s64 ref_count;
int ret;
inode_lock(ea_inode);
ret = ext4_reserve_inode_write(handle, ea_inode, &iloc);
if (ret)
goto out;
ref_count = ext4_xattr_inode_get_ref(ea_inode);
ref_count += ref_change;
ext4_xattr_inode_set_ref(ea_inode, ref_count);
if (ref_change > 0) {
WARN_ONCE(ref_count <= 0, "EA inode %lu ref_count=%lld",
ea_inode->i_ino, ref_count);
if (ref_count == 1) {
WARN_ONCE(ea_inode->i_nlink, "EA inode %lu i_nlink=%u",
ea_inode->i_ino, ea_inode->i_nlink);
set_nlink(ea_inode, 1);
ext4_orphan_del(handle, ea_inode);
}
} else {
WARN_ONCE(ref_count < 0, "EA inode %lu ref_count=%lld",
ea_inode->i_ino, ref_count);
if (ref_count == 0) {
WARN_ONCE(ea_inode->i_nlink != 1,
"EA inode %lu i_nlink=%u",
ea_inode->i_ino, ea_inode->i_nlink);
clear_nlink(ea_inode);
ext4_orphan_add(handle, ea_inode);
}
}
ret = ext4_mark_iloc_dirty(handle, ea_inode, &iloc);
if (ret)
ext4_warning_inode(ea_inode,
"ext4_mark_iloc_dirty() failed ret=%d", ret);
out:
inode_unlock(ea_inode);
return ret;
}
static int ext4_xattr_inode_inc_ref(handle_t *handle, struct inode *ea_inode)
{
return ext4_xattr_inode_update_ref(handle, ea_inode, 1);
}
static int ext4_xattr_inode_dec_ref(handle_t *handle, struct inode *ea_inode)
{
return ext4_xattr_inode_update_ref(handle, ea_inode, -1);
}
static int ext4_xattr_inode_inc_ref_all(handle_t *handle, struct inode *parent,
struct ext4_xattr_entry *first)
{
struct inode *ea_inode;
struct ext4_xattr_entry *entry;
struct ext4_xattr_entry *failed_entry;
unsigned int ea_ino;
int err, saved_err;
for (entry = first; !IS_LAST_ENTRY(entry);
entry = EXT4_XATTR_NEXT(entry)) {
if (!entry->e_value_inum)
continue;
ea_ino = le32_to_cpu(entry->e_value_inum);
err = ext4_xattr_inode_iget(parent, ea_ino,
le32_to_cpu(entry->e_hash),
&ea_inode);
if (err)
goto cleanup;
err = ext4_xattr_inode_inc_ref(handle, ea_inode);
if (err) {
ext4_warning_inode(ea_inode, "inc ref error %d", err);
iput(ea_inode);
goto cleanup;
}
iput(ea_inode);
}
return 0;
cleanup:
saved_err = err;
failed_entry = entry;
for (entry = first; entry != failed_entry;
entry = EXT4_XATTR_NEXT(entry)) {
if (!entry->e_value_inum)
continue;
ea_ino = le32_to_cpu(entry->e_value_inum);
err = ext4_xattr_inode_iget(parent, ea_ino,
le32_to_cpu(entry->e_hash),
&ea_inode);
if (err) {
ext4_warning(parent->i_sb,
"cleanup ea_ino %u iget error %d", ea_ino,
err);
continue;
}
err = ext4_xattr_inode_dec_ref(handle, ea_inode);
if (err)
ext4_warning_inode(ea_inode, "cleanup dec ref error %d",
err);
iput(ea_inode);
}
return saved_err;
}
static int ext4_xattr_restart_fn(handle_t *handle, struct inode *inode,
struct buffer_head *bh, bool block_csum, bool dirty)
{
int error;
if (bh && dirty) {
if (block_csum)
ext4_xattr_block_csum_set(inode, bh);
error = ext4_handle_dirty_metadata(handle, NULL, bh);
if (error) {
ext4_warning(inode->i_sb, "Handle metadata (error %d)",
error);
return error;
}
}
return 0;
}
static void
ext4_xattr_inode_dec_ref_all(handle_t *handle, struct inode *parent,
struct buffer_head *bh,
struct ext4_xattr_entry *first, bool block_csum,
struct ext4_xattr_inode_array **ea_inode_array,
int extra_credits, bool skip_quota)
{
struct inode *ea_inode;
struct ext4_xattr_entry *entry;
bool dirty = false;
unsigned int ea_ino;
int err;
int credits;
/* One credit for dec ref on ea_inode, one for orphan list addition, */
credits = 2 + extra_credits;
for (entry = first; !IS_LAST_ENTRY(entry);
entry = EXT4_XATTR_NEXT(entry)) {
if (!entry->e_value_inum)
continue;
ea_ino = le32_to_cpu(entry->e_value_inum);
err = ext4_xattr_inode_iget(parent, ea_ino,
le32_to_cpu(entry->e_hash),
&ea_inode);
if (err)
continue;
err = ext4_expand_inode_array(ea_inode_array, ea_inode);
if (err) {
ext4_warning_inode(ea_inode,
"Expand inode array err=%d", err);
iput(ea_inode);
continue;
}
err = ext4_journal_ensure_credits_fn(handle, credits, credits,
ext4_free_metadata_revoke_credits(parent->i_sb, 1),
ext4_xattr_restart_fn(handle, parent, bh, block_csum,
dirty));
if (err < 0) {
ext4_warning_inode(ea_inode, "Ensure credits err=%d",
err);
continue;
}
if (err > 0) {
err = ext4_journal_get_write_access(handle,
parent->i_sb, bh, EXT4_JTR_NONE);
if (err) {
ext4_warning_inode(ea_inode,
"Re-get write access err=%d",
err);
continue;
}
}
err = ext4_xattr_inode_dec_ref(handle, ea_inode);
if (err) {
ext4_warning_inode(ea_inode, "ea_inode dec ref err=%d",
err);
continue;
}
if (!skip_quota)
ext4_xattr_inode_free_quota(parent, ea_inode,
le32_to_cpu(entry->e_value_size));
/*
* Forget about ea_inode within the same transaction that
* decrements the ref count. This avoids duplicate decrements in
* case the rest of the work spills over to subsequent
* transactions.
*/
entry->e_value_inum = 0;
entry->e_value_size = 0;
dirty = true;
}
if (dirty) {
/*
* Note that we are deliberately skipping csum calculation for
* the final update because we do not expect any journal
* restarts until xattr block is freed.
*/
err = ext4_handle_dirty_metadata(handle, NULL, bh);
if (err)
ext4_warning_inode(parent,
"handle dirty metadata err=%d", err);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement it;
* otherwise free the block.
*/
static void
ext4_xattr_release_block(handle_t *handle, struct inode *inode,
struct buffer_head *bh,
struct ext4_xattr_inode_array **ea_inode_array,
int extra_credits)
{
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
u32 hash, ref;
int error = 0;
BUFFER_TRACE(bh, "get_write_access");
error = ext4_journal_get_write_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (error)
goto out;
retry_ref:
lock_buffer(bh);
hash = le32_to_cpu(BHDR(bh)->h_hash);
ref = le32_to_cpu(BHDR(bh)->h_refcount);
if (ref == 1) {
ea_bdebug(bh, "refcount now=0; freeing");
/*
* This must happen under buffer lock for
* ext4_xattr_block_set() to reliably detect freed block
*/
if (ea_block_cache) {
struct mb_cache_entry *oe;
oe = mb_cache_entry_delete_or_get(ea_block_cache, hash,
bh->b_blocknr);
if (oe) {
unlock_buffer(bh);
mb_cache_entry_wait_unused(oe);
mb_cache_entry_put(ea_block_cache, oe);
goto retry_ref;
}
}
get_bh(bh);
unlock_buffer(bh);
if (ext4_has_feature_ea_inode(inode->i_sb))
ext4_xattr_inode_dec_ref_all(handle, inode, bh,
BFIRST(bh),
true /* block_csum */,
ea_inode_array,
extra_credits,
true /* skip_quota */);
ext4_free_blocks(handle, inode, bh, 0, 1,
EXT4_FREE_BLOCKS_METADATA |
EXT4_FREE_BLOCKS_FORGET);
} else {
ref--;
BHDR(bh)->h_refcount = cpu_to_le32(ref);
if (ref == EXT4_XATTR_REFCOUNT_MAX - 1) {
struct mb_cache_entry *ce;
if (ea_block_cache) {
ce = mb_cache_entry_get(ea_block_cache, hash,
bh->b_blocknr);
if (ce) {
set_bit(MBE_REUSABLE_B, &ce->e_flags);
mb_cache_entry_put(ea_block_cache, ce);
}
}
}
ext4_xattr_block_csum_set(inode, bh);
/*
* Beware of this ugliness: Releasing of xattr block references
* from different inodes can race and so we have to protect
* from a race where someone else frees the block (and releases
* its journal_head) before we are done dirtying the buffer. In
* nojournal mode this race is harmless and we actually cannot
* call ext4_handle_dirty_metadata() with locked buffer as
* that function can call sync_dirty_buffer() so for that case
* we handle the dirtying after unlocking the buffer.
*/
if (ext4_handle_valid(handle))
error = ext4_handle_dirty_metadata(handle, inode, bh);
unlock_buffer(bh);
if (!ext4_handle_valid(handle))
error = ext4_handle_dirty_metadata(handle, inode, bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
}
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t ext4_xattr_free_space(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_inum && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < *min_offs)
*min_offs = offs;
}
if (total)
*total += EXT4_XATTR_LEN(last->e_name_len);
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
/*
* Write the value of the EA in an inode.
*/
static int ext4_xattr_inode_write(handle_t *handle, struct inode *ea_inode,
const void *buf, int bufsize)
{
struct buffer_head *bh = NULL;
unsigned long block = 0;
int blocksize = ea_inode->i_sb->s_blocksize;
int max_blocks = (bufsize + blocksize - 1) >> ea_inode->i_blkbits;
int csize, wsize = 0;
int ret = 0, ret2 = 0;
int retries = 0;
retry:
while (ret >= 0 && ret < max_blocks) {
struct ext4_map_blocks map;
map.m_lblk = block += ret;
map.m_len = max_blocks -= ret;
ret = ext4_map_blocks(handle, ea_inode, &map,
EXT4_GET_BLOCKS_CREATE);
if (ret <= 0) {
ext4_mark_inode_dirty(handle, ea_inode);
if (ret == -ENOSPC &&
ext4_should_retry_alloc(ea_inode->i_sb, &retries)) {
ret = 0;
goto retry;
}
break;
}
}
if (ret < 0)
return ret;
block = 0;
while (wsize < bufsize) {
brelse(bh);
csize = (bufsize - wsize) > blocksize ? blocksize :
bufsize - wsize;
bh = ext4_getblk(handle, ea_inode, block, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) {
WARN_ON_ONCE(1);
EXT4_ERROR_INODE(ea_inode,
"ext4_getblk() return bh = NULL");
return -EFSCORRUPTED;
}
ret = ext4_journal_get_write_access(handle, ea_inode->i_sb, bh,
EXT4_JTR_NONE);
if (ret)
goto out;
memcpy(bh->b_data, buf, csize);
set_buffer_uptodate(bh);
ext4_handle_dirty_metadata(handle, ea_inode, bh);
buf += csize;
wsize += csize;
block += 1;
}
inode_lock(ea_inode);
i_size_write(ea_inode, wsize);
ext4_update_i_disksize(ea_inode, wsize);
inode_unlock(ea_inode);
ret2 = ext4_mark_inode_dirty(handle, ea_inode);
if (unlikely(ret2 && !ret))
ret = ret2;
out:
brelse(bh);
return ret;
}
/*
* Create an inode to store the value of a large EA.
*/
static struct inode *ext4_xattr_inode_create(handle_t *handle,
struct inode *inode, u32 hash)
{
struct inode *ea_inode = NULL;
uid_t owner[2] = { i_uid_read(inode), i_gid_read(inode) };
int err;
if (inode->i_sb->s_root == NULL) {
ext4_warning(inode->i_sb,
"refuse to create EA inode when umounting");
WARN_ON(1);
return ERR_PTR(-EINVAL);
}
/*
* Let the next inode be the goal, so we try and allocate the EA inode
* in the same group, or nearby one.
*/
ea_inode = ext4_new_inode(handle, inode->i_sb->s_root->d_inode,
S_IFREG | 0600, NULL, inode->i_ino + 1, owner,
EXT4_EA_INODE_FL);
if (!IS_ERR(ea_inode)) {
ea_inode->i_op = &ext4_file_inode_operations;
ea_inode->i_fop = &ext4_file_operations;
ext4_set_aops(ea_inode);
ext4_xattr_inode_set_class(ea_inode);
unlock_new_inode(ea_inode);
ext4_xattr_inode_set_ref(ea_inode, 1);
ext4_xattr_inode_set_hash(ea_inode, hash);
err = ext4_mark_inode_dirty(handle, ea_inode);
if (!err)
err = ext4_inode_attach_jinode(ea_inode);
if (err) {
if (ext4_xattr_inode_dec_ref(handle, ea_inode))
ext4_warning_inode(ea_inode,
"cleanup dec ref error %d", err);
iput(ea_inode);
return ERR_PTR(err);
}
/*
* Xattr inodes are shared therefore quota charging is performed
* at a higher level.
*/
dquot_free_inode(ea_inode);
dquot_drop(ea_inode);
inode_lock(ea_inode);
ea_inode->i_flags |= S_NOQUOTA;
inode_unlock(ea_inode);
}
return ea_inode;
}
static struct inode *
ext4_xattr_inode_cache_find(struct inode *inode, const void *value,
size_t value_len, u32 hash)
{
struct inode *ea_inode;
struct mb_cache_entry *ce;
struct mb_cache *ea_inode_cache = EA_INODE_CACHE(inode);
void *ea_data;
if (!ea_inode_cache)
return NULL;
ce = mb_cache_entry_find_first(ea_inode_cache, hash);
if (!ce)
return NULL;
WARN_ON_ONCE(ext4_handle_valid(journal_current_handle()) &&
!(current->flags & PF_MEMALLOC_NOFS));
ea_data = kvmalloc(value_len, GFP_KERNEL);
if (!ea_data) {
mb_cache_entry_put(ea_inode_cache, ce);
return NULL;
}
while (ce) {
ea_inode = ext4_iget(inode->i_sb, ce->e_value,
EXT4_IGET_EA_INODE);
if (IS_ERR(ea_inode))
goto next_entry;
ext4_xattr_inode_set_class(ea_inode);
if (i_size_read(ea_inode) == value_len &&
!ext4_xattr_inode_read(ea_inode, ea_data, value_len) &&
!ext4_xattr_inode_verify_hashes(ea_inode, NULL, ea_data,
value_len) &&
!memcmp(value, ea_data, value_len)) {
mb_cache_entry_touch(ea_inode_cache, ce);
mb_cache_entry_put(ea_inode_cache, ce);
kvfree(ea_data);
return ea_inode;
}
iput(ea_inode);
next_entry:
ce = mb_cache_entry_find_next(ea_inode_cache, ce);
}
kvfree(ea_data);
return NULL;
}
/*
* Add value of the EA in an inode.
*/
static int ext4_xattr_inode_lookup_create(handle_t *handle, struct inode *inode,
const void *value, size_t value_len,
struct inode **ret_inode)
{
struct inode *ea_inode;
u32 hash;
int err;
hash = ext4_xattr_inode_hash(EXT4_SB(inode->i_sb), value, value_len);
ea_inode = ext4_xattr_inode_cache_find(inode, value, value_len, hash);
if (ea_inode) {
err = ext4_xattr_inode_inc_ref(handle, ea_inode);
if (err) {
iput(ea_inode);
return err;
}
*ret_inode = ea_inode;
return 0;
}
/* Create an inode for the EA value */
ea_inode = ext4_xattr_inode_create(handle, inode, hash);
if (IS_ERR(ea_inode))
return PTR_ERR(ea_inode);
err = ext4_xattr_inode_write(handle, ea_inode, value, value_len);
if (err) {
if (ext4_xattr_inode_dec_ref(handle, ea_inode))
ext4_warning_inode(ea_inode, "cleanup dec ref error %d", err);
iput(ea_inode);
return err;
}
if (EA_INODE_CACHE(inode))
mb_cache_entry_create(EA_INODE_CACHE(inode), GFP_NOFS, hash,
ea_inode->i_ino, true /* reusable */);
*ret_inode = ea_inode;
return 0;
}
/*
* Reserve min(block_size/8, 1024) bytes for xattr entries/names if ea_inode
* feature is enabled.
*/
#define EXT4_XATTR_BLOCK_RESERVE(inode) min(i_blocksize(inode)/8, 1024U)
static int ext4_xattr_set_entry(struct ext4_xattr_info *i,
struct ext4_xattr_search *s,
handle_t *handle, struct inode *inode,
bool is_block)
{
struct ext4_xattr_entry *last, *next;
struct ext4_xattr_entry *here = s->here;
size_t min_offs = s->end - s->base, name_len = strlen(i->name);
int in_inode = i->in_inode;
struct inode *old_ea_inode = NULL;
struct inode *new_ea_inode = NULL;
size_t old_size, new_size;
int ret;
/* Space used by old and new values. */
old_size = (!s->not_found && !here->e_value_inum) ?
EXT4_XATTR_SIZE(le32_to_cpu(here->e_value_size)) : 0;
new_size = (i->value && !in_inode) ? EXT4_XATTR_SIZE(i->value_len) : 0;
/*
* Optimization for the simple case when old and new values have the
* same padded sizes. Not applicable if external inodes are involved.
*/
if (new_size && new_size == old_size) {
size_t offs = le16_to_cpu(here->e_value_offs);
void *val = s->base + offs;
here->e_value_size = cpu_to_le32(i->value_len);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, new_size);
} else {
memcpy(val, i->value, i->value_len);
/* Clear padding bytes. */
memset(val + i->value_len, 0, new_size - i->value_len);
}
goto update_hash;
}
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = next) {
next = EXT4_XATTR_NEXT(last);
if ((void *)next >= s->end) {
EXT4_ERROR_INODE(inode, "corrupted xattr entries");
ret = -EFSCORRUPTED;
goto out;
}
if (!last->e_value_inum && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
/* Check whether we have enough space. */
if (i->value) {
size_t free;
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found)
free += EXT4_XATTR_LEN(name_len) + old_size;
if (free < EXT4_XATTR_LEN(name_len) + new_size) {
ret = -ENOSPC;
goto out;
}
/*
* If storing the value in an external inode is an option,
* reserve space for xattr entries/names in the external
* attribute block so that a long value does not occupy the
* whole space and prevent further entries being added.
*/
if (ext4_has_feature_ea_inode(inode->i_sb) &&
new_size && is_block &&
(min_offs + old_size - new_size) <
EXT4_XATTR_BLOCK_RESERVE(inode)) {
ret = -ENOSPC;
goto out;
}
}
/*
* Getting access to old and new ea inodes is subject to failures.
* Finish that work before doing any modifications to the xattr data.
*/
if (!s->not_found && here->e_value_inum) {
ret = ext4_xattr_inode_iget(inode,
le32_to_cpu(here->e_value_inum),
le32_to_cpu(here->e_hash),
&old_ea_inode);
if (ret) {
old_ea_inode = NULL;
goto out;
}
}
if (i->value && in_inode) {
WARN_ON_ONCE(!i->value_len);
ret = ext4_xattr_inode_alloc_quota(inode, i->value_len);
if (ret)
goto out;
ret = ext4_xattr_inode_lookup_create(handle, inode, i->value,
i->value_len,
&new_ea_inode);
if (ret) {
new_ea_inode = NULL;
ext4_xattr_inode_free_quota(inode, NULL, i->value_len);
goto out;
}
}
if (old_ea_inode) {
/* We are ready to release ref count on the old_ea_inode. */
ret = ext4_xattr_inode_dec_ref(handle, old_ea_inode);
if (ret) {
/* Release newly required ref count on new_ea_inode. */
if (new_ea_inode) {
int err;
err = ext4_xattr_inode_dec_ref(handle,
new_ea_inode);
if (err)
ext4_warning_inode(new_ea_inode,
"dec ref new_ea_inode err=%d",
err);
ext4_xattr_inode_free_quota(inode, new_ea_inode,
i->value_len);
}
goto out;
}
ext4_xattr_inode_free_quota(inode, old_ea_inode,
le32_to_cpu(here->e_value_size));
}
/* No failures allowed past this point. */
if (!s->not_found && here->e_value_size && !here->e_value_inum) {
/* Remove the old value. */
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(here->e_value_offs);
void *val = s->base + offs;
memmove(first_val + old_size, first_val, val - first_val);
memset(first_val, 0, old_size);
min_offs += old_size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_inum &&
last->e_value_size && o < offs)
last->e_value_offs = cpu_to_le16(o + old_size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(here, (void *)here + size,
(void *)last - (void *)here + sizeof(__u32));
memset(last, 0, size);
/*
* Update i_inline_off - moved ibody region might contain
* system.data attribute. Handling a failure here won't
* cause other complications for setting an xattr.
*/
if (!is_block && ext4_has_inline_data(inode)) {
ret = ext4_find_inline_data_nolock(inode);
if (ret) {
ext4_warning_inode(inode,
"unable to update i_inline_off");
goto out;
}
}
} else if (s->not_found) {
/* Insert new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)here + sizeof(__u32);
memmove((void *)here + size, here, rest);
memset(here, 0, size);
here->e_name_index = i->name_index;
here->e_name_len = name_len;
memcpy(here->e_name, i->name, name_len);
} else {
/* This is an update, reset value info. */
here->e_value_inum = 0;
here->e_value_offs = 0;
here->e_value_size = 0;
}
if (i->value) {
/* Insert new value. */
if (in_inode) {
here->e_value_inum = cpu_to_le32(new_ea_inode->i_ino);
} else if (i->value_len) {
void *val = s->base + min_offs - new_size;
here->e_value_offs = cpu_to_le16(min_offs - new_size);
if (i->value == EXT4_ZERO_XATTR_VALUE) {
memset(val, 0, new_size);
} else {
memcpy(val, i->value, i->value_len);
/* Clear padding bytes. */
memset(val + i->value_len, 0,
new_size - i->value_len);
}
}
here->e_value_size = cpu_to_le32(i->value_len);
}
update_hash:
if (i->value) {
__le32 hash = 0;
/* Entry hash calculation. */
if (in_inode) {
__le32 crc32c_hash;
/*
* Feed crc32c hash instead of the raw value for entry
* hash calculation. This is to avoid walking
* potentially long value buffer again.
*/
crc32c_hash = cpu_to_le32(
ext4_xattr_inode_get_hash(new_ea_inode));
hash = ext4_xattr_hash_entry(here->e_name,
here->e_name_len,
&crc32c_hash, 1);
} else if (is_block) {
__le32 *value = s->base + le16_to_cpu(
here->e_value_offs);
hash = ext4_xattr_hash_entry(here->e_name,
here->e_name_len, value,
new_size >> 2);
}
here->e_hash = hash;
}
if (is_block)
ext4_xattr_rehash((struct ext4_xattr_header *)s->base);
ret = 0;
out:
iput(old_ea_inode);
iput(new_ea_inode);
return ret;
}
struct ext4_xattr_block_find {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
ext4_xattr_block_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = ext4_sb_bread(sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bs->bh)) {
error = PTR_ERR(bs->bh);
bs->bh = NULL;
return error;
}
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
error = ext4_xattr_check_block(inode, bs->bh);
if (error)
return error;
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = xattr_find_entry(inode, &bs->s.here, bs->s.end,
i->name_index, i->name, 1);
if (error && error != -ENODATA)
return error;
bs->s.not_found = error;
}
return 0;
}
static int
ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search s_copy = bs->s;
struct ext4_xattr_search *s = &s_copy;
struct mb_cache_entry *ce = NULL;
int error = 0;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
struct inode *ea_inode = NULL, *tmp_inode;
size_t old_ea_inode_quota = 0;
unsigned int ea_ino;
#define header(x) ((struct ext4_xattr_header *)(x))
if (s->base) {
int offset = (char *)s->here - bs->bh->b_data;
BUFFER_TRACE(bs->bh, "get_write_access");
error = ext4_journal_get_write_access(handle, sb, bs->bh,
EXT4_JTR_NONE);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
__u32 hash = le32_to_cpu(BHDR(bs->bh)->h_hash);
/*
* This must happen under buffer lock for
* ext4_xattr_block_set() to reliably detect modified
* block
*/
if (ea_block_cache) {
struct mb_cache_entry *oe;
oe = mb_cache_entry_delete_or_get(ea_block_cache,
hash, bs->bh->b_blocknr);
if (oe) {
/*
* Xattr block is getting reused. Leave
* it alone.
*/
mb_cache_entry_put(ea_block_cache, oe);
goto clone_block;
}
}
ea_bdebug(bs->bh, "modifying in-place");
error = ext4_xattr_set_entry(i, s, handle, inode,
true /* is_block */);
ext4_xattr_block_csum_set(inode, bs->bh);
unlock_buffer(bs->bh);
if (error == -EFSCORRUPTED)
goto bad_block;
if (!error)
error = ext4_handle_dirty_metadata(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
}
clone_block:
unlock_buffer(bs->bh);
ea_bdebug(bs->bh, "cloning");
s->base = kmemdup(BHDR(bs->bh), bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
/*
* If existing entry points to an xattr inode, we need
* to prevent ext4_xattr_set_entry() from decrementing
* ref count on it because the reference belongs to the
* original block. In this case, make the entry look
* like it has an empty value.
*/
if (!s->not_found && s->here->e_value_inum) {
ea_ino = le32_to_cpu(s->here->e_value_inum);
error = ext4_xattr_inode_iget(inode, ea_ino,
le32_to_cpu(s->here->e_hash),
&tmp_inode);
if (error)
goto cleanup;
if (!ext4_test_inode_state(tmp_inode,
EXT4_STATE_LUSTRE_EA_INODE)) {
/*
* Defer quota free call for previous
* inode until success is guaranteed.
*/
old_ea_inode_quota = le32_to_cpu(
s->here->e_value_size);
}
iput(tmp_inode);
s->here->e_value_inum = 0;
s->here->e_value_size = 0;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = ext4_xattr_set_entry(i, s, handle, inode, true /* is_block */);
if (error == -EFSCORRUPTED)
goto bad_block;
if (error)
goto cleanup;
if (i->value && s->here->e_value_inum) {
/*
* A ref count on ea_inode has been taken as part of the call to
* ext4_xattr_set_entry() above. We would like to drop this
* extra ref but we have to wait until the xattr block is
* initialized and has its own ref count on the ea_inode.
*/
ea_ino = le32_to_cpu(s->here->e_value_inum);
error = ext4_xattr_inode_iget(inode, ea_ino,
le32_to_cpu(s->here->e_hash),
&ea_inode);
if (error) {
ea_inode = NULL;
goto cleanup;
}
}
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext4_xattr_block_cache_find(inode, header(s->base),
&ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
u32 ref;
#ifdef EXT4_XATTR_DEBUG
WARN_ON_ONCE(dquot_initialize_needed(inode));
#endif
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode,
EXT4_C2B(EXT4_SB(sb), 1));
if (error)
goto cleanup;
BUFFER_TRACE(new_bh, "get_write_access");
error = ext4_journal_get_write_access(
handle, sb, new_bh,
EXT4_JTR_NONE);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
/*
* We have to be careful about races with
* adding references to xattr block. Once we
* hold buffer lock xattr block's state is
* stable so we can check the additional
* reference fits.
*/
ref = le32_to_cpu(BHDR(new_bh)->h_refcount) + 1;
if (ref > EXT4_XATTR_REFCOUNT_MAX) {
/*
* Undo everything and check mbcache
* again.
*/
unlock_buffer(new_bh);
dquot_free_block(inode,
EXT4_C2B(EXT4_SB(sb),
1));
brelse(new_bh);
mb_cache_entry_put(ea_block_cache, ce);
ce = NULL;
new_bh = NULL;
goto inserted;
}
BHDR(new_bh)->h_refcount = cpu_to_le32(ref);
if (ref == EXT4_XATTR_REFCOUNT_MAX)
clear_bit(MBE_REUSABLE_B, &ce->e_flags);
ea_bdebug(new_bh, "reusing; refcount now=%d",
ref);
ext4_xattr_block_csum_set(inode, new_bh);
unlock_buffer(new_bh);
error = ext4_handle_dirty_metadata(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_touch(ea_block_cache, ce);
mb_cache_entry_put(ea_block_cache, ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
ext4_xattr_block_cache_insert(ea_block_cache, bs->bh);
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
#ifdef EXT4_XATTR_DEBUG
WARN_ON_ONCE(dquot_initialize_needed(inode));
#endif
goal = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
block = ext4_new_meta_blocks(handle, inode, goal, 0,
NULL, &error);
if (error)
goto cleanup;
ea_idebug(inode, "creating block %llu",
(unsigned long long)block);
new_bh = sb_getblk(sb, block);
if (unlikely(!new_bh)) {
error = -ENOMEM;
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
EXT4_FREE_BLOCKS_METADATA);
goto cleanup;
}
error = ext4_xattr_inode_inc_ref_all(handle, inode,
ENTRY(header(s->base)+1));
if (error)
goto getblk_failed;
if (ea_inode) {
/* Drop the extra ref on ea_inode. */
error = ext4_xattr_inode_dec_ref(handle,
ea_inode);
if (error)
ext4_warning_inode(ea_inode,
"dec ref error=%d",
error);
iput(ea_inode);
ea_inode = NULL;
}
lock_buffer(new_bh);
error = ext4_journal_get_create_access(handle, sb,
new_bh, EXT4_JTR_NONE);
if (error) {
unlock_buffer(new_bh);
error = -EIO;
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
ext4_xattr_block_csum_set(inode, new_bh);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext4_xattr_block_cache_insert(ea_block_cache, new_bh);
error = ext4_handle_dirty_metadata(handle, inode,
new_bh);
if (error)
goto cleanup;
}
}
if (old_ea_inode_quota)
ext4_xattr_inode_free_quota(inode, NULL, old_ea_inode_quota);
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh) {
struct ext4_xattr_inode_array *ea_inode_array = NULL;
ext4_xattr_release_block(handle, inode, bs->bh,
&ea_inode_array,
0 /* extra_credits */);
ext4_xattr_inode_array_free(ea_inode_array);
}
error = 0;
cleanup:
if (ea_inode) {
int error2;
error2 = ext4_xattr_inode_dec_ref(handle, ea_inode);
if (error2)
ext4_warning_inode(ea_inode, "dec ref error=%d",
error2);
/* If there was an error, revert the quota charge. */
if (error)
ext4_xattr_inode_free_quota(inode, ea_inode,
i_size_read(ea_inode));
iput(ea_inode);
}
if (ce)
mb_cache_entry_put(ea_block_cache, ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
goto cleanup;
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
int error;
if (!EXT4_INODE_HAS_XATTR_SPACE(inode))
return 0;
raw_inode = ext4_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
error = xattr_check_inode(inode, header, is->s.end);
if (error)
return error;
/* Find the named attribute. */
error = xattr_find_entry(inode, &is->s.here, is->s.end,
i->name_index, i->name, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_ibody_find *is)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (!EXT4_INODE_HAS_XATTR_SPACE(inode))
return -ENOSPC;
error = ext4_xattr_set_entry(i, s, handle, inode, false /* is_block */);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
ext4_clear_inode_state(inode, EXT4_STATE_XATTR);
}
return 0;
}
static int ext4_xattr_value_same(struct ext4_xattr_search *s,
struct ext4_xattr_info *i)
{
void *value;
/* When e_value_inum is set the value is stored externally. */
if (s->here->e_value_inum)
return 0;
if (le32_to_cpu(s->here->e_value_size) != i->value_len)
return 0;
value = ((void *)s->base) + le16_to_cpu(s->here->e_value_offs);
return !memcmp(value, i->value, i->value_len);
}
static struct buffer_head *ext4_xattr_get_block(struct inode *inode)
{
struct buffer_head *bh;
int error;
if (!EXT4_I(inode)->i_file_acl)
return NULL;
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh))
return bh;
error = ext4_xattr_check_block(inode, bh);
if (error) {
brelse(bh);
return ERR_PTR(error);
}
return bh;
}
/*
* ext4_xattr_set_handle()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
.in_inode = 0,
};
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_block_find bs = {
.s = { .not_found = -ENODATA, },
};
int no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
ext4_write_lock_xattr(inode, &no_expand);
/* Check journal credits under write lock. */
if (ext4_handle_valid(handle)) {
struct buffer_head *bh;
int credits;
bh = ext4_xattr_get_block(inode);
if (IS_ERR(bh)) {
error = PTR_ERR(bh);
goto cleanup;
}
credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
value_len,
flags & XATTR_CREATE);
brelse(bh);
if (jbd2_handle_buffer_credits(handle) < credits) {
error = -ENOSPC;
goto cleanup;
}
WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
}
error = ext4_reserve_inode_write(handle, inode, &is.iloc);
if (error)
goto cleanup;
if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
ext4_clear_inode_state(inode, EXT4_STATE_NEW);
}
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else {
error = 0;
/* Xattr value did not change? Save us some work and bail out */
if (!is.s.not_found && ext4_xattr_value_same(&is.s, &i))
goto cleanup;
if (!bs.s.not_found && ext4_xattr_value_same(&bs.s, &i))
goto cleanup;
if (ext4_has_feature_ea_inode(inode->i_sb) &&
(EXT4_XATTR_SIZE(i.value_len) >
EXT4_XATTR_MIN_LARGE_EA_SIZE(inode->i_sb->s_blocksize)))
i.in_inode = 1;
retry_inode:
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = ext4_xattr_block_set(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
brelse(bs.bh);
bs.bh = NULL;
error = ext4_xattr_block_find(inode, &i, &bs);
if (error)
goto cleanup;
}
error = ext4_xattr_block_set(handle, inode, &i, &bs);
if (!error && !is.s.not_found) {
i.value = NULL;
error = ext4_xattr_ibody_set(handle, inode, &i,
&is);
} else if (error == -ENOSPC) {
/*
* Xattr does not fit in the block, store at
* external inode if possible.
*/
if (ext4_has_feature_ea_inode(inode->i_sb) &&
i.value_len && !i.in_inode) {
i.in_inode = 1;
goto retry_inode;
}
}
}
}
if (!error) {
ext4_xattr_update_super_block(handle, inode->i_sb);
inode_set_ctime_current(inode);
inode_inc_iversion(inode);
if (!value)
no_expand = 0;
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
/*
* The bh is consumed by ext4_mark_iloc_dirty, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, handle);
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
ext4_write_unlock_xattr(inode, &no_expand);
return error;
}
int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
bool is_create, int *credits)
{
struct buffer_head *bh;
int err;
*credits = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
down_read(&EXT4_I(inode)->xattr_sem);
bh = ext4_xattr_get_block(inode);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
} else {
*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
value_len, is_create);
brelse(bh);
err = 0;
}
up_read(&EXT4_I(inode)->xattr_sem);
return err;
}
/*
* ext4_xattr_set()
*
* Like ext4_xattr_set_handle, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
struct super_block *sb = inode->i_sb;
int error, retries = 0;
int credits;
error = dquot_initialize(inode);
if (error)
return error;
retry:
error = ext4_xattr_set_credits(inode, value_len, flags & XATTR_CREATE,
&credits);
if (error)
return error;
handle = ext4_journal_start(inode, EXT4_HT_XATTR, credits);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = ext4_xattr_set_handle(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
ext4_should_retry_alloc(sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, NULL);
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* We always shift xattr headers further thus offsets get lower */
BUG_ON(value_offs_shift > 0);
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_inum && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Move xattr pointed to by 'entry' from inode into external xattr block
*/
static int ext4_xattr_move_to_block(handle_t *handle, struct inode *inode,
struct ext4_inode *raw_inode,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_ibody_find *is = NULL;
struct ext4_xattr_block_find *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t value_size = le32_to_cpu(entry->e_value_size);
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
.name_index = entry->e_name_index,
.in_inode = !!entry->e_value_inum,
};
struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
int needs_kvfree = 0;
int error;
is = kzalloc(sizeof(struct ext4_xattr_ibody_find), GFP_NOFS);
bs = kzalloc(sizeof(struct ext4_xattr_block_find), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!is || !bs || !b_entry_name) {
error = -ENOMEM;
goto out;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
/* Save the entry name and the entry value */
if (entry->e_value_inum) {
buffer = kvmalloc(value_size, GFP_NOFS);
if (!buffer) {
error = -ENOMEM;
goto out;
}
needs_kvfree = 1;
error = ext4_xattr_inode_get(inode, entry, buffer, value_size);
if (error)
goto out;
} else {
size_t value_offs = le16_to_cpu(entry->e_value_offs);
buffer = (void *)IFIRST(header) + value_offs;
}
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto out;
error = ext4_xattr_ibody_find(inode, &i, is);
if (error)
goto out;
i.value = buffer;
i.value_len = value_size;
error = ext4_xattr_block_find(inode, &i, bs);
if (error)
goto out;
/* Move ea entry from the inode into the block */
error = ext4_xattr_block_set(handle, inode, &i, bs);
if (error)
goto out;
/* Remove the chosen entry from the inode */
i.value = NULL;
i.value_len = 0;
error = ext4_xattr_ibody_set(handle, inode, &i, is);
out:
kfree(b_entry_name);
if (needs_kvfree && buffer)
kvfree(buffer);
if (is)
brelse(is->iloc.bh);
if (bs)
brelse(bs->bh);
kfree(is);
kfree(bs);
return error;
}
static int ext4_xattr_make_inode_space(handle_t *handle, struct inode *inode,
struct ext4_inode *raw_inode,
int isize_diff, size_t ifree,
size_t bfree, int *total_ino)
{
struct ext4_xattr_ibody_header *header = IHDR(inode, raw_inode);
struct ext4_xattr_entry *small_entry;
struct ext4_xattr_entry *entry;
struct ext4_xattr_entry *last;
unsigned int entry_size; /* EA entry size */
unsigned int total_size; /* EA entry size + value size */
unsigned int min_total_size;
int error;
while (isize_diff > ifree) {
entry = NULL;
small_entry = NULL;
min_total_size = ~0U;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
/* never move system.data out of the inode */
if ((last->e_name_len == 4) &&
(last->e_name_index == EXT4_XATTR_INDEX_SYSTEM) &&
!memcmp(last->e_name, "data", 4))
continue;
total_size = EXT4_XATTR_LEN(last->e_name_len);
if (!last->e_value_inum)
total_size += EXT4_XATTR_SIZE(
le32_to_cpu(last->e_value_size));
if (total_size <= bfree &&
total_size < min_total_size) {
if (total_size + ifree < isize_diff) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry == NULL)
return -ENOSPC;
entry = small_entry;
}
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
total_size = entry_size;
if (!entry->e_value_inum)
total_size += EXT4_XATTR_SIZE(
le32_to_cpu(entry->e_value_size));
error = ext4_xattr_move_to_block(handle, inode, raw_inode,
entry);
if (error)
return error;
*total_ino -= entry_size;
ifree += total_size;
bfree -= total_size;
}
return 0;
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct ext4_xattr_ibody_header *header;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
static unsigned int mnt_count;
size_t min_offs;
size_t ifree, bfree;
int total_ino;
void *base, *end;
int error = 0, tried_min_extra_isize = 0;
int s_min_extra_isize = le16_to_cpu(sbi->s_es->s_min_extra_isize);
int isize_diff; /* How much do we need to grow i_extra_isize */
retry:
isize_diff = new_extra_isize - EXT4_I(inode)->i_extra_isize;
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
return 0;
header = IHDR(inode, raw_inode);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
total_ino = sizeof(struct ext4_xattr_ibody_header) + sizeof(u32);
error = xattr_check_inode(inode, header, end);
if (error)
goto cleanup;
ifree = ext4_xattr_free_space(base, &min_offs, base, &total_ino);
if (ifree >= isize_diff)
goto shift;
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
struct buffer_head *bh;
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh)) {
error = PTR_ERR(bh);
goto cleanup;
}
error = ext4_xattr_check_block(inode, bh);
if (error) {
brelse(bh);
goto cleanup;
}
base = BHDR(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
bfree = ext4_xattr_free_space(BFIRST(bh), &min_offs, base,
NULL);
brelse(bh);
if (bfree + ifree < isize_diff) {
if (!tried_min_extra_isize && s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
goto retry;
}
error = -ENOSPC;
goto cleanup;
}
} else {
bfree = inode->i_sb->s_blocksize;
}
error = ext4_xattr_make_inode_space(handle, inode, raw_inode,
isize_diff, ifree, bfree,
&total_ino);
if (error) {
if (error == -ENOSPC && !tried_min_extra_isize &&
s_min_extra_isize) {
tried_min_extra_isize++;
new_extra_isize = s_min_extra_isize;
goto retry;
}
goto cleanup;
}
shift:
/* Adjust the offsets and shift the remaining entries ahead */
ext4_xattr_shift_entries(IFIRST(header), EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + new_extra_isize,
(void *)header, total_ino);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
if (ext4_has_inline_data(inode))
error = ext4_find_inline_data_nolock(inode);
cleanup:
if (error && (mnt_count != le16_to_cpu(sbi->s_es->s_mnt_count))) {
ext4_warning(inode->i_sb, "Unable to expand inode %lu. Delete some EAs or run e2fsck.",
inode->i_ino);
mnt_count = le16_to_cpu(sbi->s_es->s_mnt_count);
}
return error;
}
#define EIA_INCR 16 /* must be 2^n */
#define EIA_MASK (EIA_INCR - 1)
/* Add the large xattr @inode into @ea_inode_array for deferred iput().
* If @ea_inode_array is new or full it will be grown and the old
* contents copied over.
*/
static int
ext4_expand_inode_array(struct ext4_xattr_inode_array **ea_inode_array,
struct inode *inode)
{
if (*ea_inode_array == NULL) {
/*
* Start with 15 inodes, so it fits into a power-of-two size.
* If *ea_inode_array is NULL, this is essentially offsetof()
*/
(*ea_inode_array) =
kmalloc(offsetof(struct ext4_xattr_inode_array,
inodes[EIA_MASK]),
GFP_NOFS);
if (*ea_inode_array == NULL)
return -ENOMEM;
(*ea_inode_array)->count = 0;
} else if (((*ea_inode_array)->count & EIA_MASK) == EIA_MASK) {
/* expand the array once all 15 + n * 16 slots are full */
struct ext4_xattr_inode_array *new_array = NULL;
int count = (*ea_inode_array)->count;
/* if new_array is NULL, this is essentially offsetof() */
new_array = kmalloc(
offsetof(struct ext4_xattr_inode_array,
inodes[count + EIA_INCR]),
GFP_NOFS);
if (new_array == NULL)
return -ENOMEM;
memcpy(new_array, *ea_inode_array,
offsetof(struct ext4_xattr_inode_array, inodes[count]));
kfree(*ea_inode_array);
*ea_inode_array = new_array;
}
(*ea_inode_array)->inodes[(*ea_inode_array)->count++] = inode;
return 0;
}
/*
* ext4_xattr_delete_inode()
*
* Free extended attribute resources associated with this inode. Traverse
* all entries and decrement reference on any xattr inodes associated with this
* inode. This is called immediately before an inode is freed. We have exclusive
* access to the inode. If an orphan inode is deleted it will also release its
* references on xattr block and xattr inodes.
*/
int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,
struct ext4_xattr_inode_array **ea_inode_array,
int extra_credits)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_ibody_header *header;
struct ext4_iloc iloc = { .bh = NULL };
struct ext4_xattr_entry *entry;
struct inode *ea_inode;
int error;
error = ext4_journal_ensure_credits(handle, extra_credits,
ext4_free_metadata_revoke_credits(inode->i_sb, 1));
if (error < 0) {
EXT4_ERROR_INODE(inode, "ensure credits (error %d)", error);
goto cleanup;
}
if (ext4_has_feature_ea_inode(inode->i_sb) &&
ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
error = ext4_get_inode_loc(inode, &iloc);
if (error) {
EXT4_ERROR_INODE(inode, "inode loc (error %d)", error);
goto cleanup;
}
error = ext4_journal_get_write_access(handle, inode->i_sb,
iloc.bh, EXT4_JTR_NONE);
if (error) {
EXT4_ERROR_INODE(inode, "write access (error %d)",
error);
goto cleanup;
}
header = IHDR(inode, ext4_raw_inode(&iloc));
if (header->h_magic == cpu_to_le32(EXT4_XATTR_MAGIC))
ext4_xattr_inode_dec_ref_all(handle, inode, iloc.bh,
IFIRST(header),
false /* block_csum */,
ea_inode_array,
extra_credits,
false /* skip_quota */);
}
if (EXT4_I(inode)->i_file_acl) {
bh = ext4_sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl, REQ_PRIO);
if (IS_ERR(bh)) {
error = PTR_ERR(bh);
if (error == -EIO) {
EXT4_ERROR_INODE_ERR(inode, EIO,
"block %llu read error",
EXT4_I(inode)->i_file_acl);
}
bh = NULL;
goto cleanup;
}
error = ext4_xattr_check_block(inode, bh);
if (error)
goto cleanup;
if (ext4_has_feature_ea_inode(inode->i_sb)) {
for (entry = BFIRST(bh); !IS_LAST_ENTRY(entry);
entry = EXT4_XATTR_NEXT(entry)) {
if (!entry->e_value_inum)
continue;
error = ext4_xattr_inode_iget(inode,
le32_to_cpu(entry->e_value_inum),
le32_to_cpu(entry->e_hash),
&ea_inode);
if (error)
continue;
ext4_xattr_inode_free_quota(inode, ea_inode,
le32_to_cpu(entry->e_value_size));
iput(ea_inode);
}
}
ext4_xattr_release_block(handle, inode, bh, ea_inode_array,
extra_credits);
/*
* Update i_file_acl value in the same transaction that releases
* block.
*/
EXT4_I(inode)->i_file_acl = 0;
error = ext4_mark_inode_dirty(handle, inode);
if (error) {
EXT4_ERROR_INODE(inode, "mark inode dirty (error %d)",
error);
goto cleanup;
}
ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR, handle);
}
error = 0;
cleanup:
brelse(iloc.bh);
brelse(bh);
return error;
}
void ext4_xattr_inode_array_free(struct ext4_xattr_inode_array *ea_inode_array)
{
int idx;
if (ea_inode_array == NULL)
return;
for (idx = 0; idx < ea_inode_array->count; ++idx)
iput(ea_inode_array->inodes[idx]);
kfree(ea_inode_array);
}
/*
* ext4_xattr_block_cache_insert()
*
* Create a new entry in the extended attribute block cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
ext4_xattr_block_cache_insert(struct mb_cache *ea_block_cache,
struct buffer_head *bh)
{
struct ext4_xattr_header *header = BHDR(bh);
__u32 hash = le32_to_cpu(header->h_hash);
int reusable = le32_to_cpu(header->h_refcount) <
EXT4_XATTR_REFCOUNT_MAX;
int error;
if (!ea_block_cache)
return;
error = mb_cache_entry_create(ea_block_cache, GFP_NOFS, hash,
bh->b_blocknr, reusable);
if (error) {
if (error == -EBUSY)
ea_bdebug(bh, "already in cache");
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
}
/*
* ext4_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
entry1->e_value_inum != entry2->e_value_inum ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (!entry1->e_value_inum &&
memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* ext4_xattr_block_cache_find()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
ext4_xattr_block_cache_find(struct inode *inode,
struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ea_block_cache = EA_BLOCK_CACHE(inode);
if (!ea_block_cache)
return NULL;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
ce = mb_cache_entry_find_first(ea_block_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = ext4_sb_bread(inode->i_sb, ce->e_value, REQ_PRIO);
if (IS_ERR(bh)) {
if (PTR_ERR(bh) == -ENOMEM)
return NULL;
bh = NULL;
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long)ce->e_value);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ea_block_cache, ce);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* ext4_xattr_hash_entry()
*
* Compute the hash of an extended attribute.
*/
static __le32 ext4_xattr_hash_entry(char *name, size_t name_len, __le32 *value,
size_t value_count)
{
__u32 hash = 0;
while (name_len--) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
(unsigned char)*name++;
}
while (value_count--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
return cpu_to_le32(hash);
}
/*
* ext4_xattr_hash_entry_signed()
*
* Compute the hash of an extended attribute incorrectly.
*/
static __le32 ext4_xattr_hash_entry_signed(char *name, size_t name_len, __le32 *value, size_t value_count)
{
__u32 hash = 0;
while (name_len--) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
(signed char)*name++;
}
while (value_count--) {
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
return cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
#define HASH_BUCKET_BITS 10
struct mb_cache *
ext4_xattr_create_cache(void)
{
return mb_cache_create(HASH_BUCKET_BITS);
}
void ext4_xattr_destroy_cache(struct mb_cache *cache)
{
if (cache)
mb_cache_destroy(cache);
}
| linux-master | fs/ext4/xattr.c |
// SPDX-License-Identifier: GPL-2.0
/*
* fs/ext4/verity.c: fs-verity support for ext4
*
* Copyright 2019 Google LLC
*/
/*
* Implementation of fsverity_operations for ext4.
*
* ext4 stores the verity metadata (Merkle tree and fsverity_descriptor) past
* the end of the file, starting at the first 64K boundary beyond i_size. This
* approach works because (a) verity files are readonly, and (b) pages fully
* beyond i_size aren't visible to userspace but can be read/written internally
* by ext4 with only some relatively small changes to ext4. This approach
* avoids having to depend on the EA_INODE feature and on rearchitecturing
* ext4's xattr support to support paging multi-gigabyte xattrs into memory, and
* to support encrypting xattrs. Note that the verity metadata *must* be
* encrypted when the file is, since it contains hashes of the plaintext data.
*
* Using a 64K boundary rather than a 4K one keeps things ready for
* architectures with 64K pages, and it doesn't necessarily waste space on-disk
* since there can be a hole between i_size and the start of the Merkle tree.
*/
#include <linux/quotaops.h>
#include "ext4.h"
#include "ext4_extents.h"
#include "ext4_jbd2.h"
static inline loff_t ext4_verity_metadata_pos(const struct inode *inode)
{
return round_up(inode->i_size, 65536);
}
/*
* Read some verity metadata from the inode. __vfs_read() can't be used because
* we need to read beyond i_size.
*/
static int pagecache_read(struct inode *inode, void *buf, size_t count,
loff_t pos)
{
while (count) {
struct folio *folio;
size_t n;
folio = read_mapping_folio(inode->i_mapping, pos >> PAGE_SHIFT,
NULL);
if (IS_ERR(folio))
return PTR_ERR(folio);
n = memcpy_from_file_folio(buf, folio, pos, count);
folio_put(folio);
buf += n;
pos += n;
count -= n;
}
return 0;
}
/*
* Write some verity metadata to the inode for FS_IOC_ENABLE_VERITY.
* kernel_write() can't be used because the file descriptor is readonly.
*/
static int pagecache_write(struct inode *inode, const void *buf, size_t count,
loff_t pos)
{
struct address_space *mapping = inode->i_mapping;
const struct address_space_operations *aops = mapping->a_ops;
if (pos + count > inode->i_sb->s_maxbytes)
return -EFBIG;
while (count) {
size_t n = min_t(size_t, count,
PAGE_SIZE - offset_in_page(pos));
struct page *page;
void *fsdata = NULL;
int res;
res = aops->write_begin(NULL, mapping, pos, n, &page, &fsdata);
if (res)
return res;
memcpy_to_page(page, offset_in_page(pos), buf, n);
res = aops->write_end(NULL, mapping, pos, n, n, page, fsdata);
if (res < 0)
return res;
if (res != n)
return -EIO;
buf += n;
pos += n;
count -= n;
}
return 0;
}
static int ext4_begin_enable_verity(struct file *filp)
{
struct inode *inode = file_inode(filp);
const int credits = 2; /* superblock and inode for ext4_orphan_add() */
handle_t *handle;
int err;
if (IS_DAX(inode) || ext4_test_inode_flag(inode, EXT4_INODE_DAX))
return -EINVAL;
if (ext4_verity_in_progress(inode))
return -EBUSY;
/*
* Since the file was opened readonly, we have to initialize the jbd
* inode and quotas here and not rely on ->open() doing it. This must
* be done before evicting the inline data.
*/
err = ext4_inode_attach_jinode(inode);
if (err)
return err;
err = dquot_initialize(inode);
if (err)
return err;
err = ext4_convert_inline_data(inode);
if (err)
return err;
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ext4_warning_inode(inode,
"verity is only allowed on extent-based files");
return -EOPNOTSUPP;
}
/*
* ext4 uses the last allocated block to find the verity descriptor, so
* we must remove any other blocks past EOF which might confuse things.
*/
err = ext4_truncate(inode);
if (err)
return err;
handle = ext4_journal_start(inode, EXT4_HT_INODE, credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
err = ext4_orphan_add(handle, inode);
if (err == 0)
ext4_set_inode_state(inode, EXT4_STATE_VERITY_IN_PROGRESS);
ext4_journal_stop(handle);
return err;
}
/*
* ext4 stores the verity descriptor beginning on the next filesystem block
* boundary after the Merkle tree. Then, the descriptor size is stored in the
* last 4 bytes of the last allocated filesystem block --- which is either the
* block in which the descriptor ends, or the next block after that if there
* weren't at least 4 bytes remaining.
*
* We can't simply store the descriptor in an xattr because it *must* be
* encrypted when ext4 encryption is used, but ext4 encryption doesn't encrypt
* xattrs. Also, if the descriptor includes a large signature blob it may be
* too large to store in an xattr without the EA_INODE feature.
*/
static int ext4_write_verity_descriptor(struct inode *inode, const void *desc,
size_t desc_size, u64 merkle_tree_size)
{
const u64 desc_pos = round_up(ext4_verity_metadata_pos(inode) +
merkle_tree_size, i_blocksize(inode));
const u64 desc_end = desc_pos + desc_size;
const __le32 desc_size_disk = cpu_to_le32(desc_size);
const u64 desc_size_pos = round_up(desc_end + sizeof(desc_size_disk),
i_blocksize(inode)) -
sizeof(desc_size_disk);
int err;
err = pagecache_write(inode, desc, desc_size, desc_pos);
if (err)
return err;
return pagecache_write(inode, &desc_size_disk, sizeof(desc_size_disk),
desc_size_pos);
}
static int ext4_end_enable_verity(struct file *filp, const void *desc,
size_t desc_size, u64 merkle_tree_size)
{
struct inode *inode = file_inode(filp);
const int credits = 2; /* superblock and inode for ext4_orphan_del() */
handle_t *handle;
struct ext4_iloc iloc;
int err = 0;
/*
* If an error already occurred (which fs/verity/ signals by passing
* desc == NULL), then only clean-up is needed.
*/
if (desc == NULL)
goto cleanup;
/* Append the verity descriptor. */
err = ext4_write_verity_descriptor(inode, desc, desc_size,
merkle_tree_size);
if (err)
goto cleanup;
/*
* Write all pages (both data and verity metadata). Note that this must
* happen before clearing EXT4_STATE_VERITY_IN_PROGRESS; otherwise pages
* beyond i_size won't be written properly. For crash consistency, this
* also must happen before the verity inode flag gets persisted.
*/
err = filemap_write_and_wait(inode->i_mapping);
if (err)
goto cleanup;
/*
* Finally, set the verity inode flag and remove the inode from the
* orphan list (in a single transaction).
*/
handle = ext4_journal_start(inode, EXT4_HT_INODE, credits);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto cleanup;
}
err = ext4_orphan_del(handle, inode);
if (err)
goto stop_and_cleanup;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto stop_and_cleanup;
ext4_set_inode_flag(inode, EXT4_INODE_VERITY);
ext4_set_inode_flags(inode, false);
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (err)
goto stop_and_cleanup;
ext4_journal_stop(handle);
ext4_clear_inode_state(inode, EXT4_STATE_VERITY_IN_PROGRESS);
return 0;
stop_and_cleanup:
ext4_journal_stop(handle);
cleanup:
/*
* Verity failed to be enabled, so clean up by truncating any verity
* metadata that was written beyond i_size (both from cache and from
* disk), removing the inode from the orphan list (if it wasn't done
* already), and clearing EXT4_STATE_VERITY_IN_PROGRESS.
*/
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext4_truncate(inode);
ext4_orphan_del(NULL, inode);
ext4_clear_inode_state(inode, EXT4_STATE_VERITY_IN_PROGRESS);
return err;
}
static int ext4_get_verity_descriptor_location(struct inode *inode,
size_t *desc_size_ret,
u64 *desc_pos_ret)
{
struct ext4_ext_path *path;
struct ext4_extent *last_extent;
u32 end_lblk;
u64 desc_size_pos;
__le32 desc_size_disk;
u32 desc_size;
u64 desc_pos;
int err;
/*
* Descriptor size is in last 4 bytes of last allocated block.
* See ext4_write_verity_descriptor().
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
EXT4_ERROR_INODE(inode, "verity file doesn't use extents");
return -EFSCORRUPTED;
}
path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL, 0);
if (IS_ERR(path))
return PTR_ERR(path);
last_extent = path[path->p_depth].p_ext;
if (!last_extent) {
EXT4_ERROR_INODE(inode, "verity file has no extents");
ext4_free_ext_path(path);
return -EFSCORRUPTED;
}
end_lblk = le32_to_cpu(last_extent->ee_block) +
ext4_ext_get_actual_len(last_extent);
desc_size_pos = (u64)end_lblk << inode->i_blkbits;
ext4_free_ext_path(path);
if (desc_size_pos < sizeof(desc_size_disk))
goto bad;
desc_size_pos -= sizeof(desc_size_disk);
err = pagecache_read(inode, &desc_size_disk, sizeof(desc_size_disk),
desc_size_pos);
if (err)
return err;
desc_size = le32_to_cpu(desc_size_disk);
/*
* The descriptor is stored just before the desc_size_disk, but starting
* on a filesystem block boundary.
*/
if (desc_size > INT_MAX || desc_size > desc_size_pos)
goto bad;
desc_pos = round_down(desc_size_pos - desc_size, i_blocksize(inode));
if (desc_pos < ext4_verity_metadata_pos(inode))
goto bad;
*desc_size_ret = desc_size;
*desc_pos_ret = desc_pos;
return 0;
bad:
EXT4_ERROR_INODE(inode, "verity file corrupted; can't find descriptor");
return -EFSCORRUPTED;
}
static int ext4_get_verity_descriptor(struct inode *inode, void *buf,
size_t buf_size)
{
size_t desc_size = 0;
u64 desc_pos = 0;
int err;
err = ext4_get_verity_descriptor_location(inode, &desc_size, &desc_pos);
if (err)
return err;
if (buf_size) {
if (desc_size > buf_size)
return -ERANGE;
err = pagecache_read(inode, buf, desc_size, desc_pos);
if (err)
return err;
}
return desc_size;
}
static struct page *ext4_read_merkle_tree_page(struct inode *inode,
pgoff_t index,
unsigned long num_ra_pages)
{
struct folio *folio;
index += ext4_verity_metadata_pos(inode) >> PAGE_SHIFT;
folio = __filemap_get_folio(inode->i_mapping, index, FGP_ACCESSED, 0);
if (IS_ERR(folio) || !folio_test_uptodate(folio)) {
DEFINE_READAHEAD(ractl, NULL, NULL, inode->i_mapping, index);
if (!IS_ERR(folio))
folio_put(folio);
else if (num_ra_pages > 1)
page_cache_ra_unbounded(&ractl, num_ra_pages, 0);
folio = read_mapping_folio(inode->i_mapping, index, NULL);
if (IS_ERR(folio))
return ERR_CAST(folio);
}
return folio_file_page(folio, index);
}
static int ext4_write_merkle_tree_block(struct inode *inode, const void *buf,
u64 pos, unsigned int size)
{
pos += ext4_verity_metadata_pos(inode);
return pagecache_write(inode, buf, size, pos);
}
const struct fsverity_operations ext4_verityops = {
.begin_enable_verity = ext4_begin_enable_verity,
.end_enable_verity = ext4_end_enable_verity,
.get_verity_descriptor = ext4_get_verity_descriptor,
.read_merkle_tree_page = ext4_read_merkle_tree_page,
.write_merkle_tree_block = ext4_write_merkle_tree_block,
};
| linux-master | fs/ext4/verity.c |
// SPDX-License-Identifier: GPL-2.0
#include <linux/fs.h>
#include <linux/random.h>
#include <linux/buffer_head.h>
#include <linux/utsname.h>
#include <linux/kthread.h>
#include "ext4.h"
/* Checksumming functions */
static __le32 ext4_mmp_csum(struct super_block *sb, struct mmp_struct *mmp)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct mmp_struct, mmp_checksum);
__u32 csum;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (char *)mmp, offset);
return cpu_to_le32(csum);
}
static int ext4_mmp_csum_verify(struct super_block *sb, struct mmp_struct *mmp)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return mmp->mmp_checksum == ext4_mmp_csum(sb, mmp);
}
static void ext4_mmp_csum_set(struct super_block *sb, struct mmp_struct *mmp)
{
if (!ext4_has_metadata_csum(sb))
return;
mmp->mmp_checksum = ext4_mmp_csum(sb, mmp);
}
/*
* Write the MMP block using REQ_SYNC to try to get the block on-disk
* faster.
*/
static int write_mmp_block_thawed(struct super_block *sb,
struct buffer_head *bh)
{
struct mmp_struct *mmp = (struct mmp_struct *)(bh->b_data);
ext4_mmp_csum_set(sb, mmp);
lock_buffer(bh);
bh->b_end_io = end_buffer_write_sync;
get_bh(bh);
submit_bh(REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO, bh);
wait_on_buffer(bh);
if (unlikely(!buffer_uptodate(bh)))
return -EIO;
return 0;
}
static int write_mmp_block(struct super_block *sb, struct buffer_head *bh)
{
int err;
/*
* We protect against freezing so that we don't create dirty buffers
* on frozen filesystem.
*/
sb_start_write(sb);
err = write_mmp_block_thawed(sb, bh);
sb_end_write(sb);
return err;
}
/*
* Read the MMP block. It _must_ be read from disk and hence we clear the
* uptodate flag on the buffer.
*/
static int read_mmp_block(struct super_block *sb, struct buffer_head **bh,
ext4_fsblk_t mmp_block)
{
struct mmp_struct *mmp;
int ret;
if (*bh)
clear_buffer_uptodate(*bh);
/* This would be sb_bread(sb, mmp_block), except we need to be sure
* that the MD RAID device cache has been bypassed, and that the read
* is not blocked in the elevator. */
if (!*bh) {
*bh = sb_getblk(sb, mmp_block);
if (!*bh) {
ret = -ENOMEM;
goto warn_exit;
}
}
lock_buffer(*bh);
ret = ext4_read_bh(*bh, REQ_META | REQ_PRIO, NULL);
if (ret)
goto warn_exit;
mmp = (struct mmp_struct *)((*bh)->b_data);
if (le32_to_cpu(mmp->mmp_magic) != EXT4_MMP_MAGIC) {
ret = -EFSCORRUPTED;
goto warn_exit;
}
if (!ext4_mmp_csum_verify(sb, mmp)) {
ret = -EFSBADCRC;
goto warn_exit;
}
return 0;
warn_exit:
brelse(*bh);
*bh = NULL;
ext4_warning(sb, "Error %d while reading MMP block %llu",
ret, mmp_block);
return ret;
}
/*
* Dump as much information as possible to help the admin.
*/
void __dump_mmp_msg(struct super_block *sb, struct mmp_struct *mmp,
const char *function, unsigned int line, const char *msg)
{
__ext4_warning(sb, function, line, "%s", msg);
__ext4_warning(sb, function, line,
"MMP failure info: last update time: %llu, last update node: %.*s, last update device: %.*s",
(unsigned long long)le64_to_cpu(mmp->mmp_time),
(int)sizeof(mmp->mmp_nodename), mmp->mmp_nodename,
(int)sizeof(mmp->mmp_bdevname), mmp->mmp_bdevname);
}
/*
* kmmpd will update the MMP sequence every s_mmp_update_interval seconds
*/
static int kmmpd(void *data)
{
struct super_block *sb = data;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *bh = EXT4_SB(sb)->s_mmp_bh;
struct mmp_struct *mmp;
ext4_fsblk_t mmp_block;
u32 seq = 0;
unsigned long failed_writes = 0;
int mmp_update_interval = le16_to_cpu(es->s_mmp_update_interval);
unsigned mmp_check_interval;
unsigned long last_update_time;
unsigned long diff;
int retval = 0;
mmp_block = le64_to_cpu(es->s_mmp_block);
mmp = (struct mmp_struct *)(bh->b_data);
mmp->mmp_time = cpu_to_le64(ktime_get_real_seconds());
/*
* Start with the higher mmp_check_interval and reduce it if
* the MMP block is being updated on time.
*/
mmp_check_interval = max(EXT4_MMP_CHECK_MULT * mmp_update_interval,
EXT4_MMP_MIN_CHECK_INTERVAL);
mmp->mmp_check_interval = cpu_to_le16(mmp_check_interval);
memcpy(mmp->mmp_nodename, init_utsname()->nodename,
sizeof(mmp->mmp_nodename));
while (!kthread_should_stop() && !ext4_forced_shutdown(sb)) {
if (!ext4_has_feature_mmp(sb)) {
ext4_warning(sb, "kmmpd being stopped since MMP feature"
" has been disabled.");
goto wait_to_exit;
}
if (++seq > EXT4_MMP_SEQ_MAX)
seq = 1;
mmp->mmp_seq = cpu_to_le32(seq);
mmp->mmp_time = cpu_to_le64(ktime_get_real_seconds());
last_update_time = jiffies;
retval = write_mmp_block(sb, bh);
/*
* Don't spew too many error messages. Print one every
* (s_mmp_update_interval * 60) seconds.
*/
if (retval) {
if ((failed_writes % 60) == 0) {
ext4_error_err(sb, -retval,
"Error writing to MMP block");
}
failed_writes++;
}
diff = jiffies - last_update_time;
if (diff < mmp_update_interval * HZ)
schedule_timeout_interruptible(mmp_update_interval *
HZ - diff);
/*
* We need to make sure that more than mmp_check_interval
* seconds have not passed since writing. If that has happened
* we need to check if the MMP block is as we left it.
*/
diff = jiffies - last_update_time;
if (diff > mmp_check_interval * HZ) {
struct buffer_head *bh_check = NULL;
struct mmp_struct *mmp_check;
retval = read_mmp_block(sb, &bh_check, mmp_block);
if (retval) {
ext4_error_err(sb, -retval,
"error reading MMP data: %d",
retval);
goto wait_to_exit;
}
mmp_check = (struct mmp_struct *)(bh_check->b_data);
if (mmp->mmp_seq != mmp_check->mmp_seq ||
memcmp(mmp->mmp_nodename, mmp_check->mmp_nodename,
sizeof(mmp->mmp_nodename))) {
dump_mmp_msg(sb, mmp_check,
"Error while updating MMP info. "
"The filesystem seems to have been"
" multiply mounted.");
ext4_error_err(sb, EBUSY, "abort");
put_bh(bh_check);
retval = -EBUSY;
goto wait_to_exit;
}
put_bh(bh_check);
}
/*
* Adjust the mmp_check_interval depending on how much time
* it took for the MMP block to be written.
*/
mmp_check_interval = max(min(EXT4_MMP_CHECK_MULT * diff / HZ,
EXT4_MMP_MAX_CHECK_INTERVAL),
EXT4_MMP_MIN_CHECK_INTERVAL);
mmp->mmp_check_interval = cpu_to_le16(mmp_check_interval);
}
/*
* Unmount seems to be clean.
*/
mmp->mmp_seq = cpu_to_le32(EXT4_MMP_SEQ_CLEAN);
mmp->mmp_time = cpu_to_le64(ktime_get_real_seconds());
retval = write_mmp_block(sb, bh);
wait_to_exit:
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
if (!kthread_should_stop())
schedule();
}
set_current_state(TASK_RUNNING);
return retval;
}
void ext4_stop_mmpd(struct ext4_sb_info *sbi)
{
if (sbi->s_mmp_tsk) {
kthread_stop(sbi->s_mmp_tsk);
brelse(sbi->s_mmp_bh);
sbi->s_mmp_tsk = NULL;
}
}
/*
* Get a random new sequence number but make sure it is not greater than
* EXT4_MMP_SEQ_MAX.
*/
static unsigned int mmp_new_seq(void)
{
return get_random_u32_below(EXT4_MMP_SEQ_MAX + 1);
}
/*
* Protect the filesystem from being mounted more than once.
*/
int ext4_multi_mount_protect(struct super_block *sb,
ext4_fsblk_t mmp_block)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *bh = NULL;
struct mmp_struct *mmp = NULL;
u32 seq;
unsigned int mmp_check_interval = le16_to_cpu(es->s_mmp_update_interval);
unsigned int wait_time = 0;
int retval;
if (mmp_block < le32_to_cpu(es->s_first_data_block) ||
mmp_block >= ext4_blocks_count(es)) {
ext4_warning(sb, "Invalid MMP block in superblock");
retval = -EINVAL;
goto failed;
}
retval = read_mmp_block(sb, &bh, mmp_block);
if (retval)
goto failed;
mmp = (struct mmp_struct *)(bh->b_data);
if (mmp_check_interval < EXT4_MMP_MIN_CHECK_INTERVAL)
mmp_check_interval = EXT4_MMP_MIN_CHECK_INTERVAL;
/*
* If check_interval in MMP block is larger, use that instead of
* update_interval from the superblock.
*/
if (le16_to_cpu(mmp->mmp_check_interval) > mmp_check_interval)
mmp_check_interval = le16_to_cpu(mmp->mmp_check_interval);
seq = le32_to_cpu(mmp->mmp_seq);
if (seq == EXT4_MMP_SEQ_CLEAN)
goto skip;
if (seq == EXT4_MMP_SEQ_FSCK) {
dump_mmp_msg(sb, mmp, "fsck is running on the filesystem");
retval = -EBUSY;
goto failed;
}
wait_time = min(mmp_check_interval * 2 + 1,
mmp_check_interval + 60);
/* Print MMP interval if more than 20 secs. */
if (wait_time > EXT4_MMP_MIN_CHECK_INTERVAL * 4)
ext4_warning(sb, "MMP interval %u higher than expected, please"
" wait.\n", wait_time * 2);
if (schedule_timeout_interruptible(HZ * wait_time) != 0) {
ext4_warning(sb, "MMP startup interrupted, failing mount\n");
retval = -ETIMEDOUT;
goto failed;
}
retval = read_mmp_block(sb, &bh, mmp_block);
if (retval)
goto failed;
mmp = (struct mmp_struct *)(bh->b_data);
if (seq != le32_to_cpu(mmp->mmp_seq)) {
dump_mmp_msg(sb, mmp,
"Device is already active on another node.");
retval = -EBUSY;
goto failed;
}
skip:
/*
* write a new random sequence number.
*/
seq = mmp_new_seq();
mmp->mmp_seq = cpu_to_le32(seq);
/*
* On mount / remount we are protected against fs freezing (by s_umount
* semaphore) and grabbing freeze protection upsets lockdep
*/
retval = write_mmp_block_thawed(sb, bh);
if (retval)
goto failed;
/*
* wait for MMP interval and check mmp_seq.
*/
if (schedule_timeout_interruptible(HZ * wait_time) != 0) {
ext4_warning(sb, "MMP startup interrupted, failing mount");
retval = -ETIMEDOUT;
goto failed;
}
retval = read_mmp_block(sb, &bh, mmp_block);
if (retval)
goto failed;
mmp = (struct mmp_struct *)(bh->b_data);
if (seq != le32_to_cpu(mmp->mmp_seq)) {
dump_mmp_msg(sb, mmp,
"Device is already active on another node.");
retval = -EBUSY;
goto failed;
}
EXT4_SB(sb)->s_mmp_bh = bh;
BUILD_BUG_ON(sizeof(mmp->mmp_bdevname) < BDEVNAME_SIZE);
snprintf(mmp->mmp_bdevname, sizeof(mmp->mmp_bdevname),
"%pg", bh->b_bdev);
/*
* Start a kernel thread to update the MMP block periodically.
*/
EXT4_SB(sb)->s_mmp_tsk = kthread_run(kmmpd, sb, "kmmpd-%.*s",
(int)sizeof(mmp->mmp_bdevname),
mmp->mmp_bdevname);
if (IS_ERR(EXT4_SB(sb)->s_mmp_tsk)) {
EXT4_SB(sb)->s_mmp_tsk = NULL;
ext4_warning(sb, "Unable to create kmmpd thread for %s.",
sb->s_id);
retval = -ENOMEM;
goto failed;
}
return 0;
failed:
brelse(bh);
return retval;
}
| linux-master | fs/ext4/mmp.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/block_validity.c
*
* Copyright (C) 2009
* Theodore Ts'o ([email protected])
*
* Track which blocks in the filesystem are metadata blocks that
* should never be used as data blocks by files or directories.
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <linux/blkdev.h>
#include <linux/slab.h>
#include "ext4.h"
struct ext4_system_zone {
struct rb_node node;
ext4_fsblk_t start_blk;
unsigned int count;
u32 ino;
};
static struct kmem_cache *ext4_system_zone_cachep;
int __init ext4_init_system_zone(void)
{
ext4_system_zone_cachep = KMEM_CACHE(ext4_system_zone, 0);
if (ext4_system_zone_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_exit_system_zone(void)
{
rcu_barrier();
kmem_cache_destroy(ext4_system_zone_cachep);
}
static inline int can_merge(struct ext4_system_zone *entry1,
struct ext4_system_zone *entry2)
{
if ((entry1->start_blk + entry1->count) == entry2->start_blk &&
entry1->ino == entry2->ino)
return 1;
return 0;
}
static void release_system_zone(struct ext4_system_blocks *system_blks)
{
struct ext4_system_zone *entry, *n;
rbtree_postorder_for_each_entry_safe(entry, n,
&system_blks->root, node)
kmem_cache_free(ext4_system_zone_cachep, entry);
}
/*
* Mark a range of blocks as belonging to the "system zone" --- that
* is, filesystem metadata blocks which should never be used by
* inodes.
*/
static int add_system_zone(struct ext4_system_blocks *system_blks,
ext4_fsblk_t start_blk,
unsigned int count, u32 ino)
{
struct ext4_system_zone *new_entry, *entry;
struct rb_node **n = &system_blks->root.rb_node, *node;
struct rb_node *parent = NULL, *new_node = NULL;
while (*n) {
parent = *n;
entry = rb_entry(parent, struct ext4_system_zone, node);
if (start_blk < entry->start_blk)
n = &(*n)->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = &(*n)->rb_right;
else /* Unexpected overlap of system zones. */
return -EFSCORRUPTED;
}
new_entry = kmem_cache_alloc(ext4_system_zone_cachep,
GFP_KERNEL);
if (!new_entry)
return -ENOMEM;
new_entry->start_blk = start_blk;
new_entry->count = count;
new_entry->ino = ino;
new_node = &new_entry->node;
rb_link_node(new_node, parent, n);
rb_insert_color(new_node, &system_blks->root);
/* Can we merge to the left? */
node = rb_prev(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(entry, new_entry)) {
new_entry->start_blk = entry->start_blk;
new_entry->count += entry->count;
rb_erase(node, &system_blks->root);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
/* Can we merge to the right? */
node = rb_next(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(new_entry, entry)) {
new_entry->count += entry->count;
rb_erase(node, &system_blks->root);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
return 0;
}
static void debug_print_tree(struct ext4_sb_info *sbi)
{
struct rb_node *node;
struct ext4_system_zone *entry;
struct ext4_system_blocks *system_blks;
int first = 1;
printk(KERN_INFO "System zones: ");
rcu_read_lock();
system_blks = rcu_dereference(sbi->s_system_blks);
node = rb_first(&system_blks->root);
while (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
printk(KERN_CONT "%s%llu-%llu", first ? "" : ", ",
entry->start_blk, entry->start_blk + entry->count - 1);
first = 0;
node = rb_next(node);
}
rcu_read_unlock();
printk(KERN_CONT "\n");
}
static int ext4_protect_reserved_inode(struct super_block *sb,
struct ext4_system_blocks *system_blks,
u32 ino)
{
struct inode *inode;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_map_blocks map;
u32 i = 0, num;
int err = 0, n;
if ((ino < EXT4_ROOT_INO) ||
(ino > le32_to_cpu(sbi->s_es->s_inodes_count)))
return -EINVAL;
inode = ext4_iget(sb, ino, EXT4_IGET_SPECIAL);
if (IS_ERR(inode))
return PTR_ERR(inode);
num = (inode->i_size + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
while (i < num) {
cond_resched();
map.m_lblk = i;
map.m_len = num - i;
n = ext4_map_blocks(NULL, inode, &map, 0);
if (n < 0) {
err = n;
break;
}
if (n == 0) {
i++;
} else {
err = add_system_zone(system_blks, map.m_pblk, n, ino);
if (err < 0) {
if (err == -EFSCORRUPTED) {
EXT4_ERROR_INODE_ERR(inode, -err,
"blocks %llu-%llu from inode overlap system zone",
map.m_pblk,
map.m_pblk + map.m_len - 1);
}
break;
}
i += n;
}
}
iput(inode);
return err;
}
static void ext4_destroy_system_zone(struct rcu_head *rcu)
{
struct ext4_system_blocks *system_blks;
system_blks = container_of(rcu, struct ext4_system_blocks, rcu);
release_system_zone(system_blks);
kfree(system_blks);
}
/*
* Build system zone rbtree which is used for block validity checking.
*
* The update of system_blks pointer in this function is protected by
* sb->s_umount semaphore. However we have to be careful as we can be
* racing with ext4_inode_block_valid() calls reading system_blks rbtree
* protected only by RCU. That's why we first build the rbtree and then
* swap it in place.
*/
int ext4_setup_system_zone(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_system_blocks *system_blks;
struct ext4_group_desc *gdp;
ext4_group_t i;
int ret;
system_blks = kzalloc(sizeof(*system_blks), GFP_KERNEL);
if (!system_blks)
return -ENOMEM;
for (i=0; i < ngroups; i++) {
unsigned int meta_blks = ext4_num_base_meta_blocks(sb, i);
cond_resched();
if (meta_blks != 0) {
ret = add_system_zone(system_blks,
ext4_group_first_block_no(sb, i),
meta_blks, 0);
if (ret)
goto err;
}
gdp = ext4_get_group_desc(sb, i, NULL);
ret = add_system_zone(system_blks,
ext4_block_bitmap(sb, gdp), 1, 0);
if (ret)
goto err;
ret = add_system_zone(system_blks,
ext4_inode_bitmap(sb, gdp), 1, 0);
if (ret)
goto err;
ret = add_system_zone(system_blks,
ext4_inode_table(sb, gdp),
sbi->s_itb_per_group, 0);
if (ret)
goto err;
}
if (ext4_has_feature_journal(sb) && sbi->s_es->s_journal_inum) {
ret = ext4_protect_reserved_inode(sb, system_blks,
le32_to_cpu(sbi->s_es->s_journal_inum));
if (ret)
goto err;
}
/*
* System blks rbtree complete, announce it once to prevent racing
* with ext4_inode_block_valid() accessing the rbtree at the same
* time.
*/
rcu_assign_pointer(sbi->s_system_blks, system_blks);
if (test_opt(sb, DEBUG))
debug_print_tree(sbi);
return 0;
err:
release_system_zone(system_blks);
kfree(system_blks);
return ret;
}
/*
* Called when the filesystem is unmounted or when remounting it with
* noblock_validity specified.
*
* The update of system_blks pointer in this function is protected by
* sb->s_umount semaphore. However we have to be careful as we can be
* racing with ext4_inode_block_valid() calls reading system_blks rbtree
* protected only by RCU. So we first clear the system_blks pointer and
* then free the rbtree only after RCU grace period expires.
*/
void ext4_release_system_zone(struct super_block *sb)
{
struct ext4_system_blocks *system_blks;
system_blks = rcu_dereference_protected(EXT4_SB(sb)->s_system_blks,
lockdep_is_held(&sb->s_umount));
rcu_assign_pointer(EXT4_SB(sb)->s_system_blks, NULL);
if (system_blks)
call_rcu(&system_blks->rcu, ext4_destroy_system_zone);
}
int ext4_sb_block_valid(struct super_block *sb, struct inode *inode,
ext4_fsblk_t start_blk, unsigned int count)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_system_blocks *system_blks;
struct ext4_system_zone *entry;
struct rb_node *n;
int ret = 1;
if ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(start_blk + count < start_blk) ||
(start_blk + count > ext4_blocks_count(sbi->s_es)))
return 0;
/*
* Lock the system zone to prevent it being released concurrently
* when doing a remount which inverse current "[no]block_validity"
* mount option.
*/
rcu_read_lock();
system_blks = rcu_dereference(sbi->s_system_blks);
if (system_blks == NULL)
goto out_rcu;
n = system_blks->root.rb_node;
while (n) {
entry = rb_entry(n, struct ext4_system_zone, node);
if (start_blk + count - 1 < entry->start_blk)
n = n->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = n->rb_right;
else {
ret = 0;
if (inode)
ret = (entry->ino == inode->i_ino);
break;
}
}
out_rcu:
rcu_read_unlock();
return ret;
}
/*
* Returns 1 if the passed-in block region (start_blk,
* start_blk+count) is valid; 0 if some part of the block region
* overlaps with some other filesystem metadata blocks.
*/
int ext4_inode_block_valid(struct inode *inode, ext4_fsblk_t start_blk,
unsigned int count)
{
return ext4_sb_block_valid(inode->i_sb, inode, start_blk, count);
}
int ext4_check_blockref(const char *function, unsigned int line,
struct inode *inode, __le32 *p, unsigned int max)
{
__le32 *bref = p;
unsigned int blk;
if (ext4_has_feature_journal(inode->i_sb) &&
(inode->i_ino ==
le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
return 0;
while (bref < p+max) {
blk = le32_to_cpu(*bref++);
if (blk &&
unlikely(!ext4_inode_block_valid(inode, blk, 1))) {
ext4_error_inode(inode, function, line, blk,
"invalid block");
return -EFSCORRUPTED;
}
}
return 0;
}
| linux-master | fs/ext4/block_validity.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/indirect.c
*
* from
*
* linux/fs/ext4/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie
* ([email protected]), 1993, 1998
*/
#include "ext4_jbd2.h"
#include "truncate.h"
#include <linux/dax.h>
#include <linux/uio.h>
#include <trace/events/ext4.h>
typedef struct {
__le32 *p;
__le32 key;
struct buffer_head *bh;
} Indirect;
static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
{
p->key = *(p->p = v);
p->bh = bh;
}
/**
* ext4_block_to_path - parse the block number into array of offsets
* @inode: inode in question (we are only interested in its superblock)
* @i_block: block number to be parsed
* @offsets: array to store the offsets in
* @boundary: set this non-zero if the referred-to block is likely to be
* followed (on disk) by an indirect block.
*
* To store the locations of file's data ext4 uses a data structure common
* for UNIX filesystems - tree of pointers anchored in the inode, with
* data blocks at leaves and indirect blocks in intermediate nodes.
* This function translates the block number into path in that tree -
* return value is the path length and @offsets[n] is the offset of
* pointer to (n+1)th node in the nth one. If @block is out of range
* (negative or too large) warning is printed and zero returned.
*
* Note: function doesn't find node addresses, so no IO is needed. All
* we need to know is the capacity of indirect blocks (taken from the
* inode->i_sb).
*/
/*
* Portability note: the last comparison (check that we fit into triple
* indirect block) is spelled differently, because otherwise on an
* architecture with 32-bit longs and 8Kb pages we might get into trouble
* if our filesystem had 8Kb blocks. We might use long long, but that would
* kill us on x86. Oh, well, at least the sign propagation does not matter -
* i_block would have to be negative in the very beginning, so we would not
* get there at all.
*/
static int ext4_block_to_path(struct inode *inode,
ext4_lblk_t i_block,
ext4_lblk_t offsets[4], int *boundary)
{
int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
const long direct_blocks = EXT4_NDIR_BLOCKS,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
int final = 0;
if (i_block < direct_blocks) {
offsets[n++] = i_block;
final = direct_blocks;
} else if ((i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = EXT4_IND_BLOCK;
offsets[n++] = i_block;
final = ptrs;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = EXT4_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = EXT4_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else {
ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
i_block + direct_blocks +
indirect_blocks + double_blocks, inode->i_ino);
}
if (boundary)
*boundary = final - 1 - (i_block & (ptrs - 1));
return n;
}
/**
* ext4_get_branch - read the chain of indirect blocks leading to data
* @inode: inode in question
* @depth: depth of the chain (1 - direct pointer, etc.)
* @offsets: offsets of pointers in inode/indirect blocks
* @chain: place to store the result
* @err: here we store the error value
*
* Function fills the array of triples <key, p, bh> and returns %NULL
* if everything went OK or the pointer to the last filled triple
* (incomplete one) otherwise. Upon the return chain[i].key contains
* the number of (i+1)-th block in the chain (as it is stored in memory,
* i.e. little-endian 32-bit), chain[i].p contains the address of that
* number (it points into struct inode for i==0 and into the bh->b_data
* for i>0) and chain[i].bh points to the buffer_head of i-th indirect
* block for i>0 and NULL for i==0. In other words, it holds the block
* numbers of the chain, addresses they were taken from (and where we can
* verify that chain did not change) and buffer_heads hosting these
* numbers.
*
* Function stops when it stumbles upon zero pointer (absent block)
* (pointer to last triple returned, *@err == 0)
* or when it gets an IO error reading an indirect block
* (ditto, *@err == -EIO)
* or when it reads all @depth-1 indirect blocks successfully and finds
* the whole chain, all way to the data (returns %NULL, *err == 0).
*
* Need to be called with
* down_read(&EXT4_I(inode)->i_data_sem)
*/
static Indirect *ext4_get_branch(struct inode *inode, int depth,
ext4_lblk_t *offsets,
Indirect chain[4], int *err)
{
struct super_block *sb = inode->i_sb;
Indirect *p = chain;
struct buffer_head *bh;
unsigned int key;
int ret = -EIO;
*err = 0;
/* i_data is not going away, no lock needed */
add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
if (!p->key)
goto no_block;
while (--depth) {
key = le32_to_cpu(p->key);
if (key > ext4_blocks_count(EXT4_SB(sb)->s_es)) {
/* the block was out of range */
ret = -EFSCORRUPTED;
goto failure;
}
bh = sb_getblk(sb, key);
if (unlikely(!bh)) {
ret = -ENOMEM;
goto failure;
}
if (!bh_uptodate_or_lock(bh)) {
if (ext4_read_bh(bh, 0, NULL) < 0) {
put_bh(bh);
goto failure;
}
/* validate block references */
if (ext4_check_indirect_blockref(inode, bh)) {
put_bh(bh);
goto failure;
}
}
add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
/* Reader: end */
if (!p->key)
goto no_block;
}
return NULL;
failure:
*err = ret;
no_block:
return p;
}
/**
* ext4_find_near - find a place for allocation with sufficient locality
* @inode: owner
* @ind: descriptor of indirect block.
*
* This function returns the preferred place for block allocation.
* It is used when heuristic for sequential allocation fails.
* Rules are:
* + if there is a block to the left of our position - allocate near it.
* + if pointer will live in indirect block - allocate near that block.
* + if pointer will live in inode - allocate in the same
* cylinder group.
*
* In the latter case we colour the starting block by the callers PID to
* prevent it from clashing with concurrent allocations for a different inode
* in the same block group. The PID is used here so that functionally related
* files will be close-by on-disk.
*
* Caller must make sure that @ind is valid and will stay that way.
*/
static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
{
struct ext4_inode_info *ei = EXT4_I(inode);
__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
__le32 *p;
/* Try to find previous block */
for (p = ind->p - 1; p >= start; p--) {
if (*p)
return le32_to_cpu(*p);
}
/* No such thing, so let's try location of indirect block */
if (ind->bh)
return ind->bh->b_blocknr;
/*
* It is going to be referred to from the inode itself? OK, just put it
* into the same cylinder group then.
*/
return ext4_inode_to_goal_block(inode);
}
/**
* ext4_find_goal - find a preferred place for allocation.
* @inode: owner
* @block: block we want
* @partial: pointer to the last triple within a chain
*
* Normally this function find the preferred place for block allocation,
* returns it.
* Because this is only used for non-extent files, we limit the block nr
* to 32 bits.
*/
static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
Indirect *partial)
{
ext4_fsblk_t goal;
/*
* XXX need to get goal block from mballoc's data structures
*/
goal = ext4_find_near(inode, partial);
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
return goal;
}
/**
* ext4_blks_to_allocate - Look up the block map and count the number
* of direct blocks need to be allocated for the given branch.
*
* @branch: chain of indirect blocks
* @k: number of blocks need for indirect blocks
* @blks: number of data blocks to be mapped.
* @blocks_to_boundary: the offset in the indirect block
*
* return the total number of blocks to be allocate, including the
* direct and indirect blocks.
*/
static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
int blocks_to_boundary)
{
unsigned int count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now we don't handle cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary &&
le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
/**
* ext4_alloc_branch() - allocate and set up a chain of blocks
* @handle: handle for this transaction
* @ar: structure describing the allocation request
* @indirect_blks: number of allocated indirect blocks
* @offsets: offsets (in the blocks) to store the pointers to next.
* @branch: place to store the chain in.
*
* This function allocates blocks, zeroes out all but the last one,
* links them into chain and (if we are synchronous) writes them to disk.
* In other words, it prepares a branch that can be spliced onto the
* inode. It stores the information about that chain in the branch[], in
* the same format as ext4_get_branch() would do. We are calling it after
* we had read the existing part of chain and partial points to the last
* triple of that (one with zero ->key). Upon the exit we have the same
* picture as after the successful ext4_get_block(), except that in one
* place chain is disconnected - *branch->p is still zero (we did not
* set the last link), but branch->key contains the number that should
* be placed into *branch->p to fill that gap.
*
* If allocation fails we free all blocks we've allocated (and forget
* their buffer_heads) and return the error value the from failed
* ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
* as described above and return 0.
*/
static int ext4_alloc_branch(handle_t *handle,
struct ext4_allocation_request *ar,
int indirect_blks, ext4_lblk_t *offsets,
Indirect *branch)
{
struct buffer_head * bh;
ext4_fsblk_t b, new_blocks[4];
__le32 *p;
int i, j, err, len = 1;
for (i = 0; i <= indirect_blks; i++) {
if (i == indirect_blks) {
new_blocks[i] = ext4_mb_new_blocks(handle, ar, &err);
} else {
ar->goal = new_blocks[i] = ext4_new_meta_blocks(handle,
ar->inode, ar->goal,
ar->flags & EXT4_MB_DELALLOC_RESERVED,
NULL, &err);
/* Simplify error cleanup... */
branch[i+1].bh = NULL;
}
if (err) {
i--;
goto failed;
}
branch[i].key = cpu_to_le32(new_blocks[i]);
if (i == 0)
continue;
bh = branch[i].bh = sb_getblk(ar->inode->i_sb, new_blocks[i-1]);
if (unlikely(!bh)) {
err = -ENOMEM;
goto failed;
}
lock_buffer(bh);
BUFFER_TRACE(bh, "call get_create_access");
err = ext4_journal_get_create_access(handle, ar->inode->i_sb,
bh, EXT4_JTR_NONE);
if (err) {
unlock_buffer(bh);
goto failed;
}
memset(bh->b_data, 0, bh->b_size);
p = branch[i].p = (__le32 *) bh->b_data + offsets[i];
b = new_blocks[i];
if (i == indirect_blks)
len = ar->len;
for (j = 0; j < len; j++)
*p++ = cpu_to_le32(b++);
BUFFER_TRACE(bh, "marking uptodate");
set_buffer_uptodate(bh);
unlock_buffer(bh);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, ar->inode, bh);
if (err)
goto failed;
}
return 0;
failed:
if (i == indirect_blks) {
/* Free data blocks */
ext4_free_blocks(handle, ar->inode, NULL, new_blocks[i],
ar->len, 0);
i--;
}
for (; i >= 0; i--) {
/*
* We want to ext4_forget() only freshly allocated indirect
* blocks. Buffer for new_blocks[i] is at branch[i+1].bh
* (buffer at branch[0].bh is indirect block / inode already
* existing before ext4_alloc_branch() was called). Also
* because blocks are freshly allocated, we don't need to
* revoke them which is why we don't set
* EXT4_FREE_BLOCKS_METADATA.
*/
ext4_free_blocks(handle, ar->inode, branch[i+1].bh,
new_blocks[i], 1,
branch[i+1].bh ? EXT4_FREE_BLOCKS_FORGET : 0);
}
return err;
}
/**
* ext4_splice_branch() - splice the allocated branch onto inode.
* @handle: handle for this transaction
* @ar: structure describing the allocation request
* @where: location of missing link
* @num: number of indirect blocks we are adding
*
* This function fills the missing link and does all housekeeping needed in
* inode (->i_blocks, etc.). In case of success we end up with the full
* chain to new block and return 0.
*/
static int ext4_splice_branch(handle_t *handle,
struct ext4_allocation_request *ar,
Indirect *where, int num)
{
int i;
int err = 0;
ext4_fsblk_t current_block;
/*
* If we're splicing into a [td]indirect block (as opposed to the
* inode) then we need to get write access to the [td]indirect block
* before the splice.
*/
if (where->bh) {
BUFFER_TRACE(where->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, ar->inode->i_sb,
where->bh, EXT4_JTR_NONE);
if (err)
goto err_out;
}
/* That's it */
*where->p = where->key;
/*
* Update the host buffer_head or inode to point to more just allocated
* direct blocks blocks
*/
if (num == 0 && ar->len > 1) {
current_block = le32_to_cpu(where->key) + 1;
for (i = 1; i < ar->len; i++)
*(where->p + i) = cpu_to_le32(current_block++);
}
/* We are done with atomic stuff, now do the rest of housekeeping */
/* had we spliced it onto indirect block? */
if (where->bh) {
/*
* If we spliced it onto an indirect block, we haven't
* altered the inode. Note however that if it is being spliced
* onto an indirect block at the very end of the file (the
* file is growing) then we *will* alter the inode to reflect
* the new i_size. But that is not done here - it is done in
* generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
*/
ext4_debug("splicing indirect only\n");
BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, ar->inode, where->bh);
if (err)
goto err_out;
} else {
/*
* OK, we spliced it into the inode itself on a direct block.
*/
err = ext4_mark_inode_dirty(handle, ar->inode);
if (unlikely(err))
goto err_out;
ext4_debug("splicing direct\n");
}
return err;
err_out:
for (i = 1; i <= num; i++) {
/*
* branch[i].bh is newly allocated, so there is no
* need to revoke the block, which is why we don't
* need to set EXT4_FREE_BLOCKS_METADATA.
*/
ext4_free_blocks(handle, ar->inode, where[i].bh, 0, 1,
EXT4_FREE_BLOCKS_FORGET);
}
ext4_free_blocks(handle, ar->inode, NULL, le32_to_cpu(where[num].key),
ar->len, 0);
return err;
}
/*
* The ext4_ind_map_blocks() function handles non-extents inodes
* (i.e., using the traditional indirect/double-indirect i_blocks
* scheme) for ext4_map_blocks().
*
* Allocation strategy is simple: if we have to allocate something, we will
* have to go the whole way to leaf. So let's do it before attaching anything
* to tree, set linkage between the newborn blocks, write them if sync is
* required, recheck the path, free and repeat if check fails, otherwise
* set the last missing link (that will protect us from any truncate-generated
* removals - all blocks on the path are immune now) and possibly force the
* write on the parent block.
* That has a nice additional property: no special recovery from the failed
* allocations is needed - we simply release blocks and do not touch anything
* reachable from inode.
*
* `handle' can be NULL if create == 0.
*
* return > 0, # of blocks mapped or allocated.
* return = 0, if plain lookup failed.
* return < 0, error case.
*
* The ext4_ind_get_blocks() function should be called with
* down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
* blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
* down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
* blocks.
*/
int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
int flags)
{
struct ext4_allocation_request ar;
int err = -EIO;
ext4_lblk_t offsets[4];
Indirect chain[4];
Indirect *partial;
int indirect_blks;
int blocks_to_boundary = 0;
int depth;
int count = 0;
ext4_fsblk_t first_block = 0;
trace_ext4_ind_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
depth = ext4_block_to_path(inode, map->m_lblk, offsets,
&blocks_to_boundary);
if (depth == 0)
goto out;
partial = ext4_get_branch(inode, depth, offsets, chain, &err);
/* Simplest case - block found, no allocation needed */
if (!partial) {
first_block = le32_to_cpu(chain[depth - 1].key);
count++;
/*map more blocks*/
while (count < map->m_len && count <= blocks_to_boundary) {
ext4_fsblk_t blk;
blk = le32_to_cpu(*(chain[depth-1].p + count));
if (blk == first_block + count)
count++;
else
break;
}
goto got_it;
}
/* Next simple case - plain lookup failed */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
unsigned epb = inode->i_sb->s_blocksize / sizeof(u32);
int i;
/*
* Count number blocks in a subtree under 'partial'. At each
* level we count number of complete empty subtrees beyond
* current offset and then descend into the subtree only
* partially beyond current offset.
*/
count = 0;
for (i = partial - chain + 1; i < depth; i++)
count = count * epb + (epb - offsets[i] - 1);
count++;
/* Fill in size of a hole we found */
map->m_pblk = 0;
map->m_len = min_t(unsigned int, map->m_len, count);
goto cleanup;
}
/* Failed read of indirect block */
if (err == -EIO)
goto cleanup;
/*
* Okay, we need to do block allocation.
*/
if (ext4_has_feature_bigalloc(inode->i_sb)) {
EXT4_ERROR_INODE(inode, "Can't allocate blocks for "
"non-extent mapped inodes with bigalloc");
err = -EFSCORRUPTED;
goto out;
}
/* Set up for the direct block allocation */
memset(&ar, 0, sizeof(ar));
ar.inode = inode;
ar.logical = map->m_lblk;
if (S_ISREG(inode->i_mode))
ar.flags = EXT4_MB_HINT_DATA;
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ar.flags |= EXT4_MB_DELALLOC_RESERVED;
if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
ar.flags |= EXT4_MB_USE_RESERVED;
ar.goal = ext4_find_goal(inode, map->m_lblk, partial);
/* the number of blocks need to allocate for [d,t]indirect blocks */
indirect_blks = (chain + depth) - partial - 1;
/*
* Next look up the indirect map to count the totoal number of
* direct blocks to allocate for this branch.
*/
ar.len = ext4_blks_to_allocate(partial, indirect_blks,
map->m_len, blocks_to_boundary);
/*
* Block out ext4_truncate while we alter the tree
*/
err = ext4_alloc_branch(handle, &ar, indirect_blks,
offsets + (partial - chain), partial);
/*
* The ext4_splice_branch call will free and forget any buffers
* on the new chain if there is a failure, but that risks using
* up transaction credits, especially for bitmaps where the
* credits cannot be returned. Can we handle this somehow? We
* may need to return -EAGAIN upwards in the worst case. --sct
*/
if (!err)
err = ext4_splice_branch(handle, &ar, partial, indirect_blks);
if (err)
goto cleanup;
map->m_flags |= EXT4_MAP_NEW;
ext4_update_inode_fsync_trans(handle, inode, 1);
count = ar.len;
/*
* Update reserved blocks/metadata blocks after successful block
* allocation which had been deferred till now.
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ext4_da_update_reserve_space(inode, count, 1);
got_it:
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = le32_to_cpu(chain[depth-1].key);
map->m_len = count;
if (count > blocks_to_boundary)
map->m_flags |= EXT4_MAP_BOUNDARY;
err = count;
/* Clean up and exit */
partial = chain + depth - 1; /* the whole chain */
cleanup:
while (partial > chain) {
BUFFER_TRACE(partial->bh, "call brelse");
brelse(partial->bh);
partial--;
}
out:
trace_ext4_ind_map_blocks_exit(inode, flags, map, err);
return err;
}
/*
* Calculate number of indirect blocks touched by mapping @nrblocks logically
* contiguous blocks
*/
int ext4_ind_trans_blocks(struct inode *inode, int nrblocks)
{
/*
* With N contiguous data blocks, we need at most
* N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
* 2 dindirect blocks, and 1 tindirect block
*/
return DIV_ROUND_UP(nrblocks, EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
}
static int ext4_ind_trunc_restart_fn(handle_t *handle, struct inode *inode,
struct buffer_head *bh, int *dropped)
{
int err;
if (bh) {
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (unlikely(err))
return err;
}
err = ext4_mark_inode_dirty(handle, inode);
if (unlikely(err))
return err;
/*
* Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
* moment, get_block can be called only for blocks inside i_size since
* page cache has been already dropped and writes are blocked by
* i_rwsem. So we can safely drop the i_data_sem here.
*/
BUG_ON(EXT4_JOURNAL(inode) == NULL);
ext4_discard_preallocations(inode, 0);
up_write(&EXT4_I(inode)->i_data_sem);
*dropped = 1;
return 0;
}
/*
* Truncate transactions can be complex and absolutely huge. So we need to
* be able to restart the transaction at a convenient checkpoint to make
* sure we don't overflow the journal.
*
* Try to extend this transaction for the purposes of truncation. If
* extend fails, we restart transaction.
*/
static int ext4_ind_truncate_ensure_credits(handle_t *handle,
struct inode *inode,
struct buffer_head *bh,
int revoke_creds)
{
int ret;
int dropped = 0;
ret = ext4_journal_ensure_credits_fn(handle, EXT4_RESERVE_TRANS_BLOCKS,
ext4_blocks_for_truncate(inode), revoke_creds,
ext4_ind_trunc_restart_fn(handle, inode, bh, &dropped));
if (dropped)
down_write(&EXT4_I(inode)->i_data_sem);
if (ret <= 0)
return ret;
if (bh) {
BUFFER_TRACE(bh, "retaking write access");
ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (unlikely(ret))
return ret;
}
return 0;
}
/*
* Probably it should be a library function... search for first non-zero word
* or memcmp with zero_page, whatever is better for particular architecture.
* Linus?
*/
static inline int all_zeroes(__le32 *p, __le32 *q)
{
while (p < q)
if (*p++)
return 0;
return 1;
}
/**
* ext4_find_shared - find the indirect blocks for partial truncation.
* @inode: inode in question
* @depth: depth of the affected branch
* @offsets: offsets of pointers in that branch (see ext4_block_to_path)
* @chain: place to store the pointers to partial indirect blocks
* @top: place to the (detached) top of branch
*
* This is a helper function used by ext4_truncate().
*
* When we do truncate() we may have to clean the ends of several
* indirect blocks but leave the blocks themselves alive. Block is
* partially truncated if some data below the new i_size is referred
* from it (and it is on the path to the first completely truncated
* data block, indeed). We have to free the top of that path along
* with everything to the right of the path. Since no allocation
* past the truncation point is possible until ext4_truncate()
* finishes, we may safely do the latter, but top of branch may
* require special attention - pageout below the truncation point
* might try to populate it.
*
* We atomically detach the top of branch from the tree, store the
* block number of its root in *@top, pointers to buffer_heads of
* partially truncated blocks - in @chain[].bh and pointers to
* their last elements that should not be removed - in
* @chain[].p. Return value is the pointer to last filled element
* of @chain.
*
* The work left to caller to do the actual freeing of subtrees:
* a) free the subtree starting from *@top
* b) free the subtrees whose roots are stored in
* (@chain[i].p+1 .. end of @chain[i].bh->b_data)
* c) free the subtrees growing from the inode past the @chain[0].
* (no partially truncated stuff there). */
static Indirect *ext4_find_shared(struct inode *inode, int depth,
ext4_lblk_t offsets[4], Indirect chain[4],
__le32 *top)
{
Indirect *partial, *p;
int k, err;
*top = 0;
/* Make k index the deepest non-null offset + 1 */
for (k = depth; k > 1 && !offsets[k-1]; k--)
;
partial = ext4_get_branch(inode, k, offsets, chain, &err);
/* Writer: pointers */
if (!partial)
partial = chain + k-1;
/*
* If the branch acquired continuation since we've looked at it -
* fine, it should all survive and (new) top doesn't belong to us.
*/
if (!partial->key && *partial->p)
/* Writer: end */
goto no_top;
for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
;
/*
* OK, we've found the last block that must survive. The rest of our
* branch should be detached before unlocking. However, if that rest
* of branch is all ours and does not grow immediately from the inode
* it's easier to cheat and just decrement partial->p.
*/
if (p == chain + k - 1 && p > chain) {
p->p--;
} else {
*top = *p->p;
/* Nope, don't do this in ext4. Must leave the tree intact */
#if 0
*p->p = 0;
#endif
}
/* Writer: end */
while (partial > p) {
brelse(partial->bh);
partial--;
}
no_top:
return partial;
}
/*
* Zero a number of block pointers in either an inode or an indirect block.
* If we restart the transaction we must again get write access to the
* indirect block for further modification.
*
* We release `count' blocks on disk, but (last - first) may be greater
* than `count' because there can be holes in there.
*
* Return 0 on success, 1 on invalid block range
* and < 0 on fatal error.
*/
static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
struct buffer_head *bh,
ext4_fsblk_t block_to_free,
unsigned long count, __le32 *first,
__le32 *last)
{
__le32 *p;
int flags = EXT4_FREE_BLOCKS_VALIDATED;
int err;
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
flags |= EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_METADATA;
else if (ext4_should_journal_data(inode))
flags |= EXT4_FREE_BLOCKS_FORGET;
if (!ext4_inode_block_valid(inode, block_to_free, count)) {
EXT4_ERROR_INODE(inode, "attempt to clear invalid "
"blocks %llu len %lu",
(unsigned long long) block_to_free, count);
return 1;
}
err = ext4_ind_truncate_ensure_credits(handle, inode, bh,
ext4_free_data_revoke_credits(inode, count));
if (err < 0)
goto out_err;
for (p = first; p < last; p++)
*p = 0;
ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
return 0;
out_err:
ext4_std_error(inode->i_sb, err);
return err;
}
/**
* ext4_free_data - free a list of data blocks
* @handle: handle for this transaction
* @inode: inode we are dealing with
* @this_bh: indirect buffer_head which contains *@first and *@last
* @first: array of block numbers
* @last: points immediately past the end of array
*
* We are freeing all blocks referred from that array (numbers are stored as
* little-endian 32-bit) and updating @inode->i_blocks appropriately.
*
* We accumulate contiguous runs of blocks to free. Conveniently, if these
* blocks are contiguous then releasing them at one time will only affect one
* or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
* actually use a lot of journal space.
*
* @this_bh will be %NULL if @first and @last point into the inode's direct
* block pointers.
*/
static void ext4_free_data(handle_t *handle, struct inode *inode,
struct buffer_head *this_bh,
__le32 *first, __le32 *last)
{
ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
unsigned long count = 0; /* Number of blocks in the run */
__le32 *block_to_free_p = NULL; /* Pointer into inode/ind
corresponding to
block_to_free */
ext4_fsblk_t nr; /* Current block # */
__le32 *p; /* Pointer into inode/ind
for current block */
int err = 0;
if (this_bh) { /* For indirect block */
BUFFER_TRACE(this_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb,
this_bh, EXT4_JTR_NONE);
/* Important: if we can't update the indirect pointers
* to the blocks, we can't free them. */
if (err)
return;
}
for (p = first; p < last; p++) {
nr = le32_to_cpu(*p);
if (nr) {
/* accumulate blocks to free if they're contiguous */
if (count == 0) {
block_to_free = nr;
block_to_free_p = p;
count = 1;
} else if (nr == block_to_free + count) {
count++;
} else {
err = ext4_clear_blocks(handle, inode, this_bh,
block_to_free, count,
block_to_free_p, p);
if (err)
break;
block_to_free = nr;
block_to_free_p = p;
count = 1;
}
}
}
if (!err && count > 0)
err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
count, block_to_free_p, p);
if (err < 0)
/* fatal error */
return;
if (this_bh) {
BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
/*
* The buffer head should have an attached journal head at this
* point. However, if the data is corrupted and an indirect
* block pointed to itself, it would have been detached when
* the block was cleared. Check for this instead of OOPSing.
*/
if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
ext4_handle_dirty_metadata(handle, inode, this_bh);
else
EXT4_ERROR_INODE(inode,
"circular indirect block detected at "
"block %llu",
(unsigned long long) this_bh->b_blocknr);
}
}
/**
* ext4_free_branches - free an array of branches
* @handle: JBD handle for this transaction
* @inode: inode we are dealing with
* @parent_bh: the buffer_head which contains *@first and *@last
* @first: array of block numbers
* @last: pointer immediately past the end of array
* @depth: depth of the branches to free
*
* We are freeing all blocks referred from these branches (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static void ext4_free_branches(handle_t *handle, struct inode *inode,
struct buffer_head *parent_bh,
__le32 *first, __le32 *last, int depth)
{
ext4_fsblk_t nr;
__le32 *p;
if (ext4_handle_is_aborted(handle))
return;
if (depth--) {
struct buffer_head *bh;
int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
p = last;
while (--p >= first) {
nr = le32_to_cpu(*p);
if (!nr)
continue; /* A hole */
if (!ext4_inode_block_valid(inode, nr, 1)) {
EXT4_ERROR_INODE(inode,
"invalid indirect mapped "
"block %lu (level %d)",
(unsigned long) nr, depth);
break;
}
/* Go read the buffer for the next level down */
bh = ext4_sb_bread(inode->i_sb, nr, 0);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (IS_ERR(bh)) {
ext4_error_inode_block(inode, nr, -PTR_ERR(bh),
"Read failure");
continue;
}
/* This zaps the entire block. Bottom up. */
BUFFER_TRACE(bh, "free child branches");
ext4_free_branches(handle, inode, bh,
(__le32 *) bh->b_data,
(__le32 *) bh->b_data + addr_per_block,
depth);
brelse(bh);
/*
* Everything below this pointer has been
* released. Now let this top-of-subtree go.
*
* We want the freeing of this indirect block to be
* atomic in the journal with the updating of the
* bitmap block which owns it. So make some room in
* the journal.
*
* We zero the parent pointer *after* freeing its
* pointee in the bitmaps, so if extend_transaction()
* for some reason fails to put the bitmap changes and
* the release into the same transaction, recovery
* will merely complain about releasing a free block,
* rather than leaking blocks.
*/
if (ext4_handle_is_aborted(handle))
return;
if (ext4_ind_truncate_ensure_credits(handle, inode,
NULL,
ext4_free_metadata_revoke_credits(
inode->i_sb, 1)) < 0)
return;
/*
* The forget flag here is critical because if
* we are journaling (and not doing data
* journaling), we have to make sure a revoke
* record is written to prevent the journal
* replay from overwriting the (former)
* indirect block if it gets reallocated as a
* data block. This must happen in the same
* transaction where the data blocks are
* actually freed.
*/
ext4_free_blocks(handle, inode, NULL, nr, 1,
EXT4_FREE_BLOCKS_METADATA|
EXT4_FREE_BLOCKS_FORGET);
if (parent_bh) {
/*
* The block which we have just freed is
* pointed to by an indirect block: journal it
*/
BUFFER_TRACE(parent_bh, "get_write_access");
if (!ext4_journal_get_write_access(handle,
inode->i_sb, parent_bh,
EXT4_JTR_NONE)) {
*p = 0;
BUFFER_TRACE(parent_bh,
"call ext4_handle_dirty_metadata");
ext4_handle_dirty_metadata(handle,
inode,
parent_bh);
}
}
}
} else {
/* We have reached the bottom of the tree. */
BUFFER_TRACE(parent_bh, "free data blocks");
ext4_free_data(handle, inode, parent_bh, first, last);
}
}
void ext4_ind_truncate(handle_t *handle, struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
__le32 *i_data = ei->i_data;
int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
ext4_lblk_t offsets[4];
Indirect chain[4];
Indirect *partial;
__le32 nr = 0;
int n = 0;
ext4_lblk_t last_block, max_block;
unsigned blocksize = inode->i_sb->s_blocksize;
last_block = (inode->i_size + blocksize-1)
>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
if (last_block != max_block) {
n = ext4_block_to_path(inode, last_block, offsets, NULL);
if (n == 0)
return;
}
ext4_es_remove_extent(inode, last_block, EXT_MAX_BLOCKS - last_block);
/*
* The orphan list entry will now protect us from any crash which
* occurs before the truncate completes, so it is now safe to propagate
* the new, shorter inode size (held for now in i_size) into the
* on-disk inode. We do this via i_disksize, which is the value which
* ext4 *really* writes onto the disk inode.
*/
ei->i_disksize = inode->i_size;
if (last_block == max_block) {
/*
* It is unnecessary to free any data blocks if last_block is
* equal to the indirect block limit.
*/
return;
} else if (n == 1) { /* direct blocks */
ext4_free_data(handle, inode, NULL, i_data+offsets[0],
i_data + EXT4_NDIR_BLOCKS);
goto do_indirects;
}
partial = ext4_find_shared(inode, n, offsets, chain, &nr);
/* Kill the top of shared branch (not detached) */
if (nr) {
if (partial == chain) {
/* Shared branch grows from the inode */
ext4_free_branches(handle, inode, NULL,
&nr, &nr+1, (chain+n-1) - partial);
*partial->p = 0;
/*
* We mark the inode dirty prior to restart,
* and prior to stop. No need for it here.
*/
} else {
/* Shared branch grows from an indirect block */
BUFFER_TRACE(partial->bh, "get_write_access");
ext4_free_branches(handle, inode, partial->bh,
partial->p,
partial->p+1, (chain+n-1) - partial);
}
}
/* Clear the ends of indirect blocks on the shared branch */
while (partial > chain) {
ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
(__le32*)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
BUFFER_TRACE(partial->bh, "call brelse");
brelse(partial->bh);
partial--;
}
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
nr = i_data[EXT4_IND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
i_data[EXT4_IND_BLOCK] = 0;
}
fallthrough;
case EXT4_IND_BLOCK:
nr = i_data[EXT4_DIND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
i_data[EXT4_DIND_BLOCK] = 0;
}
fallthrough;
case EXT4_DIND_BLOCK:
nr = i_data[EXT4_TIND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
i_data[EXT4_TIND_BLOCK] = 0;
}
fallthrough;
case EXT4_TIND_BLOCK:
;
}
}
/**
* ext4_ind_remove_space - remove space from the range
* @handle: JBD handle for this transaction
* @inode: inode we are dealing with
* @start: First block to remove
* @end: One block after the last block to remove (exclusive)
*
* Free the blocks in the defined range (end is exclusive endpoint of
* range). This is used by ext4_punch_hole().
*/
int ext4_ind_remove_space(handle_t *handle, struct inode *inode,
ext4_lblk_t start, ext4_lblk_t end)
{
struct ext4_inode_info *ei = EXT4_I(inode);
__le32 *i_data = ei->i_data;
int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
ext4_lblk_t offsets[4], offsets2[4];
Indirect chain[4], chain2[4];
Indirect *partial, *partial2;
Indirect *p = NULL, *p2 = NULL;
ext4_lblk_t max_block;
__le32 nr = 0, nr2 = 0;
int n = 0, n2 = 0;
unsigned blocksize = inode->i_sb->s_blocksize;
max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
if (end >= max_block)
end = max_block;
if ((start >= end) || (start > max_block))
return 0;
n = ext4_block_to_path(inode, start, offsets, NULL);
n2 = ext4_block_to_path(inode, end, offsets2, NULL);
BUG_ON(n > n2);
if ((n == 1) && (n == n2)) {
/* We're punching only within direct block range */
ext4_free_data(handle, inode, NULL, i_data + offsets[0],
i_data + offsets2[0]);
return 0;
} else if (n2 > n) {
/*
* Start and end are on a different levels so we're going to
* free partial block at start, and partial block at end of
* the range. If there are some levels in between then
* do_indirects label will take care of that.
*/
if (n == 1) {
/*
* Start is at the direct block level, free
* everything to the end of the level.
*/
ext4_free_data(handle, inode, NULL, i_data + offsets[0],
i_data + EXT4_NDIR_BLOCKS);
goto end_range;
}
partial = p = ext4_find_shared(inode, n, offsets, chain, &nr);
if (nr) {
if (partial == chain) {
/* Shared branch grows from the inode */
ext4_free_branches(handle, inode, NULL,
&nr, &nr+1, (chain+n-1) - partial);
*partial->p = 0;
} else {
/* Shared branch grows from an indirect block */
BUFFER_TRACE(partial->bh, "get_write_access");
ext4_free_branches(handle, inode, partial->bh,
partial->p,
partial->p+1, (chain+n-1) - partial);
}
}
/*
* Clear the ends of indirect blocks on the shared branch
* at the start of the range
*/
while (partial > chain) {
ext4_free_branches(handle, inode, partial->bh,
partial->p + 1,
(__le32 *)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
partial--;
}
end_range:
partial2 = p2 = ext4_find_shared(inode, n2, offsets2, chain2, &nr2);
if (nr2) {
if (partial2 == chain2) {
/*
* Remember, end is exclusive so here we're at
* the start of the next level we're not going
* to free. Everything was covered by the start
* of the range.
*/
goto do_indirects;
}
} else {
/*
* ext4_find_shared returns Indirect structure which
* points to the last element which should not be
* removed by truncate. But this is end of the range
* in punch_hole so we need to point to the next element
*/
partial2->p++;
}
/*
* Clear the ends of indirect blocks on the shared branch
* at the end of the range
*/
while (partial2 > chain2) {
ext4_free_branches(handle, inode, partial2->bh,
(__le32 *)partial2->bh->b_data,
partial2->p,
(chain2+n2-1) - partial2);
partial2--;
}
goto do_indirects;
}
/* Punch happened within the same level (n == n2) */
partial = p = ext4_find_shared(inode, n, offsets, chain, &nr);
partial2 = p2 = ext4_find_shared(inode, n2, offsets2, chain2, &nr2);
/* Free top, but only if partial2 isn't its subtree. */
if (nr) {
int level = min(partial - chain, partial2 - chain2);
int i;
int subtree = 1;
for (i = 0; i <= level; i++) {
if (offsets[i] != offsets2[i]) {
subtree = 0;
break;
}
}
if (!subtree) {
if (partial == chain) {
/* Shared branch grows from the inode */
ext4_free_branches(handle, inode, NULL,
&nr, &nr+1,
(chain+n-1) - partial);
*partial->p = 0;
} else {
/* Shared branch grows from an indirect block */
BUFFER_TRACE(partial->bh, "get_write_access");
ext4_free_branches(handle, inode, partial->bh,
partial->p,
partial->p+1,
(chain+n-1) - partial);
}
}
}
if (!nr2) {
/*
* ext4_find_shared returns Indirect structure which
* points to the last element which should not be
* removed by truncate. But this is end of the range
* in punch_hole so we need to point to the next element
*/
partial2->p++;
}
while (partial > chain || partial2 > chain2) {
int depth = (chain+n-1) - partial;
int depth2 = (chain2+n2-1) - partial2;
if (partial > chain && partial2 > chain2 &&
partial->bh->b_blocknr == partial2->bh->b_blocknr) {
/*
* We've converged on the same block. Clear the range,
* then we're done.
*/
ext4_free_branches(handle, inode, partial->bh,
partial->p + 1,
partial2->p,
(chain+n-1) - partial);
goto cleanup;
}
/*
* The start and end partial branches may not be at the same
* level even though the punch happened within one level. So, we
* give them a chance to arrive at the same level, then walk
* them in step with each other until we converge on the same
* block.
*/
if (partial > chain && depth <= depth2) {
ext4_free_branches(handle, inode, partial->bh,
partial->p + 1,
(__le32 *)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
partial--;
}
if (partial2 > chain2 && depth2 <= depth) {
ext4_free_branches(handle, inode, partial2->bh,
(__le32 *)partial2->bh->b_data,
partial2->p,
(chain2+n2-1) - partial2);
partial2--;
}
}
cleanup:
while (p && p > chain) {
BUFFER_TRACE(p->bh, "call brelse");
brelse(p->bh);
p--;
}
while (p2 && p2 > chain2) {
BUFFER_TRACE(p2->bh, "call brelse");
brelse(p2->bh);
p2--;
}
return 0;
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
if (++n >= n2)
break;
nr = i_data[EXT4_IND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
i_data[EXT4_IND_BLOCK] = 0;
}
fallthrough;
case EXT4_IND_BLOCK:
if (++n >= n2)
break;
nr = i_data[EXT4_DIND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
i_data[EXT4_DIND_BLOCK] = 0;
}
fallthrough;
case EXT4_DIND_BLOCK:
if (++n >= n2)
break;
nr = i_data[EXT4_TIND_BLOCK];
if (nr) {
ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
i_data[EXT4_TIND_BLOCK] = 0;
}
fallthrough;
case EXT4_TIND_BLOCK:
;
}
goto cleanup;
}
| linux-master | fs/ext4/indirect.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/bitmap.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include <linux/buffer_head.h>
#include "ext4.h"
unsigned int ext4_count_free(char *bitmap, unsigned int numchars)
{
return numchars * BITS_PER_BYTE - memweight(bitmap, numchars);
}
int ext4_inode_bitmap_csum_verify(struct super_block *sb,
struct ext4_group_desc *gdp,
struct buffer_head *bh, int sz)
{
__u32 hi;
__u32 provided, calculated;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return 1;
provided = le16_to_cpu(gdp->bg_inode_bitmap_csum_lo);
calculated = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END) {
hi = le16_to_cpu(gdp->bg_inode_bitmap_csum_hi);
provided |= (hi << 16);
} else
calculated &= 0xFFFF;
return provided == calculated;
}
void ext4_inode_bitmap_csum_set(struct super_block *sb,
struct ext4_group_desc *gdp,
struct buffer_head *bh, int sz)
{
__u32 csum;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
gdp->bg_inode_bitmap_csum_lo = cpu_to_le16(csum & 0xFFFF);
if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END)
gdp->bg_inode_bitmap_csum_hi = cpu_to_le16(csum >> 16);
}
int ext4_block_bitmap_csum_verify(struct super_block *sb,
struct ext4_group_desc *gdp,
struct buffer_head *bh)
{
__u32 hi;
__u32 provided, calculated;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int sz = EXT4_CLUSTERS_PER_GROUP(sb) / 8;
if (!ext4_has_metadata_csum(sb))
return 1;
provided = le16_to_cpu(gdp->bg_block_bitmap_csum_lo);
calculated = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END) {
hi = le16_to_cpu(gdp->bg_block_bitmap_csum_hi);
provided |= (hi << 16);
} else
calculated &= 0xFFFF;
return provided == calculated;
}
void ext4_block_bitmap_csum_set(struct super_block *sb,
struct ext4_group_desc *gdp,
struct buffer_head *bh)
{
int sz = EXT4_CLUSTERS_PER_GROUP(sb) / 8;
__u32 csum;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
gdp->bg_block_bitmap_csum_lo = cpu_to_le16(csum & 0xFFFF);
if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END)
gdp->bg_block_bitmap_csum_hi = cpu_to_le16(csum >> 16);
}
| linux-master | fs/ext4/bitmap.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Interface between ext4 and JBD
*/
#include "ext4_jbd2.h"
#include <trace/events/ext4.h>
int ext4_inode_journal_mode(struct inode *inode)
{
if (EXT4_JOURNAL(inode) == NULL)
return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */
/* We do not support data journalling with delayed allocation */
if (!S_ISREG(inode->i_mode) ||
ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE) ||
test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
(ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA) &&
!test_opt(inode->i_sb, DELALLOC))) {
/* We do not support data journalling for encrypted data */
if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode))
return EXT4_INODE_ORDERED_DATA_MODE; /* ordered */
return EXT4_INODE_JOURNAL_DATA_MODE; /* journal data */
}
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
return EXT4_INODE_ORDERED_DATA_MODE; /* ordered */
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */
BUG();
}
/* Just increment the non-pointer handle value */
static handle_t *ext4_get_nojournal(void)
{
handle_t *handle = current->journal_info;
unsigned long ref_cnt = (unsigned long)handle;
BUG_ON(ref_cnt >= EXT4_NOJOURNAL_MAX_REF_COUNT);
ref_cnt++;
handle = (handle_t *)ref_cnt;
current->journal_info = handle;
return handle;
}
/* Decrement the non-pointer handle value */
static void ext4_put_nojournal(handle_t *handle)
{
unsigned long ref_cnt = (unsigned long)handle;
BUG_ON(ref_cnt == 0);
ref_cnt--;
handle = (handle_t *)ref_cnt;
current->journal_info = handle;
}
/*
* Wrappers for jbd2_journal_start/end.
*/
static int ext4_journal_check_start(struct super_block *sb)
{
journal_t *journal;
might_sleep();
if (unlikely(ext4_forced_shutdown(sb)))
return -EIO;
if (WARN_ON_ONCE(sb_rdonly(sb)))
return -EROFS;
WARN_ON(sb->s_writers.frozen == SB_FREEZE_COMPLETE);
journal = EXT4_SB(sb)->s_journal;
/*
* Special case here: if the journal has aborted behind our
* backs (eg. EIO in the commit thread), then we still need to
* take the FS itself readonly cleanly.
*/
if (journal && is_journal_aborted(journal)) {
ext4_abort(sb, -journal->j_errno, "Detected aborted journal");
return -EROFS;
}
return 0;
}
handle_t *__ext4_journal_start_sb(struct inode *inode,
struct super_block *sb, unsigned int line,
int type, int blocks, int rsv_blocks,
int revoke_creds)
{
journal_t *journal;
int err;
if (inode)
trace_ext4_journal_start_inode(inode, blocks, rsv_blocks,
revoke_creds, type,
_RET_IP_);
else
trace_ext4_journal_start_sb(sb, blocks, rsv_blocks,
revoke_creds, type,
_RET_IP_);
err = ext4_journal_check_start(sb);
if (err < 0)
return ERR_PTR(err);
journal = EXT4_SB(sb)->s_journal;
if (!journal || (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))
return ext4_get_nojournal();
return jbd2__journal_start(journal, blocks, rsv_blocks, revoke_creds,
GFP_NOFS, type, line);
}
int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
err = handle->h_err;
if (!handle->h_transaction) {
rc = jbd2_journal_stop(handle);
return err ? err : rc;
}
sb = handle->h_transaction->t_journal->j_private;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line,
int type)
{
struct super_block *sb;
int err;
if (!ext4_handle_valid(handle))
return ext4_get_nojournal();
sb = handle->h_journal->j_private;
trace_ext4_journal_start_reserved(sb,
jbd2_handle_buffer_credits(handle), _RET_IP_);
err = ext4_journal_check_start(sb);
if (err < 0) {
jbd2_journal_free_reserved(handle);
return ERR_PTR(err);
}
err = jbd2_journal_start_reserved(handle, type, line);
if (err < 0)
return ERR_PTR(err);
return handle;
}
int __ext4_journal_ensure_credits(handle_t *handle, int check_cred,
int extend_cred, int revoke_cred)
{
if (!ext4_handle_valid(handle))
return 0;
if (is_handle_aborted(handle))
return -EROFS;
if (jbd2_handle_buffer_credits(handle) >= check_cred &&
handle->h_revoke_credits >= revoke_cred)
return 0;
extend_cred = max(0, extend_cred - jbd2_handle_buffer_credits(handle));
revoke_cred = max(0, revoke_cred - handle->h_revoke_credits);
return ext4_journal_extend(handle, extend_cred, revoke_cred);
}
static void ext4_journal_abort_handle(const char *caller, unsigned int line,
const char *err_fn,
struct buffer_head *bh,
handle_t *handle, int err)
{
char nbuf[16];
const char *errstr = ext4_decode_error(NULL, err, nbuf);
BUG_ON(!ext4_handle_valid(handle));
if (bh)
BUFFER_TRACE(bh, "abort");
if (!handle->h_err)
handle->h_err = err;
if (is_handle_aborted(handle))
return;
printk(KERN_ERR "EXT4-fs: %s:%d: aborting transaction: %s in %s\n",
caller, line, errstr, err_fn);
jbd2_journal_abort_handle(handle);
}
static void ext4_check_bdev_write_error(struct super_block *sb)
{
struct address_space *mapping = sb->s_bdev->bd_inode->i_mapping;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err;
/*
* If the block device has write error flag, it may have failed to
* async write out metadata buffers in the background. In this case,
* we could read old data from disk and write it out again, which
* may lead to on-disk filesystem inconsistency.
*/
if (errseq_check(&mapping->wb_err, READ_ONCE(sbi->s_bdev_wb_err))) {
spin_lock(&sbi->s_bdev_wb_lock);
err = errseq_check_and_advance(&mapping->wb_err, &sbi->s_bdev_wb_err);
spin_unlock(&sbi->s_bdev_wb_lock);
if (err)
ext4_error_err(sb, -err,
"Error while async write back metadata");
}
}
int __ext4_journal_get_write_access(const char *where, unsigned int line,
handle_t *handle, struct super_block *sb,
struct buffer_head *bh,
enum ext4_journal_trigger_type trigger_type)
{
int err;
might_sleep();
ext4_check_bdev_write_error(sb);
if (ext4_handle_valid(handle)) {
err = jbd2_journal_get_write_access(handle, bh);
if (err) {
ext4_journal_abort_handle(where, line, __func__, bh,
handle, err);
return err;
}
}
if (trigger_type == EXT4_JTR_NONE || !ext4_has_metadata_csum(sb))
return 0;
BUG_ON(trigger_type >= EXT4_JOURNAL_TRIGGER_COUNT);
jbd2_journal_set_triggers(bh,
&EXT4_SB(sb)->s_journal_triggers[trigger_type].tr_triggers);
return 0;
}
/*
* The ext4 forget function must perform a revoke if we are freeing data
* which has been journaled. Metadata (eg. indirect blocks) must be
* revoked in all cases.
*
* "bh" may be NULL: a metadata block may have been freed from memory
* but there may still be a record of it in the journal, and that record
* still needs to be revoked.
*/
int __ext4_forget(const char *where, unsigned int line, handle_t *handle,
int is_metadata, struct inode *inode,
struct buffer_head *bh, ext4_fsblk_t blocknr)
{
int err;
might_sleep();
trace_ext4_forget(inode, is_metadata, blocknr);
BUFFER_TRACE(bh, "enter");
ext4_debug("forgetting bh %p: is_metadata=%d, mode %o, data mode %x\n",
bh, is_metadata, inode->i_mode,
test_opt(inode->i_sb, DATA_FLAGS));
/* In the no journal case, we can just do a bforget and return */
if (!ext4_handle_valid(handle)) {
bforget(bh);
return 0;
}
/* Never use the revoke function if we are doing full data
* journaling: there is no need to, and a V1 superblock won't
* support it. Otherwise, only skip the revoke on un-journaled
* data blocks. */
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
(!is_metadata && !ext4_should_journal_data(inode))) {
if (bh) {
BUFFER_TRACE(bh, "call jbd2_journal_forget");
err = jbd2_journal_forget(handle, bh);
if (err)
ext4_journal_abort_handle(where, line, __func__,
bh, handle, err);
return err;
}
return 0;
}
/*
* data!=journal && (is_metadata || should_journal_data(inode))
*/
BUFFER_TRACE(bh, "call jbd2_journal_revoke");
err = jbd2_journal_revoke(handle, blocknr, bh);
if (err) {
ext4_journal_abort_handle(where, line, __func__,
bh, handle, err);
__ext4_error(inode->i_sb, where, line, true, -err, 0,
"error %d when attempting revoke", err);
}
BUFFER_TRACE(bh, "exit");
return err;
}
int __ext4_journal_get_create_access(const char *where, unsigned int line,
handle_t *handle, struct super_block *sb,
struct buffer_head *bh,
enum ext4_journal_trigger_type trigger_type)
{
int err;
if (!ext4_handle_valid(handle))
return 0;
err = jbd2_journal_get_create_access(handle, bh);
if (err) {
ext4_journal_abort_handle(where, line, __func__, bh, handle,
err);
return err;
}
if (trigger_type == EXT4_JTR_NONE || !ext4_has_metadata_csum(sb))
return 0;
BUG_ON(trigger_type >= EXT4_JOURNAL_TRIGGER_COUNT);
jbd2_journal_set_triggers(bh,
&EXT4_SB(sb)->s_journal_triggers[trigger_type].tr_triggers);
return 0;
}
int __ext4_handle_dirty_metadata(const char *where, unsigned int line,
handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
int err = 0;
might_sleep();
set_buffer_meta(bh);
set_buffer_prio(bh);
set_buffer_uptodate(bh);
if (ext4_handle_valid(handle)) {
err = jbd2_journal_dirty_metadata(handle, bh);
/* Errors can only happen due to aborted journal or a nasty bug */
if (!is_handle_aborted(handle) && WARN_ON_ONCE(err)) {
ext4_journal_abort_handle(where, line, __func__, bh,
handle, err);
if (inode == NULL) {
pr_err("EXT4: jbd2_journal_dirty_metadata "
"failed: handle type %u started at "
"line %u, credits %u/%u, errcode %d",
handle->h_type,
handle->h_line_no,
handle->h_requested_credits,
jbd2_handle_buffer_credits(handle), err);
return err;
}
ext4_error_inode(inode, where, line,
bh->b_blocknr,
"journal_dirty_metadata failed: "
"handle type %u started at line %u, "
"credits %u/%u, errcode %d",
handle->h_type,
handle->h_line_no,
handle->h_requested_credits,
jbd2_handle_buffer_credits(handle),
err);
}
} else {
if (inode)
mark_buffer_dirty_inode(bh, inode);
else
mark_buffer_dirty(bh);
if (inode && inode_needs_sync(inode)) {
sync_dirty_buffer(bh);
if (buffer_req(bh) && !buffer_uptodate(bh)) {
ext4_error_inode_err(inode, where, line,
bh->b_blocknr, EIO,
"IO error syncing itable block");
err = -EIO;
}
}
}
return err;
}
| linux-master | fs/ext4/ext4_jbd2.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/page-io.c
*
* This contains the new page_io functions for ext4
*
* Written by Theodore Ts'o, 2010.
*/
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include <linux/pagevec.h>
#include <linux/mpage.h>
#include <linux/namei.h>
#include <linux/uio.h>
#include <linux/bio.h>
#include <linux/workqueue.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/sched/mm.h>
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
static struct kmem_cache *io_end_cachep;
static struct kmem_cache *io_end_vec_cachep;
int __init ext4_init_pageio(void)
{
io_end_cachep = KMEM_CACHE(ext4_io_end, SLAB_RECLAIM_ACCOUNT);
if (io_end_cachep == NULL)
return -ENOMEM;
io_end_vec_cachep = KMEM_CACHE(ext4_io_end_vec, 0);
if (io_end_vec_cachep == NULL) {
kmem_cache_destroy(io_end_cachep);
return -ENOMEM;
}
return 0;
}
void ext4_exit_pageio(void)
{
kmem_cache_destroy(io_end_cachep);
kmem_cache_destroy(io_end_vec_cachep);
}
struct ext4_io_end_vec *ext4_alloc_io_end_vec(ext4_io_end_t *io_end)
{
struct ext4_io_end_vec *io_end_vec;
io_end_vec = kmem_cache_zalloc(io_end_vec_cachep, GFP_NOFS);
if (!io_end_vec)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&io_end_vec->list);
list_add_tail(&io_end_vec->list, &io_end->list_vec);
return io_end_vec;
}
static void ext4_free_io_end_vec(ext4_io_end_t *io_end)
{
struct ext4_io_end_vec *io_end_vec, *tmp;
if (list_empty(&io_end->list_vec))
return;
list_for_each_entry_safe(io_end_vec, tmp, &io_end->list_vec, list) {
list_del(&io_end_vec->list);
kmem_cache_free(io_end_vec_cachep, io_end_vec);
}
}
struct ext4_io_end_vec *ext4_last_io_end_vec(ext4_io_end_t *io_end)
{
BUG_ON(list_empty(&io_end->list_vec));
return list_last_entry(&io_end->list_vec, struct ext4_io_end_vec, list);
}
/*
* Print an buffer I/O error compatible with the fs/buffer.c. This
* provides compatibility with dmesg scrapers that look for a specific
* buffer I/O error message. We really need a unified error reporting
* structure to userspace ala Digital Unix's uerf system, but it's
* probably not going to happen in my lifetime, due to LKML politics...
*/
static void buffer_io_error(struct buffer_head *bh)
{
printk_ratelimited(KERN_ERR "Buffer I/O error on device %pg, logical block %llu\n",
bh->b_bdev,
(unsigned long long)bh->b_blocknr);
}
static void ext4_finish_bio(struct bio *bio)
{
struct folio_iter fi;
bio_for_each_folio_all(fi, bio) {
struct folio *folio = fi.folio;
struct folio *io_folio = NULL;
struct buffer_head *bh, *head;
size_t bio_start = fi.offset;
size_t bio_end = bio_start + fi.length;
unsigned under_io = 0;
unsigned long flags;
if (fscrypt_is_bounce_folio(folio)) {
io_folio = folio;
folio = fscrypt_pagecache_folio(folio);
}
if (bio->bi_status) {
int err = blk_status_to_errno(bio->bi_status);
folio_set_error(folio);
mapping_set_error(folio->mapping, err);
}
bh = head = folio_buffers(folio);
/*
* We check all buffers in the folio under b_uptodate_lock
* to avoid races with other end io clearing async_write flags
*/
spin_lock_irqsave(&head->b_uptodate_lock, flags);
do {
if (bh_offset(bh) < bio_start ||
bh_offset(bh) + bh->b_size > bio_end) {
if (buffer_async_write(bh))
under_io++;
continue;
}
clear_buffer_async_write(bh);
if (bio->bi_status) {
set_buffer_write_io_error(bh);
buffer_io_error(bh);
}
} while ((bh = bh->b_this_page) != head);
spin_unlock_irqrestore(&head->b_uptodate_lock, flags);
if (!under_io) {
fscrypt_free_bounce_page(&io_folio->page);
folio_end_writeback(folio);
}
}
}
static void ext4_release_io_end(ext4_io_end_t *io_end)
{
struct bio *bio, *next_bio;
BUG_ON(!list_empty(&io_end->list));
BUG_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
WARN_ON(io_end->handle);
for (bio = io_end->bio; bio; bio = next_bio) {
next_bio = bio->bi_private;
ext4_finish_bio(bio);
bio_put(bio);
}
ext4_free_io_end_vec(io_end);
kmem_cache_free(io_end_cachep, io_end);
}
/*
* Check a range of space and convert unwritten extents to written. Note that
* we are protected from truncate touching same part of extent tree by the
* fact that truncate code waits for all DIO to finish (thus exclusion from
* direct IO is achieved) and also waits for PageWriteback bits. Thus we
* cannot get to ext4_ext_truncate() before all IOs overlapping that range are
* completed (happens from ext4_free_ioend()).
*/
static int ext4_end_io_end(ext4_io_end_t *io_end)
{
struct inode *inode = io_end->inode;
handle_t *handle = io_end->handle;
int ret = 0;
ext4_debug("ext4_end_io_nolock: io_end 0x%p from inode %lu,list->next 0x%p,"
"list->prev 0x%p\n",
io_end, inode->i_ino, io_end->list.next, io_end->list.prev);
io_end->handle = NULL; /* Following call will use up the handle */
ret = ext4_convert_unwritten_io_end_vec(handle, io_end);
if (ret < 0 && !ext4_forced_shutdown(inode->i_sb)) {
ext4_msg(inode->i_sb, KERN_EMERG,
"failed to convert unwritten extents to written "
"extents -- potential data loss! "
"(inode %lu, error %d)", inode->i_ino, ret);
}
ext4_clear_io_unwritten_flag(io_end);
ext4_release_io_end(io_end);
return ret;
}
static void dump_completed_IO(struct inode *inode, struct list_head *head)
{
#ifdef EXT4FS_DEBUG
struct list_head *cur, *before, *after;
ext4_io_end_t *io_end, *io_end0, *io_end1;
if (list_empty(head))
return;
ext4_debug("Dump inode %lu completed io list\n", inode->i_ino);
list_for_each_entry(io_end, head, list) {
cur = &io_end->list;
before = cur->prev;
io_end0 = container_of(before, ext4_io_end_t, list);
after = cur->next;
io_end1 = container_of(after, ext4_io_end_t, list);
ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
io_end, inode->i_ino, io_end0, io_end1);
}
#endif
}
/* Add the io_end to per-inode completed end_io list. */
static void ext4_add_complete_io(ext4_io_end_t *io_end)
{
struct ext4_inode_info *ei = EXT4_I(io_end->inode);
struct ext4_sb_info *sbi = EXT4_SB(io_end->inode->i_sb);
struct workqueue_struct *wq;
unsigned long flags;
/* Only reserved conversions from writeback should enter here */
WARN_ON(!(io_end->flag & EXT4_IO_END_UNWRITTEN));
WARN_ON(!io_end->handle && sbi->s_journal);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
wq = sbi->rsv_conversion_wq;
if (list_empty(&ei->i_rsv_conversion_list))
queue_work(wq, &ei->i_rsv_conversion_work);
list_add_tail(&io_end->list, &ei->i_rsv_conversion_list);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
}
static int ext4_do_flush_completed_IO(struct inode *inode,
struct list_head *head)
{
ext4_io_end_t *io_end;
struct list_head unwritten;
unsigned long flags;
struct ext4_inode_info *ei = EXT4_I(inode);
int err, ret = 0;
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
dump_completed_IO(inode, head);
list_replace_init(head, &unwritten);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
while (!list_empty(&unwritten)) {
io_end = list_entry(unwritten.next, ext4_io_end_t, list);
BUG_ON(!(io_end->flag & EXT4_IO_END_UNWRITTEN));
list_del_init(&io_end->list);
err = ext4_end_io_end(io_end);
if (unlikely(!ret && err))
ret = err;
}
return ret;
}
/*
* work on completed IO, to convert unwritten extents to extents
*/
void ext4_end_io_rsv_work(struct work_struct *work)
{
struct ext4_inode_info *ei = container_of(work, struct ext4_inode_info,
i_rsv_conversion_work);
ext4_do_flush_completed_IO(&ei->vfs_inode, &ei->i_rsv_conversion_list);
}
ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags)
{
ext4_io_end_t *io_end = kmem_cache_zalloc(io_end_cachep, flags);
if (io_end) {
io_end->inode = inode;
INIT_LIST_HEAD(&io_end->list);
INIT_LIST_HEAD(&io_end->list_vec);
refcount_set(&io_end->count, 1);
}
return io_end;
}
void ext4_put_io_end_defer(ext4_io_end_t *io_end)
{
if (refcount_dec_and_test(&io_end->count)) {
if (!(io_end->flag & EXT4_IO_END_UNWRITTEN) ||
list_empty(&io_end->list_vec)) {
ext4_release_io_end(io_end);
return;
}
ext4_add_complete_io(io_end);
}
}
int ext4_put_io_end(ext4_io_end_t *io_end)
{
int err = 0;
if (refcount_dec_and_test(&io_end->count)) {
if (io_end->flag & EXT4_IO_END_UNWRITTEN) {
err = ext4_convert_unwritten_io_end_vec(io_end->handle,
io_end);
io_end->handle = NULL;
ext4_clear_io_unwritten_flag(io_end);
}
ext4_release_io_end(io_end);
}
return err;
}
ext4_io_end_t *ext4_get_io_end(ext4_io_end_t *io_end)
{
refcount_inc(&io_end->count);
return io_end;
}
/* BIO completion function for page writeback */
static void ext4_end_bio(struct bio *bio)
{
ext4_io_end_t *io_end = bio->bi_private;
sector_t bi_sector = bio->bi_iter.bi_sector;
if (WARN_ONCE(!io_end, "io_end is NULL: %pg: sector %Lu len %u err %d\n",
bio->bi_bdev,
(long long) bio->bi_iter.bi_sector,
(unsigned) bio_sectors(bio),
bio->bi_status)) {
ext4_finish_bio(bio);
bio_put(bio);
return;
}
bio->bi_end_io = NULL;
if (bio->bi_status) {
struct inode *inode = io_end->inode;
ext4_warning(inode->i_sb, "I/O error %d writing to inode %lu "
"starting block %llu)",
bio->bi_status, inode->i_ino,
(unsigned long long)
bi_sector >> (inode->i_blkbits - 9));
mapping_set_error(inode->i_mapping,
blk_status_to_errno(bio->bi_status));
}
if (io_end->flag & EXT4_IO_END_UNWRITTEN) {
/*
* Link bio into list hanging from io_end. We have to do it
* atomically as bio completions can be racing against each
* other.
*/
bio->bi_private = xchg(&io_end->bio, bio);
ext4_put_io_end_defer(io_end);
} else {
/*
* Drop io_end reference early. Inode can get freed once
* we finish the bio.
*/
ext4_put_io_end_defer(io_end);
ext4_finish_bio(bio);
bio_put(bio);
}
}
void ext4_io_submit(struct ext4_io_submit *io)
{
struct bio *bio = io->io_bio;
if (bio) {
if (io->io_wbc->sync_mode == WB_SYNC_ALL)
io->io_bio->bi_opf |= REQ_SYNC;
submit_bio(io->io_bio);
}
io->io_bio = NULL;
}
void ext4_io_submit_init(struct ext4_io_submit *io,
struct writeback_control *wbc)
{
io->io_wbc = wbc;
io->io_bio = NULL;
io->io_end = NULL;
}
static void io_submit_init_bio(struct ext4_io_submit *io,
struct buffer_head *bh)
{
struct bio *bio;
/*
* bio_alloc will _always_ be able to allocate a bio if
* __GFP_DIRECT_RECLAIM is set, see comments for bio_alloc_bioset().
*/
bio = bio_alloc(bh->b_bdev, BIO_MAX_VECS, REQ_OP_WRITE, GFP_NOIO);
fscrypt_set_bio_crypt_ctx_bh(bio, bh, GFP_NOIO);
bio->bi_iter.bi_sector = bh->b_blocknr * (bh->b_size >> 9);
bio->bi_end_io = ext4_end_bio;
bio->bi_private = ext4_get_io_end(io->io_end);
io->io_bio = bio;
io->io_next_block = bh->b_blocknr;
wbc_init_bio(io->io_wbc, bio);
}
static void io_submit_add_bh(struct ext4_io_submit *io,
struct inode *inode,
struct folio *folio,
struct folio *io_folio,
struct buffer_head *bh)
{
if (io->io_bio && (bh->b_blocknr != io->io_next_block ||
!fscrypt_mergeable_bio_bh(io->io_bio, bh))) {
submit_and_retry:
ext4_io_submit(io);
}
if (io->io_bio == NULL)
io_submit_init_bio(io, bh);
if (!bio_add_folio(io->io_bio, io_folio, bh->b_size, bh_offset(bh)))
goto submit_and_retry;
wbc_account_cgroup_owner(io->io_wbc, &folio->page, bh->b_size);
io->io_next_block++;
}
int ext4_bio_write_folio(struct ext4_io_submit *io, struct folio *folio,
size_t len)
{
struct folio *io_folio = folio;
struct inode *inode = folio->mapping->host;
unsigned block_start;
struct buffer_head *bh, *head;
int ret = 0;
int nr_to_submit = 0;
struct writeback_control *wbc = io->io_wbc;
bool keep_towrite = false;
BUG_ON(!folio_test_locked(folio));
BUG_ON(folio_test_writeback(folio));
folio_clear_error(folio);
/*
* Comments copied from block_write_full_page:
*
* The folio straddles i_size. It must be zeroed out on each and every
* writepage invocation because it may be mmapped. "A file is mapped
* in multiples of the page size. For a file that is not a multiple of
* the page size, the remaining memory is zeroed when mapped, and
* writes to that region are not written out to the file."
*/
if (len < folio_size(folio))
folio_zero_segment(folio, len, folio_size(folio));
/*
* In the first loop we prepare and mark buffers to submit. We have to
* mark all buffers in the folio before submitting so that
* folio_end_writeback() cannot be called from ext4_end_bio() when IO
* on the first buffer finishes and we are still working on submitting
* the second buffer.
*/
bh = head = folio_buffers(folio);
do {
block_start = bh_offset(bh);
if (block_start >= len) {
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
continue;
}
if (!buffer_dirty(bh) || buffer_delay(bh) ||
!buffer_mapped(bh) || buffer_unwritten(bh)) {
/* A hole? We can safely clear the dirty bit */
if (!buffer_mapped(bh))
clear_buffer_dirty(bh);
/*
* Keeping dirty some buffer we cannot write? Make sure
* to redirty the folio and keep TOWRITE tag so that
* racing WB_SYNC_ALL writeback does not skip the folio.
* This happens e.g. when doing writeout for
* transaction commit or when journalled data is not
* yet committed.
*/
if (buffer_dirty(bh) ||
(buffer_jbd(bh) && buffer_jbddirty(bh))) {
if (!folio_test_dirty(folio))
folio_redirty_for_writepage(wbc, folio);
keep_towrite = true;
}
continue;
}
if (buffer_new(bh))
clear_buffer_new(bh);
set_buffer_async_write(bh);
clear_buffer_dirty(bh);
nr_to_submit++;
} while ((bh = bh->b_this_page) != head);
/* Nothing to submit? Just unlock the folio... */
if (!nr_to_submit)
return 0;
bh = head = folio_buffers(folio);
/*
* If any blocks are being written to an encrypted file, encrypt them
* into a bounce page. For simplicity, just encrypt until the last
* block which might be needed. This may cause some unneeded blocks
* (e.g. holes) to be unnecessarily encrypted, but this is rare and
* can't happen in the common case of blocksize == PAGE_SIZE.
*/
if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
gfp_t gfp_flags = GFP_NOFS;
unsigned int enc_bytes = round_up(len, i_blocksize(inode));
struct page *bounce_page;
/*
* Since bounce page allocation uses a mempool, we can only use
* a waiting mask (i.e. request guaranteed allocation) on the
* first page of the bio. Otherwise it can deadlock.
*/
if (io->io_bio)
gfp_flags = GFP_NOWAIT | __GFP_NOWARN;
retry_encrypt:
bounce_page = fscrypt_encrypt_pagecache_blocks(&folio->page,
enc_bytes, 0, gfp_flags);
if (IS_ERR(bounce_page)) {
ret = PTR_ERR(bounce_page);
if (ret == -ENOMEM &&
(io->io_bio || wbc->sync_mode == WB_SYNC_ALL)) {
gfp_t new_gfp_flags = GFP_NOFS;
if (io->io_bio)
ext4_io_submit(io);
else
new_gfp_flags |= __GFP_NOFAIL;
memalloc_retry_wait(gfp_flags);
gfp_flags = new_gfp_flags;
goto retry_encrypt;
}
printk_ratelimited(KERN_ERR "%s: ret = %d\n", __func__, ret);
folio_redirty_for_writepage(wbc, folio);
do {
if (buffer_async_write(bh)) {
clear_buffer_async_write(bh);
set_buffer_dirty(bh);
}
bh = bh->b_this_page;
} while (bh != head);
return ret;
}
io_folio = page_folio(bounce_page);
}
__folio_start_writeback(folio, keep_towrite);
/* Now submit buffers to write */
do {
if (!buffer_async_write(bh))
continue;
io_submit_add_bh(io, inode, folio, io_folio, bh);
} while ((bh = bh->b_this_page) != head);
return 0;
}
| linux-master | fs/ext4/page-io.c |
// SPDX-License-Identifier: LGPL-2.1
/*
* Copyright (c) 2008,2009 NEC Software Tohoku, Ltd.
* Written by Takashi Sato <[email protected]>
* Akira Fujita <[email protected]>
*/
#include <linux/fs.h>
#include <linux/quotaops.h>
#include <linux/slab.h>
#include <linux/sched/mm.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "ext4_extents.h"
/**
* get_ext_path() - Find an extent path for designated logical block number.
* @inode: inode to be searched
* @lblock: logical block number to find an extent path
* @ppath: pointer to an extent path pointer (for output)
*
* ext4_find_extent wrapper. Return 0 on success, or a negative error value
* on failure.
*/
static inline int
get_ext_path(struct inode *inode, ext4_lblk_t lblock,
struct ext4_ext_path **ppath)
{
struct ext4_ext_path *path;
path = ext4_find_extent(inode, lblock, ppath, EXT4_EX_NOCACHE);
if (IS_ERR(path))
return PTR_ERR(path);
if (path[ext_depth(inode)].p_ext == NULL) {
ext4_free_ext_path(path);
*ppath = NULL;
return -ENODATA;
}
*ppath = path;
return 0;
}
/**
* ext4_double_down_write_data_sem() - write lock two inodes's i_data_sem
* @first: inode to be locked
* @second: inode to be locked
*
* Acquire write lock of i_data_sem of the two inodes
*/
void
ext4_double_down_write_data_sem(struct inode *first, struct inode *second)
{
if (first < second) {
down_write(&EXT4_I(first)->i_data_sem);
down_write_nested(&EXT4_I(second)->i_data_sem, I_DATA_SEM_OTHER);
} else {
down_write(&EXT4_I(second)->i_data_sem);
down_write_nested(&EXT4_I(first)->i_data_sem, I_DATA_SEM_OTHER);
}
}
/**
* ext4_double_up_write_data_sem - Release two inodes' write lock of i_data_sem
*
* @orig_inode: original inode structure to be released its lock first
* @donor_inode: donor inode structure to be released its lock second
* Release write lock of i_data_sem of two inodes (orig and donor).
*/
void
ext4_double_up_write_data_sem(struct inode *orig_inode,
struct inode *donor_inode)
{
up_write(&EXT4_I(orig_inode)->i_data_sem);
up_write(&EXT4_I(donor_inode)->i_data_sem);
}
/**
* mext_check_coverage - Check that all extents in range has the same type
*
* @inode: inode in question
* @from: block offset of inode
* @count: block count to be checked
* @unwritten: extents expected to be unwritten
* @err: pointer to save error value
*
* Return 1 if all extents in range has expected type, and zero otherwise.
*/
static int
mext_check_coverage(struct inode *inode, ext4_lblk_t from, ext4_lblk_t count,
int unwritten, int *err)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ext;
int ret = 0;
ext4_lblk_t last = from + count;
while (from < last) {
*err = get_ext_path(inode, from, &path);
if (*err)
goto out;
ext = path[ext_depth(inode)].p_ext;
if (unwritten != ext4_ext_is_unwritten(ext))
goto out;
from += ext4_ext_get_actual_len(ext);
}
ret = 1;
out:
ext4_free_ext_path(path);
return ret;
}
/**
* mext_folio_double_lock - Grab and lock folio on both @inode1 and @inode2
*
* @inode1: the inode structure
* @inode2: the inode structure
* @index1: folio index
* @index2: folio index
* @folio: result folio vector
*
* Grab two locked folio for inode's by inode order
*/
static int
mext_folio_double_lock(struct inode *inode1, struct inode *inode2,
pgoff_t index1, pgoff_t index2, struct folio *folio[2])
{
struct address_space *mapping[2];
unsigned int flags;
BUG_ON(!inode1 || !inode2);
if (inode1 < inode2) {
mapping[0] = inode1->i_mapping;
mapping[1] = inode2->i_mapping;
} else {
swap(index1, index2);
mapping[0] = inode2->i_mapping;
mapping[1] = inode1->i_mapping;
}
flags = memalloc_nofs_save();
folio[0] = __filemap_get_folio(mapping[0], index1, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping[0]));
if (IS_ERR(folio[0])) {
memalloc_nofs_restore(flags);
return PTR_ERR(folio[0]);
}
folio[1] = __filemap_get_folio(mapping[1], index2, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping[1]));
memalloc_nofs_restore(flags);
if (IS_ERR(folio[1])) {
folio_unlock(folio[0]);
folio_put(folio[0]);
return PTR_ERR(folio[1]);
}
/*
* __filemap_get_folio() may not wait on folio's writeback if
* BDI not demand that. But it is reasonable to be very conservative
* here and explicitly wait on folio's writeback
*/
folio_wait_writeback(folio[0]);
folio_wait_writeback(folio[1]);
if (inode1 > inode2)
swap(folio[0], folio[1]);
return 0;
}
/* Force page buffers uptodate w/o dropping page's lock */
static int
mext_page_mkuptodate(struct folio *folio, unsigned from, unsigned to)
{
struct inode *inode = folio->mapping->host;
sector_t block;
struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
unsigned int blocksize, block_start, block_end;
int i, err, nr = 0, partial = 0;
BUG_ON(!folio_test_locked(folio));
BUG_ON(folio_test_writeback(folio));
if (folio_test_uptodate(folio))
return 0;
blocksize = i_blocksize(inode);
head = folio_buffers(folio);
if (!head) {
create_empty_buffers(&folio->page, blocksize, 0);
head = folio_buffers(folio);
}
block = (sector_t)folio->index << (PAGE_SHIFT - inode->i_blkbits);
for (bh = head, block_start = 0; bh != head || !block_start;
block++, block_start = block_end, bh = bh->b_this_page) {
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (!buffer_uptodate(bh))
partial = 1;
continue;
}
if (buffer_uptodate(bh))
continue;
if (!buffer_mapped(bh)) {
err = ext4_get_block(inode, block, bh, 0);
if (err) {
folio_set_error(folio);
return err;
}
if (!buffer_mapped(bh)) {
folio_zero_range(folio, block_start, blocksize);
set_buffer_uptodate(bh);
continue;
}
}
BUG_ON(nr >= MAX_BUF_PER_PAGE);
arr[nr++] = bh;
}
/* No io required */
if (!nr)
goto out;
for (i = 0; i < nr; i++) {
bh = arr[i];
if (!bh_uptodate_or_lock(bh)) {
err = ext4_read_bh(bh, 0, NULL);
if (err)
return err;
}
}
out:
if (!partial)
folio_mark_uptodate(folio);
return 0;
}
/**
* move_extent_per_page - Move extent data per page
*
* @o_filp: file structure of original file
* @donor_inode: donor inode
* @orig_page_offset: page index on original file
* @donor_page_offset: page index on donor file
* @data_offset_in_page: block index where data swapping starts
* @block_len_in_page: the number of blocks to be swapped
* @unwritten: orig extent is unwritten or not
* @err: pointer to save return value
*
* Save the data in original inode blocks and replace original inode extents
* with donor inode extents by calling ext4_swap_extents().
* Finally, write out the saved data in new original inode blocks. Return
* replaced block count.
*/
static int
move_extent_per_page(struct file *o_filp, struct inode *donor_inode,
pgoff_t orig_page_offset, pgoff_t donor_page_offset,
int data_offset_in_page,
int block_len_in_page, int unwritten, int *err)
{
struct inode *orig_inode = file_inode(o_filp);
struct folio *folio[2] = {NULL, NULL};
handle_t *handle;
ext4_lblk_t orig_blk_offset, donor_blk_offset;
unsigned long blocksize = orig_inode->i_sb->s_blocksize;
unsigned int tmp_data_size, data_size, replaced_size;
int i, err2, jblocks, retries = 0;
int replaced_count = 0;
int from = data_offset_in_page << orig_inode->i_blkbits;
int blocks_per_page = PAGE_SIZE >> orig_inode->i_blkbits;
struct super_block *sb = orig_inode->i_sb;
struct buffer_head *bh = NULL;
/*
* It needs twice the amount of ordinary journal buffers because
* inode and donor_inode may change each different metadata blocks.
*/
again:
*err = 0;
jblocks = ext4_writepage_trans_blocks(orig_inode) * 2;
handle = ext4_journal_start(orig_inode, EXT4_HT_MOVE_EXTENTS, jblocks);
if (IS_ERR(handle)) {
*err = PTR_ERR(handle);
return 0;
}
orig_blk_offset = orig_page_offset * blocks_per_page +
data_offset_in_page;
donor_blk_offset = donor_page_offset * blocks_per_page +
data_offset_in_page;
/* Calculate data_size */
if ((orig_blk_offset + block_len_in_page - 1) ==
((orig_inode->i_size - 1) >> orig_inode->i_blkbits)) {
/* Replace the last block */
tmp_data_size = orig_inode->i_size & (blocksize - 1);
/*
* If data_size equal zero, it shows data_size is multiples of
* blocksize. So we set appropriate value.
*/
if (tmp_data_size == 0)
tmp_data_size = blocksize;
data_size = tmp_data_size +
((block_len_in_page - 1) << orig_inode->i_blkbits);
} else
data_size = block_len_in_page << orig_inode->i_blkbits;
replaced_size = data_size;
*err = mext_folio_double_lock(orig_inode, donor_inode, orig_page_offset,
donor_page_offset, folio);
if (unlikely(*err < 0))
goto stop_journal;
/*
* If orig extent was unwritten it can become initialized
* at any time after i_data_sem was dropped, in order to
* serialize with delalloc we have recheck extent while we
* hold page's lock, if it is still the case data copy is not
* necessary, just swap data blocks between orig and donor.
*/
VM_BUG_ON_FOLIO(folio_test_large(folio[0]), folio[0]);
VM_BUG_ON_FOLIO(folio_test_large(folio[1]), folio[1]);
VM_BUG_ON_FOLIO(folio_nr_pages(folio[0]) != folio_nr_pages(folio[1]), folio[1]);
if (unwritten) {
ext4_double_down_write_data_sem(orig_inode, donor_inode);
/* If any of extents in range became initialized we have to
* fallback to data copying */
unwritten = mext_check_coverage(orig_inode, orig_blk_offset,
block_len_in_page, 1, err);
if (*err)
goto drop_data_sem;
unwritten &= mext_check_coverage(donor_inode, donor_blk_offset,
block_len_in_page, 1, err);
if (*err)
goto drop_data_sem;
if (!unwritten) {
ext4_double_up_write_data_sem(orig_inode, donor_inode);
goto data_copy;
}
if (!filemap_release_folio(folio[0], 0) ||
!filemap_release_folio(folio[1], 0)) {
*err = -EBUSY;
goto drop_data_sem;
}
replaced_count = ext4_swap_extents(handle, orig_inode,
donor_inode, orig_blk_offset,
donor_blk_offset,
block_len_in_page, 1, err);
drop_data_sem:
ext4_double_up_write_data_sem(orig_inode, donor_inode);
goto unlock_folios;
}
data_copy:
*err = mext_page_mkuptodate(folio[0], from, from + replaced_size);
if (*err)
goto unlock_folios;
/* At this point all buffers in range are uptodate, old mapping layout
* is no longer required, try to drop it now. */
if (!filemap_release_folio(folio[0], 0) ||
!filemap_release_folio(folio[1], 0)) {
*err = -EBUSY;
goto unlock_folios;
}
ext4_double_down_write_data_sem(orig_inode, donor_inode);
replaced_count = ext4_swap_extents(handle, orig_inode, donor_inode,
orig_blk_offset, donor_blk_offset,
block_len_in_page, 1, err);
ext4_double_up_write_data_sem(orig_inode, donor_inode);
if (*err) {
if (replaced_count) {
block_len_in_page = replaced_count;
replaced_size =
block_len_in_page << orig_inode->i_blkbits;
} else
goto unlock_folios;
}
/* Perform all necessary steps similar write_begin()/write_end()
* but keeping in mind that i_size will not change */
if (!folio_buffers(folio[0]))
create_empty_buffers(&folio[0]->page, 1 << orig_inode->i_blkbits, 0);
bh = folio_buffers(folio[0]);
for (i = 0; i < data_offset_in_page; i++)
bh = bh->b_this_page;
for (i = 0; i < block_len_in_page; i++) {
*err = ext4_get_block(orig_inode, orig_blk_offset + i, bh, 0);
if (*err < 0)
goto repair_branches;
bh = bh->b_this_page;
}
block_commit_write(&folio[0]->page, from, from + replaced_size);
/* Even in case of data=writeback it is reasonable to pin
* inode to transaction, to prevent unexpected data loss */
*err = ext4_jbd2_inode_add_write(handle, orig_inode,
(loff_t)orig_page_offset << PAGE_SHIFT, replaced_size);
unlock_folios:
folio_unlock(folio[0]);
folio_put(folio[0]);
folio_unlock(folio[1]);
folio_put(folio[1]);
stop_journal:
ext4_journal_stop(handle);
if (*err == -ENOSPC &&
ext4_should_retry_alloc(sb, &retries))
goto again;
/* Buffer was busy because probably is pinned to journal transaction,
* force transaction commit may help to free it. */
if (*err == -EBUSY && retries++ < 4 && EXT4_SB(sb)->s_journal &&
jbd2_journal_force_commit_nested(EXT4_SB(sb)->s_journal))
goto again;
return replaced_count;
repair_branches:
/*
* This should never ever happen!
* Extents are swapped already, but we are not able to copy data.
* Try to swap extents to it's original places
*/
ext4_double_down_write_data_sem(orig_inode, donor_inode);
replaced_count = ext4_swap_extents(handle, donor_inode, orig_inode,
orig_blk_offset, donor_blk_offset,
block_len_in_page, 0, &err2);
ext4_double_up_write_data_sem(orig_inode, donor_inode);
if (replaced_count != block_len_in_page) {
ext4_error_inode_block(orig_inode, (sector_t)(orig_blk_offset),
EIO, "Unable to copy data block,"
" data will be lost.");
*err = -EIO;
}
replaced_count = 0;
goto unlock_folios;
}
/**
* mext_check_arguments - Check whether move extent can be done
*
* @orig_inode: original inode
* @donor_inode: donor inode
* @orig_start: logical start offset in block for orig
* @donor_start: logical start offset in block for donor
* @len: the number of blocks to be moved
*
* Check the arguments of ext4_move_extents() whether the files can be
* exchanged with each other.
* Return 0 on success, or a negative error value on failure.
*/
static int
mext_check_arguments(struct inode *orig_inode,
struct inode *donor_inode, __u64 orig_start,
__u64 donor_start, __u64 *len)
{
__u64 orig_eof, donor_eof;
unsigned int blkbits = orig_inode->i_blkbits;
unsigned int blocksize = 1 << blkbits;
orig_eof = (i_size_read(orig_inode) + blocksize - 1) >> blkbits;
donor_eof = (i_size_read(donor_inode) + blocksize - 1) >> blkbits;
if (donor_inode->i_mode & (S_ISUID|S_ISGID)) {
ext4_debug("ext4 move extent: suid or sgid is set"
" to donor file [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if (IS_IMMUTABLE(donor_inode) || IS_APPEND(donor_inode))
return -EPERM;
/* Ext4 move extent does not support swap files */
if (IS_SWAPFILE(orig_inode) || IS_SWAPFILE(donor_inode)) {
ext4_debug("ext4 move extent: The argument files should not be swap files [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -ETXTBSY;
}
if (ext4_is_quota_file(orig_inode) && ext4_is_quota_file(donor_inode)) {
ext4_debug("ext4 move extent: The argument files should not be quota files [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EOPNOTSUPP;
}
/* Ext4 move extent supports only extent based file */
if (!(ext4_test_inode_flag(orig_inode, EXT4_INODE_EXTENTS))) {
ext4_debug("ext4 move extent: orig file is not extents "
"based file [ino:orig %lu]\n", orig_inode->i_ino);
return -EOPNOTSUPP;
} else if (!(ext4_test_inode_flag(donor_inode, EXT4_INODE_EXTENTS))) {
ext4_debug("ext4 move extent: donor file is not extents "
"based file [ino:donor %lu]\n", donor_inode->i_ino);
return -EOPNOTSUPP;
}
if ((!orig_inode->i_size) || (!donor_inode->i_size)) {
ext4_debug("ext4 move extent: File size is 0 byte\n");
return -EINVAL;
}
/* Start offset should be same */
if ((orig_start & ~(PAGE_MASK >> orig_inode->i_blkbits)) !=
(donor_start & ~(PAGE_MASK >> orig_inode->i_blkbits))) {
ext4_debug("ext4 move extent: orig and donor's start "
"offsets are not aligned [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if ((orig_start >= EXT_MAX_BLOCKS) ||
(donor_start >= EXT_MAX_BLOCKS) ||
(*len > EXT_MAX_BLOCKS) ||
(donor_start + *len >= EXT_MAX_BLOCKS) ||
(orig_start + *len >= EXT_MAX_BLOCKS)) {
ext4_debug("ext4 move extent: Can't handle over [%u] blocks "
"[ino:orig %lu, donor %lu]\n", EXT_MAX_BLOCKS,
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if (orig_eof <= orig_start)
*len = 0;
else if (orig_eof < orig_start + *len - 1)
*len = orig_eof - orig_start;
if (donor_eof <= donor_start)
*len = 0;
else if (donor_eof < donor_start + *len - 1)
*len = donor_eof - donor_start;
if (!*len) {
ext4_debug("ext4 move extent: len should not be 0 "
"[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
donor_inode->i_ino);
return -EINVAL;
}
return 0;
}
/**
* ext4_move_extents - Exchange the specified range of a file
*
* @o_filp: file structure of the original file
* @d_filp: file structure of the donor file
* @orig_blk: start offset in block for orig
* @donor_blk: start offset in block for donor
* @len: the number of blocks to be moved
* @moved_len: moved block length
*
* This function returns 0 and moved block length is set in moved_len
* if succeed, otherwise returns error value.
*
*/
int
ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk,
__u64 donor_blk, __u64 len, __u64 *moved_len)
{
struct inode *orig_inode = file_inode(o_filp);
struct inode *donor_inode = file_inode(d_filp);
struct ext4_ext_path *path = NULL;
int blocks_per_page = PAGE_SIZE >> orig_inode->i_blkbits;
ext4_lblk_t o_end, o_start = orig_blk;
ext4_lblk_t d_start = donor_blk;
int ret;
if (orig_inode->i_sb != donor_inode->i_sb) {
ext4_debug("ext4 move extent: The argument files "
"should be in same FS [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* orig and donor should be different inodes */
if (orig_inode == donor_inode) {
ext4_debug("ext4 move extent: The argument files should not "
"be same inode [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* Regular file check */
if (!S_ISREG(orig_inode->i_mode) || !S_ISREG(donor_inode->i_mode)) {
ext4_debug("ext4 move extent: The argument files should be "
"regular file [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* TODO: it's not obvious how to swap blocks for inodes with full
journaling enabled */
if (ext4_should_journal_data(orig_inode) ||
ext4_should_journal_data(donor_inode)) {
ext4_msg(orig_inode->i_sb, KERN_ERR,
"Online defrag not supported with data journaling");
return -EOPNOTSUPP;
}
if (IS_ENCRYPTED(orig_inode) || IS_ENCRYPTED(donor_inode)) {
ext4_msg(orig_inode->i_sb, KERN_ERR,
"Online defrag not supported for encrypted files");
return -EOPNOTSUPP;
}
/* Protect orig and donor inodes against a truncate */
lock_two_nondirectories(orig_inode, donor_inode);
/* Wait for all existing dio workers */
inode_dio_wait(orig_inode);
inode_dio_wait(donor_inode);
/* Protect extent tree against block allocations via delalloc */
ext4_double_down_write_data_sem(orig_inode, donor_inode);
/* Check the filesystem environment whether move_extent can be done */
ret = mext_check_arguments(orig_inode, donor_inode, orig_blk,
donor_blk, &len);
if (ret)
goto out;
o_end = o_start + len;
while (o_start < o_end) {
struct ext4_extent *ex;
ext4_lblk_t cur_blk, next_blk;
pgoff_t orig_page_index, donor_page_index;
int offset_in_page;
int unwritten, cur_len;
ret = get_ext_path(orig_inode, o_start, &path);
if (ret)
goto out;
ex = path[path->p_depth].p_ext;
cur_blk = le32_to_cpu(ex->ee_block);
cur_len = ext4_ext_get_actual_len(ex);
/* Check hole before the start pos */
if (cur_blk + cur_len - 1 < o_start) {
next_blk = ext4_ext_next_allocated_block(path);
if (next_blk == EXT_MAX_BLOCKS) {
ret = -ENODATA;
goto out;
}
d_start += next_blk - o_start;
o_start = next_blk;
continue;
/* Check hole after the start pos */
} else if (cur_blk > o_start) {
/* Skip hole */
d_start += cur_blk - o_start;
o_start = cur_blk;
/* Extent inside requested range ?*/
if (cur_blk >= o_end)
goto out;
} else { /* in_range(o_start, o_blk, o_len) */
cur_len += cur_blk - o_start;
}
unwritten = ext4_ext_is_unwritten(ex);
if (o_end - o_start < cur_len)
cur_len = o_end - o_start;
orig_page_index = o_start >> (PAGE_SHIFT -
orig_inode->i_blkbits);
donor_page_index = d_start >> (PAGE_SHIFT -
donor_inode->i_blkbits);
offset_in_page = o_start % blocks_per_page;
if (cur_len > blocks_per_page - offset_in_page)
cur_len = blocks_per_page - offset_in_page;
/*
* Up semaphore to avoid following problems:
* a. transaction deadlock among ext4_journal_start,
* ->write_begin via pagefault, and jbd2_journal_commit
* b. racing with ->read_folio, ->write_begin, and
* ext4_get_block in move_extent_per_page
*/
ext4_double_up_write_data_sem(orig_inode, donor_inode);
/* Swap original branches with new branches */
move_extent_per_page(o_filp, donor_inode,
orig_page_index, donor_page_index,
offset_in_page, cur_len,
unwritten, &ret);
ext4_double_down_write_data_sem(orig_inode, donor_inode);
if (ret < 0)
break;
o_start += cur_len;
d_start += cur_len;
}
*moved_len = o_start - orig_blk;
if (*moved_len > len)
*moved_len = len;
out:
if (*moved_len) {
ext4_discard_preallocations(orig_inode, 0);
ext4_discard_preallocations(donor_inode, 0);
}
ext4_free_ext_path(path);
ext4_double_up_write_data_sem(orig_inode, donor_inode);
unlock_two_nondirectories(orig_inode, donor_inode);
return ret;
}
| linux-master | fs/ext4/move_extent.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/xattr_user.c
* Handler for extended user attributes.
*
* Copyright (C) 2001 by Andreas Gruenbacher, <[email protected]>
*/
#include <linux/string.h>
#include <linux/fs.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
static bool
ext4_xattr_user_list(struct dentry *dentry)
{
return test_opt(dentry->d_sb, XATTR_USER);
}
static int
ext4_xattr_user_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_USER,
name, buffer, size);
}
static int
ext4_xattr_user_set(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)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_set(inode, EXT4_XATTR_INDEX_USER,
name, value, size, flags);
}
const struct xattr_handler ext4_xattr_user_handler = {
.prefix = XATTR_USER_PREFIX,
.list = ext4_xattr_user_list,
.get = ext4_xattr_user_get,
.set = ext4_xattr_user_set,
};
| linux-master | fs/ext4/xattr_user.c |
// SPDX-License-Identifier: GPL-2.0
/*
* fs/ext4/extents_status.c
*
* Written by Yongqiang Yang <[email protected]>
* Modified by
* Allison Henderson <[email protected]>
* Hugh Dickins <[email protected]>
* Zheng Liu <[email protected]>
*
* Ext4 extents status tree core functions.
*/
#include <linux/list_sort.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include "ext4.h"
#include <trace/events/ext4.h>
/*
* According to previous discussion in Ext4 Developer Workshop, we
* will introduce a new structure called io tree to track all extent
* status in order to solve some problems that we have met
* (e.g. Reservation space warning), and provide extent-level locking.
* Delay extent tree is the first step to achieve this goal. It is
* original built by Yongqiang Yang. At that time it is called delay
* extent tree, whose goal is only track delayed extents in memory to
* simplify the implementation of fiemap and bigalloc, and introduce
* lseek SEEK_DATA/SEEK_HOLE support. That is why it is still called
* delay extent tree at the first commit. But for better understand
* what it does, it has been rename to extent status tree.
*
* Step1:
* Currently the first step has been done. All delayed extents are
* tracked in the tree. It maintains the delayed extent when a delayed
* allocation is issued, and the delayed extent is written out or
* invalidated. Therefore the implementation of fiemap and bigalloc
* are simplified, and SEEK_DATA/SEEK_HOLE are introduced.
*
* The following comment describes the implemenmtation of extent
* status tree and future works.
*
* Step2:
* In this step all extent status are tracked by extent status tree.
* Thus, we can first try to lookup a block mapping in this tree before
* finding it in extent tree. Hence, single extent cache can be removed
* because extent status tree can do a better job. Extents in status
* tree are loaded on-demand. Therefore, the extent status tree may not
* contain all of the extents in a file. Meanwhile we define a shrinker
* to reclaim memory from extent status tree because fragmented extent
* tree will make status tree cost too much memory. written/unwritten/-
* hole extents in the tree will be reclaimed by this shrinker when we
* are under high memory pressure. Delayed extents will not be
* reclimed because fiemap, bigalloc, and seek_data/hole need it.
*/
/*
* Extent status tree implementation for ext4.
*
*
* ==========================================================================
* Extent status tree tracks all extent status.
*
* 1. Why we need to implement extent status tree?
*
* Without extent status tree, ext4 identifies a delayed extent by looking
* up page cache, this has several deficiencies - complicated, buggy,
* and inefficient code.
*
* FIEMAP, SEEK_HOLE/DATA, bigalloc, and writeout all need to know if a
* block or a range of blocks are belonged to a delayed extent.
*
* Let us have a look at how they do without extent status tree.
* -- FIEMAP
* FIEMAP looks up page cache to identify delayed allocations from holes.
*
* -- SEEK_HOLE/DATA
* SEEK_HOLE/DATA has the same problem as FIEMAP.
*
* -- bigalloc
* bigalloc looks up page cache to figure out if a block is
* already under delayed allocation or not to determine whether
* quota reserving is needed for the cluster.
*
* -- writeout
* Writeout looks up whole page cache to see if a buffer is
* mapped, If there are not very many delayed buffers, then it is
* time consuming.
*
* With extent status tree implementation, FIEMAP, SEEK_HOLE/DATA,
* bigalloc and writeout can figure out if a block or a range of
* blocks is under delayed allocation(belonged to a delayed extent) or
* not by searching the extent tree.
*
*
* ==========================================================================
* 2. Ext4 extent status tree impelmentation
*
* -- extent
* A extent is a range of blocks which are contiguous logically and
* physically. Unlike extent in extent tree, this extent in ext4 is
* a in-memory struct, there is no corresponding on-disk data. There
* is no limit on length of extent, so an extent can contain as many
* blocks as they are contiguous logically and physically.
*
* -- extent status tree
* Every inode has an extent status tree and all allocation blocks
* are added to the tree with different status. The extent in the
* tree are ordered by logical block no.
*
* -- operations on a extent status tree
* There are three important operations on a delayed extent tree: find
* next extent, adding a extent(a range of blocks) and removing a extent.
*
* -- race on a extent status tree
* Extent status tree is protected by inode->i_es_lock.
*
* -- memory consumption
* Fragmented extent tree will make extent status tree cost too much
* memory. Hence, we will reclaim written/unwritten/hole extents from
* the tree under a heavy memory pressure.
*
*
* ==========================================================================
* 3. Performance analysis
*
* -- overhead
* 1. There is a cache extent for write access, so if writes are
* not very random, adding space operaions are in O(1) time.
*
* -- gain
* 2. Code is much simpler, more readable, more maintainable and
* more efficient.
*
*
* ==========================================================================
* 4. TODO list
*
* -- Refactor delayed space reservation
*
* -- Extent-level locking
*/
static struct kmem_cache *ext4_es_cachep;
static struct kmem_cache *ext4_pending_cachep;
static int __es_insert_extent(struct inode *inode, struct extent_status *newes,
struct extent_status *prealloc);
static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t end, int *reserved,
struct extent_status *prealloc);
static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan);
static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan,
struct ext4_inode_info *locked_ei);
static void __revise_pending(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len);
int __init ext4_init_es(void)
{
ext4_es_cachep = KMEM_CACHE(extent_status, SLAB_RECLAIM_ACCOUNT);
if (ext4_es_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_exit_es(void)
{
kmem_cache_destroy(ext4_es_cachep);
}
void ext4_es_init_tree(struct ext4_es_tree *tree)
{
tree->root = RB_ROOT;
tree->cache_es = NULL;
}
#ifdef ES_DEBUG__
static void ext4_es_print_tree(struct inode *inode)
{
struct ext4_es_tree *tree;
struct rb_node *node;
printk(KERN_DEBUG "status extents for inode %lu:", inode->i_ino);
tree = &EXT4_I(inode)->i_es_tree;
node = rb_first(&tree->root);
while (node) {
struct extent_status *es;
es = rb_entry(node, struct extent_status, rb_node);
printk(KERN_DEBUG " [%u/%u) %llu %x",
es->es_lblk, es->es_len,
ext4_es_pblock(es), ext4_es_status(es));
node = rb_next(node);
}
printk(KERN_DEBUG "\n");
}
#else
#define ext4_es_print_tree(inode)
#endif
static inline ext4_lblk_t ext4_es_end(struct extent_status *es)
{
BUG_ON(es->es_lblk + es->es_len < es->es_lblk);
return es->es_lblk + es->es_len - 1;
}
/*
* search through the tree for an delayed extent with a given offset. If
* it can't be found, try to find next extent.
*/
static struct extent_status *__es_tree_search(struct rb_root *root,
ext4_lblk_t lblk)
{
struct rb_node *node = root->rb_node;
struct extent_status *es = NULL;
while (node) {
es = rb_entry(node, struct extent_status, rb_node);
if (lblk < es->es_lblk)
node = node->rb_left;
else if (lblk > ext4_es_end(es))
node = node->rb_right;
else
return es;
}
if (es && lblk < es->es_lblk)
return es;
if (es && lblk > ext4_es_end(es)) {
node = rb_next(&es->rb_node);
return node ? rb_entry(node, struct extent_status, rb_node) :
NULL;
}
return NULL;
}
/*
* ext4_es_find_extent_range - find extent with specified status within block
* range or next extent following block range in
* extents status tree
*
* @inode - file containing the range
* @matching_fn - pointer to function that matches extents with desired status
* @lblk - logical block defining start of range
* @end - logical block defining end of range
* @es - extent found, if any
*
* Find the first extent within the block range specified by @lblk and @end
* in the extents status tree that satisfies @matching_fn. If a match
* is found, it's returned in @es. If not, and a matching extent is found
* beyond the block range, it's returned in @es. If no match is found, an
* extent is returned in @es whose es_lblk, es_len, and es_pblk components
* are 0.
*/
static void __es_find_extent_range(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t lblk, ext4_lblk_t end,
struct extent_status *es)
{
struct ext4_es_tree *tree = NULL;
struct extent_status *es1 = NULL;
struct rb_node *node;
WARN_ON(es == NULL);
WARN_ON(end < lblk);
tree = &EXT4_I(inode)->i_es_tree;
/* see if the extent has been cached */
es->es_lblk = es->es_len = es->es_pblk = 0;
es1 = READ_ONCE(tree->cache_es);
if (es1 && in_range(lblk, es1->es_lblk, es1->es_len)) {
es_debug("%u cached by [%u/%u) %llu %x\n",
lblk, es1->es_lblk, es1->es_len,
ext4_es_pblock(es1), ext4_es_status(es1));
goto out;
}
es1 = __es_tree_search(&tree->root, lblk);
out:
if (es1 && !matching_fn(es1)) {
while ((node = rb_next(&es1->rb_node)) != NULL) {
es1 = rb_entry(node, struct extent_status, rb_node);
if (es1->es_lblk > end) {
es1 = NULL;
break;
}
if (matching_fn(es1))
break;
}
}
if (es1 && matching_fn(es1)) {
WRITE_ONCE(tree->cache_es, es1);
es->es_lblk = es1->es_lblk;
es->es_len = es1->es_len;
es->es_pblk = es1->es_pblk;
}
}
/*
* Locking for __es_find_extent_range() for external use
*/
void ext4_es_find_extent_range(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t lblk, ext4_lblk_t end,
struct extent_status *es)
{
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return;
trace_ext4_es_find_extent_range_enter(inode, lblk);
read_lock(&EXT4_I(inode)->i_es_lock);
__es_find_extent_range(inode, matching_fn, lblk, end, es);
read_unlock(&EXT4_I(inode)->i_es_lock);
trace_ext4_es_find_extent_range_exit(inode, es);
}
/*
* __es_scan_range - search block range for block with specified status
* in extents status tree
*
* @inode - file containing the range
* @matching_fn - pointer to function that matches extents with desired status
* @lblk - logical block defining start of range
* @end - logical block defining end of range
*
* Returns true if at least one block in the specified block range satisfies
* the criterion specified by @matching_fn, and false if not. If at least
* one extent has the specified status, then there is at least one block
* in the cluster with that status. Should only be called by code that has
* taken i_es_lock.
*/
static bool __es_scan_range(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t start, ext4_lblk_t end)
{
struct extent_status es;
__es_find_extent_range(inode, matching_fn, start, end, &es);
if (es.es_len == 0)
return false; /* no matching extent in the tree */
else if (es.es_lblk <= start &&
start < es.es_lblk + es.es_len)
return true;
else if (start <= es.es_lblk && es.es_lblk <= end)
return true;
else
return false;
}
/*
* Locking for __es_scan_range() for external use
*/
bool ext4_es_scan_range(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t lblk, ext4_lblk_t end)
{
bool ret;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return false;
read_lock(&EXT4_I(inode)->i_es_lock);
ret = __es_scan_range(inode, matching_fn, lblk, end);
read_unlock(&EXT4_I(inode)->i_es_lock);
return ret;
}
/*
* __es_scan_clu - search cluster for block with specified status in
* extents status tree
*
* @inode - file containing the cluster
* @matching_fn - pointer to function that matches extents with desired status
* @lblk - logical block in cluster to be searched
*
* Returns true if at least one extent in the cluster containing @lblk
* satisfies the criterion specified by @matching_fn, and false if not. If at
* least one extent has the specified status, then there is at least one block
* in the cluster with that status. Should only be called by code that has
* taken i_es_lock.
*/
static bool __es_scan_clu(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_lblk_t lblk_start, lblk_end;
lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
return __es_scan_range(inode, matching_fn, lblk_start, lblk_end);
}
/*
* Locking for __es_scan_clu() for external use
*/
bool ext4_es_scan_clu(struct inode *inode,
int (*matching_fn)(struct extent_status *es),
ext4_lblk_t lblk)
{
bool ret;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return false;
read_lock(&EXT4_I(inode)->i_es_lock);
ret = __es_scan_clu(inode, matching_fn, lblk);
read_unlock(&EXT4_I(inode)->i_es_lock);
return ret;
}
static void ext4_es_list_add(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (!list_empty(&ei->i_es_list))
return;
spin_lock(&sbi->s_es_lock);
if (list_empty(&ei->i_es_list)) {
list_add_tail(&ei->i_es_list, &sbi->s_es_list);
sbi->s_es_nr_inode++;
}
spin_unlock(&sbi->s_es_lock);
}
static void ext4_es_list_del(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
spin_lock(&sbi->s_es_lock);
if (!list_empty(&ei->i_es_list)) {
list_del_init(&ei->i_es_list);
sbi->s_es_nr_inode--;
WARN_ON_ONCE(sbi->s_es_nr_inode < 0);
}
spin_unlock(&sbi->s_es_lock);
}
/*
* Returns true if we cannot fail to allocate memory for this extent_status
* entry and cannot reclaim it until its status changes.
*/
static inline bool ext4_es_must_keep(struct extent_status *es)
{
/* fiemap, bigalloc, and seek_data/hole need to use it. */
if (ext4_es_is_delayed(es))
return true;
return false;
}
static inline struct extent_status *__es_alloc_extent(bool nofail)
{
if (!nofail)
return kmem_cache_alloc(ext4_es_cachep, GFP_ATOMIC);
return kmem_cache_zalloc(ext4_es_cachep, GFP_KERNEL | __GFP_NOFAIL);
}
static void ext4_es_init_extent(struct inode *inode, struct extent_status *es,
ext4_lblk_t lblk, ext4_lblk_t len, ext4_fsblk_t pblk)
{
es->es_lblk = lblk;
es->es_len = len;
es->es_pblk = pblk;
/* We never try to reclaim a must kept extent, so we don't count it. */
if (!ext4_es_must_keep(es)) {
if (!EXT4_I(inode)->i_es_shk_nr++)
ext4_es_list_add(inode);
percpu_counter_inc(&EXT4_SB(inode->i_sb)->
s_es_stats.es_stats_shk_cnt);
}
EXT4_I(inode)->i_es_all_nr++;
percpu_counter_inc(&EXT4_SB(inode->i_sb)->s_es_stats.es_stats_all_cnt);
}
static inline void __es_free_extent(struct extent_status *es)
{
kmem_cache_free(ext4_es_cachep, es);
}
static void ext4_es_free_extent(struct inode *inode, struct extent_status *es)
{
EXT4_I(inode)->i_es_all_nr--;
percpu_counter_dec(&EXT4_SB(inode->i_sb)->s_es_stats.es_stats_all_cnt);
/* Decrease the shrink counter when we can reclaim the extent. */
if (!ext4_es_must_keep(es)) {
BUG_ON(EXT4_I(inode)->i_es_shk_nr == 0);
if (!--EXT4_I(inode)->i_es_shk_nr)
ext4_es_list_del(inode);
percpu_counter_dec(&EXT4_SB(inode->i_sb)->
s_es_stats.es_stats_shk_cnt);
}
__es_free_extent(es);
}
/*
* Check whether or not two extents can be merged
* Condition:
* - logical block number is contiguous
* - physical block number is contiguous
* - status is equal
*/
static int ext4_es_can_be_merged(struct extent_status *es1,
struct extent_status *es2)
{
if (ext4_es_type(es1) != ext4_es_type(es2))
return 0;
if (((__u64) es1->es_len) + es2->es_len > EXT_MAX_BLOCKS) {
pr_warn("ES assertion failed when merging extents. "
"The sum of lengths of es1 (%d) and es2 (%d) "
"is bigger than allowed file size (%d)\n",
es1->es_len, es2->es_len, EXT_MAX_BLOCKS);
WARN_ON(1);
return 0;
}
if (((__u64) es1->es_lblk) + es1->es_len != es2->es_lblk)
return 0;
if ((ext4_es_is_written(es1) || ext4_es_is_unwritten(es1)) &&
(ext4_es_pblock(es1) + es1->es_len == ext4_es_pblock(es2)))
return 1;
if (ext4_es_is_hole(es1))
return 1;
/* we need to check delayed extent is without unwritten status */
if (ext4_es_is_delayed(es1) && !ext4_es_is_unwritten(es1))
return 1;
return 0;
}
static struct extent_status *
ext4_es_try_to_merge_left(struct inode *inode, struct extent_status *es)
{
struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
struct extent_status *es1;
struct rb_node *node;
node = rb_prev(&es->rb_node);
if (!node)
return es;
es1 = rb_entry(node, struct extent_status, rb_node);
if (ext4_es_can_be_merged(es1, es)) {
es1->es_len += es->es_len;
if (ext4_es_is_referenced(es))
ext4_es_set_referenced(es1);
rb_erase(&es->rb_node, &tree->root);
ext4_es_free_extent(inode, es);
es = es1;
}
return es;
}
static struct extent_status *
ext4_es_try_to_merge_right(struct inode *inode, struct extent_status *es)
{
struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
struct extent_status *es1;
struct rb_node *node;
node = rb_next(&es->rb_node);
if (!node)
return es;
es1 = rb_entry(node, struct extent_status, rb_node);
if (ext4_es_can_be_merged(es, es1)) {
es->es_len += es1->es_len;
if (ext4_es_is_referenced(es1))
ext4_es_set_referenced(es);
rb_erase(node, &tree->root);
ext4_es_free_extent(inode, es1);
}
return es;
}
#ifdef ES_AGGRESSIVE_TEST
#include "ext4_extents.h" /* Needed when ES_AGGRESSIVE_TEST is defined */
static void ext4_es_insert_extent_ext_check(struct inode *inode,
struct extent_status *es)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent *ex;
ext4_lblk_t ee_block;
ext4_fsblk_t ee_start;
unsigned short ee_len;
int depth, ee_status, es_status;
path = ext4_find_extent(inode, es->es_lblk, NULL, EXT4_EX_NOCACHE);
if (IS_ERR(path))
return;
depth = ext_depth(inode);
ex = path[depth].p_ext;
if (ex) {
ee_block = le32_to_cpu(ex->ee_block);
ee_start = ext4_ext_pblock(ex);
ee_len = ext4_ext_get_actual_len(ex);
ee_status = ext4_ext_is_unwritten(ex) ? 1 : 0;
es_status = ext4_es_is_unwritten(es) ? 1 : 0;
/*
* Make sure ex and es are not overlap when we try to insert
* a delayed/hole extent.
*/
if (!ext4_es_is_written(es) && !ext4_es_is_unwritten(es)) {
if (in_range(es->es_lblk, ee_block, ee_len)) {
pr_warn("ES insert assertion failed for "
"inode: %lu we can find an extent "
"at block [%d/%d/%llu/%c], but we "
"want to add a delayed/hole extent "
"[%d/%d/%llu/%x]\n",
inode->i_ino, ee_block, ee_len,
ee_start, ee_status ? 'u' : 'w',
es->es_lblk, es->es_len,
ext4_es_pblock(es), ext4_es_status(es));
}
goto out;
}
/*
* We don't check ee_block == es->es_lblk, etc. because es
* might be a part of whole extent, vice versa.
*/
if (es->es_lblk < ee_block ||
ext4_es_pblock(es) != ee_start + es->es_lblk - ee_block) {
pr_warn("ES insert assertion failed for inode: %lu "
"ex_status [%d/%d/%llu/%c] != "
"es_status [%d/%d/%llu/%c]\n", inode->i_ino,
ee_block, ee_len, ee_start,
ee_status ? 'u' : 'w', es->es_lblk, es->es_len,
ext4_es_pblock(es), es_status ? 'u' : 'w');
goto out;
}
if (ee_status ^ es_status) {
pr_warn("ES insert assertion failed for inode: %lu "
"ex_status [%d/%d/%llu/%c] != "
"es_status [%d/%d/%llu/%c]\n", inode->i_ino,
ee_block, ee_len, ee_start,
ee_status ? 'u' : 'w', es->es_lblk, es->es_len,
ext4_es_pblock(es), es_status ? 'u' : 'w');
}
} else {
/*
* We can't find an extent on disk. So we need to make sure
* that we don't want to add an written/unwritten extent.
*/
if (!ext4_es_is_delayed(es) && !ext4_es_is_hole(es)) {
pr_warn("ES insert assertion failed for inode: %lu "
"can't find an extent at block %d but we want "
"to add a written/unwritten extent "
"[%d/%d/%llu/%x]\n", inode->i_ino,
es->es_lblk, es->es_lblk, es->es_len,
ext4_es_pblock(es), ext4_es_status(es));
}
}
out:
ext4_free_ext_path(path);
}
static void ext4_es_insert_extent_ind_check(struct inode *inode,
struct extent_status *es)
{
struct ext4_map_blocks map;
int retval;
/*
* Here we call ext4_ind_map_blocks to lookup a block mapping because
* 'Indirect' structure is defined in indirect.c. So we couldn't
* access direct/indirect tree from outside. It is too dirty to define
* this function in indirect.c file.
*/
map.m_lblk = es->es_lblk;
map.m_len = es->es_len;
retval = ext4_ind_map_blocks(NULL, inode, &map, 0);
if (retval > 0) {
if (ext4_es_is_delayed(es) || ext4_es_is_hole(es)) {
/*
* We want to add a delayed/hole extent but this
* block has been allocated.
*/
pr_warn("ES insert assertion failed for inode: %lu "
"We can find blocks but we want to add a "
"delayed/hole extent [%d/%d/%llu/%x]\n",
inode->i_ino, es->es_lblk, es->es_len,
ext4_es_pblock(es), ext4_es_status(es));
return;
} else if (ext4_es_is_written(es)) {
if (retval != es->es_len) {
pr_warn("ES insert assertion failed for "
"inode: %lu retval %d != es_len %d\n",
inode->i_ino, retval, es->es_len);
return;
}
if (map.m_pblk != ext4_es_pblock(es)) {
pr_warn("ES insert assertion failed for "
"inode: %lu m_pblk %llu != "
"es_pblk %llu\n",
inode->i_ino, map.m_pblk,
ext4_es_pblock(es));
return;
}
} else {
/*
* We don't need to check unwritten extent because
* indirect-based file doesn't have it.
*/
BUG();
}
} else if (retval == 0) {
if (ext4_es_is_written(es)) {
pr_warn("ES insert assertion failed for inode: %lu "
"We can't find the block but we want to add "
"a written extent [%d/%d/%llu/%x]\n",
inode->i_ino, es->es_lblk, es->es_len,
ext4_es_pblock(es), ext4_es_status(es));
return;
}
}
}
static inline void ext4_es_insert_extent_check(struct inode *inode,
struct extent_status *es)
{
/*
* We don't need to worry about the race condition because
* caller takes i_data_sem locking.
*/
BUG_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
ext4_es_insert_extent_ext_check(inode, es);
else
ext4_es_insert_extent_ind_check(inode, es);
}
#else
static inline void ext4_es_insert_extent_check(struct inode *inode,
struct extent_status *es)
{
}
#endif
static int __es_insert_extent(struct inode *inode, struct extent_status *newes,
struct extent_status *prealloc)
{
struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
struct rb_node **p = &tree->root.rb_node;
struct rb_node *parent = NULL;
struct extent_status *es;
while (*p) {
parent = *p;
es = rb_entry(parent, struct extent_status, rb_node);
if (newes->es_lblk < es->es_lblk) {
if (ext4_es_can_be_merged(newes, es)) {
/*
* Here we can modify es_lblk directly
* because it isn't overlapped.
*/
es->es_lblk = newes->es_lblk;
es->es_len += newes->es_len;
if (ext4_es_is_written(es) ||
ext4_es_is_unwritten(es))
ext4_es_store_pblock(es,
newes->es_pblk);
es = ext4_es_try_to_merge_left(inode, es);
goto out;
}
p = &(*p)->rb_left;
} else if (newes->es_lblk > ext4_es_end(es)) {
if (ext4_es_can_be_merged(es, newes)) {
es->es_len += newes->es_len;
es = ext4_es_try_to_merge_right(inode, es);
goto out;
}
p = &(*p)->rb_right;
} else {
BUG();
return -EINVAL;
}
}
if (prealloc)
es = prealloc;
else
es = __es_alloc_extent(false);
if (!es)
return -ENOMEM;
ext4_es_init_extent(inode, es, newes->es_lblk, newes->es_len,
newes->es_pblk);
rb_link_node(&es->rb_node, parent, p);
rb_insert_color(&es->rb_node, &tree->root);
out:
tree->cache_es = es;
return 0;
}
/*
* ext4_es_insert_extent() adds information to an inode's extent
* status tree.
*/
void ext4_es_insert_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len, ext4_fsblk_t pblk,
unsigned int status)
{
struct extent_status newes;
ext4_lblk_t end = lblk + len - 1;
int err1 = 0;
int err2 = 0;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct extent_status *es1 = NULL;
struct extent_status *es2 = NULL;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return;
es_debug("add [%u/%u) %llu %x to extent status tree of inode %lu\n",
lblk, len, pblk, status, inode->i_ino);
if (!len)
return;
BUG_ON(end < lblk);
if ((status & EXTENT_STATUS_DELAYED) &&
(status & EXTENT_STATUS_WRITTEN)) {
ext4_warning(inode->i_sb, "Inserting extent [%u/%u] as "
" delayed and written which can potentially "
" cause data loss.", lblk, len);
WARN_ON(1);
}
newes.es_lblk = lblk;
newes.es_len = len;
ext4_es_store_pblock_status(&newes, pblk, status);
trace_ext4_es_insert_extent(inode, &newes);
ext4_es_insert_extent_check(inode, &newes);
retry:
if (err1 && !es1)
es1 = __es_alloc_extent(true);
if ((err1 || err2) && !es2)
es2 = __es_alloc_extent(true);
write_lock(&EXT4_I(inode)->i_es_lock);
err1 = __es_remove_extent(inode, lblk, end, NULL, es1);
if (err1 != 0)
goto error;
/* Free preallocated extent if it didn't get used. */
if (es1) {
if (!es1->es_len)
__es_free_extent(es1);
es1 = NULL;
}
err2 = __es_insert_extent(inode, &newes, es2);
if (err2 == -ENOMEM && !ext4_es_must_keep(&newes))
err2 = 0;
if (err2 != 0)
goto error;
/* Free preallocated extent if it didn't get used. */
if (es2) {
if (!es2->es_len)
__es_free_extent(es2);
es2 = NULL;
}
if (sbi->s_cluster_ratio > 1 && test_opt(inode->i_sb, DELALLOC) &&
(status & EXTENT_STATUS_WRITTEN ||
status & EXTENT_STATUS_UNWRITTEN))
__revise_pending(inode, lblk, len);
error:
write_unlock(&EXT4_I(inode)->i_es_lock);
if (err1 || err2)
goto retry;
ext4_es_print_tree(inode);
return;
}
/*
* ext4_es_cache_extent() inserts information into the extent status
* tree if and only if there isn't information about the range in
* question already.
*/
void ext4_es_cache_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len, ext4_fsblk_t pblk,
unsigned int status)
{
struct extent_status *es;
struct extent_status newes;
ext4_lblk_t end = lblk + len - 1;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return;
newes.es_lblk = lblk;
newes.es_len = len;
ext4_es_store_pblock_status(&newes, pblk, status);
trace_ext4_es_cache_extent(inode, &newes);
if (!len)
return;
BUG_ON(end < lblk);
write_lock(&EXT4_I(inode)->i_es_lock);
es = __es_tree_search(&EXT4_I(inode)->i_es_tree.root, lblk);
if (!es || es->es_lblk > end)
__es_insert_extent(inode, &newes, NULL);
write_unlock(&EXT4_I(inode)->i_es_lock);
}
/*
* ext4_es_lookup_extent() looks up an extent in extent status tree.
*
* ext4_es_lookup_extent is called by ext4_map_blocks/ext4_da_map_blocks.
*
* Return: 1 on found, 0 on not
*/
int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t *next_lblk,
struct extent_status *es)
{
struct ext4_es_tree *tree;
struct ext4_es_stats *stats;
struct extent_status *es1 = NULL;
struct rb_node *node;
int found = 0;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return 0;
trace_ext4_es_lookup_extent_enter(inode, lblk);
es_debug("lookup extent in block %u\n", lblk);
tree = &EXT4_I(inode)->i_es_tree;
read_lock(&EXT4_I(inode)->i_es_lock);
/* find extent in cache firstly */
es->es_lblk = es->es_len = es->es_pblk = 0;
es1 = READ_ONCE(tree->cache_es);
if (es1 && in_range(lblk, es1->es_lblk, es1->es_len)) {
es_debug("%u cached by [%u/%u)\n",
lblk, es1->es_lblk, es1->es_len);
found = 1;
goto out;
}
node = tree->root.rb_node;
while (node) {
es1 = rb_entry(node, struct extent_status, rb_node);
if (lblk < es1->es_lblk)
node = node->rb_left;
else if (lblk > ext4_es_end(es1))
node = node->rb_right;
else {
found = 1;
break;
}
}
out:
stats = &EXT4_SB(inode->i_sb)->s_es_stats;
if (found) {
BUG_ON(!es1);
es->es_lblk = es1->es_lblk;
es->es_len = es1->es_len;
es->es_pblk = es1->es_pblk;
if (!ext4_es_is_referenced(es1))
ext4_es_set_referenced(es1);
percpu_counter_inc(&stats->es_stats_cache_hits);
if (next_lblk) {
node = rb_next(&es1->rb_node);
if (node) {
es1 = rb_entry(node, struct extent_status,
rb_node);
*next_lblk = es1->es_lblk;
} else
*next_lblk = 0;
}
} else {
percpu_counter_inc(&stats->es_stats_cache_misses);
}
read_unlock(&EXT4_I(inode)->i_es_lock);
trace_ext4_es_lookup_extent_exit(inode, es, found);
return found;
}
struct rsvd_count {
int ndelonly;
bool first_do_lblk_found;
ext4_lblk_t first_do_lblk;
ext4_lblk_t last_do_lblk;
struct extent_status *left_es;
bool partial;
ext4_lblk_t lclu;
};
/*
* init_rsvd - initialize reserved count data before removing block range
* in file from extent status tree
*
* @inode - file containing range
* @lblk - first block in range
* @es - pointer to first extent in range
* @rc - pointer to reserved count data
*
* Assumes es is not NULL
*/
static void init_rsvd(struct inode *inode, ext4_lblk_t lblk,
struct extent_status *es, struct rsvd_count *rc)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct rb_node *node;
rc->ndelonly = 0;
/*
* for bigalloc, note the first delonly block in the range has not
* been found, record the extent containing the block to the left of
* the region to be removed, if any, and note that there's no partial
* cluster to track
*/
if (sbi->s_cluster_ratio > 1) {
rc->first_do_lblk_found = false;
if (lblk > es->es_lblk) {
rc->left_es = es;
} else {
node = rb_prev(&es->rb_node);
rc->left_es = node ? rb_entry(node,
struct extent_status,
rb_node) : NULL;
}
rc->partial = false;
}
}
/*
* count_rsvd - count the clusters containing delayed and not unwritten
* (delonly) blocks in a range within an extent and add to
* the running tally in rsvd_count
*
* @inode - file containing extent
* @lblk - first block in range
* @len - length of range in blocks
* @es - pointer to extent containing clusters to be counted
* @rc - pointer to reserved count data
*
* Tracks partial clusters found at the beginning and end of extents so
* they aren't overcounted when they span adjacent extents
*/
static void count_rsvd(struct inode *inode, ext4_lblk_t lblk, long len,
struct extent_status *es, struct rsvd_count *rc)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_lblk_t i, end, nclu;
if (!ext4_es_is_delonly(es))
return;
WARN_ON(len <= 0);
if (sbi->s_cluster_ratio == 1) {
rc->ndelonly += (int) len;
return;
}
/* bigalloc */
i = (lblk < es->es_lblk) ? es->es_lblk : lblk;
end = lblk + (ext4_lblk_t) len - 1;
end = (end > ext4_es_end(es)) ? ext4_es_end(es) : end;
/* record the first block of the first delonly extent seen */
if (!rc->first_do_lblk_found) {
rc->first_do_lblk = i;
rc->first_do_lblk_found = true;
}
/* update the last lblk in the region seen so far */
rc->last_do_lblk = end;
/*
* if we're tracking a partial cluster and the current extent
* doesn't start with it, count it and stop tracking
*/
if (rc->partial && (rc->lclu != EXT4_B2C(sbi, i))) {
rc->ndelonly++;
rc->partial = false;
}
/*
* if the first cluster doesn't start on a cluster boundary but
* ends on one, count it
*/
if (EXT4_LBLK_COFF(sbi, i) != 0) {
if (end >= EXT4_LBLK_CFILL(sbi, i)) {
rc->ndelonly++;
rc->partial = false;
i = EXT4_LBLK_CFILL(sbi, i) + 1;
}
}
/*
* if the current cluster starts on a cluster boundary, count the
* number of whole delonly clusters in the extent
*/
if ((i + sbi->s_cluster_ratio - 1) <= end) {
nclu = (end - i + 1) >> sbi->s_cluster_bits;
rc->ndelonly += nclu;
i += nclu << sbi->s_cluster_bits;
}
/*
* start tracking a partial cluster if there's a partial at the end
* of the current extent and we're not already tracking one
*/
if (!rc->partial && i <= end) {
rc->partial = true;
rc->lclu = EXT4_B2C(sbi, i);
}
}
/*
* __pr_tree_search - search for a pending cluster reservation
*
* @root - root of pending reservation tree
* @lclu - logical cluster to search for
*
* Returns the pending reservation for the cluster identified by @lclu
* if found. If not, returns a reservation for the next cluster if any,
* and if not, returns NULL.
*/
static struct pending_reservation *__pr_tree_search(struct rb_root *root,
ext4_lblk_t lclu)
{
struct rb_node *node = root->rb_node;
struct pending_reservation *pr = NULL;
while (node) {
pr = rb_entry(node, struct pending_reservation, rb_node);
if (lclu < pr->lclu)
node = node->rb_left;
else if (lclu > pr->lclu)
node = node->rb_right;
else
return pr;
}
if (pr && lclu < pr->lclu)
return pr;
if (pr && lclu > pr->lclu) {
node = rb_next(&pr->rb_node);
return node ? rb_entry(node, struct pending_reservation,
rb_node) : NULL;
}
return NULL;
}
/*
* get_rsvd - calculates and returns the number of cluster reservations to be
* released when removing a block range from the extent status tree
* and releases any pending reservations within the range
*
* @inode - file containing block range
* @end - last block in range
* @right_es - pointer to extent containing next block beyond end or NULL
* @rc - pointer to reserved count data
*
* The number of reservations to be released is equal to the number of
* clusters containing delayed and not unwritten (delonly) blocks within
* the range, minus the number of clusters still containing delonly blocks
* at the ends of the range, and minus the number of pending reservations
* within the range.
*/
static unsigned int get_rsvd(struct inode *inode, ext4_lblk_t end,
struct extent_status *right_es,
struct rsvd_count *rc)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct pending_reservation *pr;
struct ext4_pending_tree *tree = &EXT4_I(inode)->i_pending_tree;
struct rb_node *node;
ext4_lblk_t first_lclu, last_lclu;
bool left_delonly, right_delonly, count_pending;
struct extent_status *es;
if (sbi->s_cluster_ratio > 1) {
/* count any remaining partial cluster */
if (rc->partial)
rc->ndelonly++;
if (rc->ndelonly == 0)
return 0;
first_lclu = EXT4_B2C(sbi, rc->first_do_lblk);
last_lclu = EXT4_B2C(sbi, rc->last_do_lblk);
/*
* decrease the delonly count by the number of clusters at the
* ends of the range that still contain delonly blocks -
* these clusters still need to be reserved
*/
left_delonly = right_delonly = false;
es = rc->left_es;
while (es && ext4_es_end(es) >=
EXT4_LBLK_CMASK(sbi, rc->first_do_lblk)) {
if (ext4_es_is_delonly(es)) {
rc->ndelonly--;
left_delonly = true;
break;
}
node = rb_prev(&es->rb_node);
if (!node)
break;
es = rb_entry(node, struct extent_status, rb_node);
}
if (right_es && (!left_delonly || first_lclu != last_lclu)) {
if (end < ext4_es_end(right_es)) {
es = right_es;
} else {
node = rb_next(&right_es->rb_node);
es = node ? rb_entry(node, struct extent_status,
rb_node) : NULL;
}
while (es && es->es_lblk <=
EXT4_LBLK_CFILL(sbi, rc->last_do_lblk)) {
if (ext4_es_is_delonly(es)) {
rc->ndelonly--;
right_delonly = true;
break;
}
node = rb_next(&es->rb_node);
if (!node)
break;
es = rb_entry(node, struct extent_status,
rb_node);
}
}
/*
* Determine the block range that should be searched for
* pending reservations, if any. Clusters on the ends of the
* original removed range containing delonly blocks are
* excluded. They've already been accounted for and it's not
* possible to determine if an associated pending reservation
* should be released with the information available in the
* extents status tree.
*/
if (first_lclu == last_lclu) {
if (left_delonly | right_delonly)
count_pending = false;
else
count_pending = true;
} else {
if (left_delonly)
first_lclu++;
if (right_delonly)
last_lclu--;
if (first_lclu <= last_lclu)
count_pending = true;
else
count_pending = false;
}
/*
* a pending reservation found between first_lclu and last_lclu
* represents an allocated cluster that contained at least one
* delonly block, so the delonly total must be reduced by one
* for each pending reservation found and released
*/
if (count_pending) {
pr = __pr_tree_search(&tree->root, first_lclu);
while (pr && pr->lclu <= last_lclu) {
rc->ndelonly--;
node = rb_next(&pr->rb_node);
rb_erase(&pr->rb_node, &tree->root);
kmem_cache_free(ext4_pending_cachep, pr);
if (!node)
break;
pr = rb_entry(node, struct pending_reservation,
rb_node);
}
}
}
return rc->ndelonly;
}
/*
* __es_remove_extent - removes block range from extent status tree
*
* @inode - file containing range
* @lblk - first block in range
* @end - last block in range
* @reserved - number of cluster reservations released
* @prealloc - pre-allocated es to avoid memory allocation failures
*
* If @reserved is not NULL and delayed allocation is enabled, counts
* block/cluster reservations freed by removing range and if bigalloc
* enabled cancels pending reservations as needed. Returns 0 on success,
* error code on failure.
*/
static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t end, int *reserved,
struct extent_status *prealloc)
{
struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
struct rb_node *node;
struct extent_status *es;
struct extent_status orig_es;
ext4_lblk_t len1, len2;
ext4_fsblk_t block;
int err = 0;
bool count_reserved = true;
struct rsvd_count rc;
if (reserved == NULL || !test_opt(inode->i_sb, DELALLOC))
count_reserved = false;
es = __es_tree_search(&tree->root, lblk);
if (!es)
goto out;
if (es->es_lblk > end)
goto out;
/* Simply invalidate cache_es. */
tree->cache_es = NULL;
if (count_reserved)
init_rsvd(inode, lblk, es, &rc);
orig_es.es_lblk = es->es_lblk;
orig_es.es_len = es->es_len;
orig_es.es_pblk = es->es_pblk;
len1 = lblk > es->es_lblk ? lblk - es->es_lblk : 0;
len2 = ext4_es_end(es) > end ? ext4_es_end(es) - end : 0;
if (len1 > 0)
es->es_len = len1;
if (len2 > 0) {
if (len1 > 0) {
struct extent_status newes;
newes.es_lblk = end + 1;
newes.es_len = len2;
block = 0x7FDEADBEEFULL;
if (ext4_es_is_written(&orig_es) ||
ext4_es_is_unwritten(&orig_es))
block = ext4_es_pblock(&orig_es) +
orig_es.es_len - len2;
ext4_es_store_pblock_status(&newes, block,
ext4_es_status(&orig_es));
err = __es_insert_extent(inode, &newes, prealloc);
if (err) {
if (!ext4_es_must_keep(&newes))
return 0;
es->es_lblk = orig_es.es_lblk;
es->es_len = orig_es.es_len;
goto out;
}
} else {
es->es_lblk = end + 1;
es->es_len = len2;
if (ext4_es_is_written(es) ||
ext4_es_is_unwritten(es)) {
block = orig_es.es_pblk + orig_es.es_len - len2;
ext4_es_store_pblock(es, block);
}
}
if (count_reserved)
count_rsvd(inode, lblk, orig_es.es_len - len1 - len2,
&orig_es, &rc);
goto out_get_reserved;
}
if (len1 > 0) {
if (count_reserved)
count_rsvd(inode, lblk, orig_es.es_len - len1,
&orig_es, &rc);
node = rb_next(&es->rb_node);
if (node)
es = rb_entry(node, struct extent_status, rb_node);
else
es = NULL;
}
while (es && ext4_es_end(es) <= end) {
if (count_reserved)
count_rsvd(inode, es->es_lblk, es->es_len, es, &rc);
node = rb_next(&es->rb_node);
rb_erase(&es->rb_node, &tree->root);
ext4_es_free_extent(inode, es);
if (!node) {
es = NULL;
break;
}
es = rb_entry(node, struct extent_status, rb_node);
}
if (es && es->es_lblk < end + 1) {
ext4_lblk_t orig_len = es->es_len;
len1 = ext4_es_end(es) - end;
if (count_reserved)
count_rsvd(inode, es->es_lblk, orig_len - len1,
es, &rc);
es->es_lblk = end + 1;
es->es_len = len1;
if (ext4_es_is_written(es) || ext4_es_is_unwritten(es)) {
block = es->es_pblk + orig_len - len1;
ext4_es_store_pblock(es, block);
}
}
out_get_reserved:
if (count_reserved)
*reserved = get_rsvd(inode, end, es, &rc);
out:
return err;
}
/*
* ext4_es_remove_extent - removes block range from extent status tree
*
* @inode - file containing range
* @lblk - first block in range
* @len - number of blocks to remove
*
* Reduces block/cluster reservation count and for bigalloc cancels pending
* reservations as needed.
*/
void ext4_es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len)
{
ext4_lblk_t end;
int err = 0;
int reserved = 0;
struct extent_status *es = NULL;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return;
trace_ext4_es_remove_extent(inode, lblk, len);
es_debug("remove [%u/%u) from extent status tree of inode %lu\n",
lblk, len, inode->i_ino);
if (!len)
return;
end = lblk + len - 1;
BUG_ON(end < lblk);
retry:
if (err && !es)
es = __es_alloc_extent(true);
/*
* ext4_clear_inode() depends on us taking i_es_lock unconditionally
* so that we are sure __es_shrink() is done with the inode before it
* is reclaimed.
*/
write_lock(&EXT4_I(inode)->i_es_lock);
err = __es_remove_extent(inode, lblk, end, &reserved, es);
/* Free preallocated extent if it didn't get used. */
if (es) {
if (!es->es_len)
__es_free_extent(es);
es = NULL;
}
write_unlock(&EXT4_I(inode)->i_es_lock);
if (err)
goto retry;
ext4_es_print_tree(inode);
ext4_da_release_space(inode, reserved);
return;
}
static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan,
struct ext4_inode_info *locked_ei)
{
struct ext4_inode_info *ei;
struct ext4_es_stats *es_stats;
ktime_t start_time;
u64 scan_time;
int nr_to_walk;
int nr_shrunk = 0;
int retried = 0, nr_skipped = 0;
es_stats = &sbi->s_es_stats;
start_time = ktime_get();
retry:
spin_lock(&sbi->s_es_lock);
nr_to_walk = sbi->s_es_nr_inode;
while (nr_to_walk-- > 0) {
if (list_empty(&sbi->s_es_list)) {
spin_unlock(&sbi->s_es_lock);
goto out;
}
ei = list_first_entry(&sbi->s_es_list, struct ext4_inode_info,
i_es_list);
/* Move the inode to the tail */
list_move_tail(&ei->i_es_list, &sbi->s_es_list);
/*
* Normally we try hard to avoid shrinking precached inodes,
* but we will as a last resort.
*/
if (!retried && ext4_test_inode_state(&ei->vfs_inode,
EXT4_STATE_EXT_PRECACHED)) {
nr_skipped++;
continue;
}
if (ei == locked_ei || !write_trylock(&ei->i_es_lock)) {
nr_skipped++;
continue;
}
/*
* Now we hold i_es_lock which protects us from inode reclaim
* freeing inode under us
*/
spin_unlock(&sbi->s_es_lock);
nr_shrunk += es_reclaim_extents(ei, &nr_to_scan);
write_unlock(&ei->i_es_lock);
if (nr_to_scan <= 0)
goto out;
spin_lock(&sbi->s_es_lock);
}
spin_unlock(&sbi->s_es_lock);
/*
* If we skipped any inodes, and we weren't able to make any
* forward progress, try again to scan precached inodes.
*/
if ((nr_shrunk == 0) && nr_skipped && !retried) {
retried++;
goto retry;
}
if (locked_ei && nr_shrunk == 0)
nr_shrunk = es_reclaim_extents(locked_ei, &nr_to_scan);
out:
scan_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
if (likely(es_stats->es_stats_scan_time))
es_stats->es_stats_scan_time = (scan_time +
es_stats->es_stats_scan_time*3) / 4;
else
es_stats->es_stats_scan_time = scan_time;
if (scan_time > es_stats->es_stats_max_scan_time)
es_stats->es_stats_max_scan_time = scan_time;
if (likely(es_stats->es_stats_shrunk))
es_stats->es_stats_shrunk = (nr_shrunk +
es_stats->es_stats_shrunk*3) / 4;
else
es_stats->es_stats_shrunk = nr_shrunk;
trace_ext4_es_shrink(sbi->s_sb, nr_shrunk, scan_time,
nr_skipped, retried);
return nr_shrunk;
}
static unsigned long ext4_es_count(struct shrinker *shrink,
struct shrink_control *sc)
{
unsigned long nr;
struct ext4_sb_info *sbi;
sbi = container_of(shrink, struct ext4_sb_info, s_es_shrinker);
nr = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
trace_ext4_es_shrink_count(sbi->s_sb, sc->nr_to_scan, nr);
return nr;
}
static unsigned long ext4_es_scan(struct shrinker *shrink,
struct shrink_control *sc)
{
struct ext4_sb_info *sbi = container_of(shrink,
struct ext4_sb_info, s_es_shrinker);
int nr_to_scan = sc->nr_to_scan;
int ret, nr_shrunk;
ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
trace_ext4_es_shrink_scan_enter(sbi->s_sb, nr_to_scan, ret);
nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL);
ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
trace_ext4_es_shrink_scan_exit(sbi->s_sb, nr_shrunk, ret);
return nr_shrunk;
}
int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v)
{
struct ext4_sb_info *sbi = EXT4_SB((struct super_block *) seq->private);
struct ext4_es_stats *es_stats = &sbi->s_es_stats;
struct ext4_inode_info *ei, *max = NULL;
unsigned int inode_cnt = 0;
if (v != SEQ_START_TOKEN)
return 0;
/* here we just find an inode that has the max nr. of objects */
spin_lock(&sbi->s_es_lock);
list_for_each_entry(ei, &sbi->s_es_list, i_es_list) {
inode_cnt++;
if (max && max->i_es_all_nr < ei->i_es_all_nr)
max = ei;
else if (!max)
max = ei;
}
spin_unlock(&sbi->s_es_lock);
seq_printf(seq, "stats:\n %lld objects\n %lld reclaimable objects\n",
percpu_counter_sum_positive(&es_stats->es_stats_all_cnt),
percpu_counter_sum_positive(&es_stats->es_stats_shk_cnt));
seq_printf(seq, " %lld/%lld cache hits/misses\n",
percpu_counter_sum_positive(&es_stats->es_stats_cache_hits),
percpu_counter_sum_positive(&es_stats->es_stats_cache_misses));
if (inode_cnt)
seq_printf(seq, " %d inodes on list\n", inode_cnt);
seq_printf(seq, "average:\n %llu us scan time\n",
div_u64(es_stats->es_stats_scan_time, 1000));
seq_printf(seq, " %lu shrunk objects\n", es_stats->es_stats_shrunk);
if (inode_cnt)
seq_printf(seq,
"maximum:\n %lu inode (%u objects, %u reclaimable)\n"
" %llu us max scan time\n",
max->vfs_inode.i_ino, max->i_es_all_nr, max->i_es_shk_nr,
div_u64(es_stats->es_stats_max_scan_time, 1000));
return 0;
}
int ext4_es_register_shrinker(struct ext4_sb_info *sbi)
{
int err;
/* Make sure we have enough bits for physical block number */
BUILD_BUG_ON(ES_SHIFT < 48);
INIT_LIST_HEAD(&sbi->s_es_list);
sbi->s_es_nr_inode = 0;
spin_lock_init(&sbi->s_es_lock);
sbi->s_es_stats.es_stats_shrunk = 0;
err = percpu_counter_init(&sbi->s_es_stats.es_stats_cache_hits, 0,
GFP_KERNEL);
if (err)
return err;
err = percpu_counter_init(&sbi->s_es_stats.es_stats_cache_misses, 0,
GFP_KERNEL);
if (err)
goto err1;
sbi->s_es_stats.es_stats_scan_time = 0;
sbi->s_es_stats.es_stats_max_scan_time = 0;
err = percpu_counter_init(&sbi->s_es_stats.es_stats_all_cnt, 0, GFP_KERNEL);
if (err)
goto err2;
err = percpu_counter_init(&sbi->s_es_stats.es_stats_shk_cnt, 0, GFP_KERNEL);
if (err)
goto err3;
sbi->s_es_shrinker.scan_objects = ext4_es_scan;
sbi->s_es_shrinker.count_objects = ext4_es_count;
sbi->s_es_shrinker.seeks = DEFAULT_SEEKS;
err = register_shrinker(&sbi->s_es_shrinker, "ext4-es:%s",
sbi->s_sb->s_id);
if (err)
goto err4;
return 0;
err4:
percpu_counter_destroy(&sbi->s_es_stats.es_stats_shk_cnt);
err3:
percpu_counter_destroy(&sbi->s_es_stats.es_stats_all_cnt);
err2:
percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_misses);
err1:
percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_hits);
return err;
}
void ext4_es_unregister_shrinker(struct ext4_sb_info *sbi)
{
percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_hits);
percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_misses);
percpu_counter_destroy(&sbi->s_es_stats.es_stats_all_cnt);
percpu_counter_destroy(&sbi->s_es_stats.es_stats_shk_cnt);
unregister_shrinker(&sbi->s_es_shrinker);
}
/*
* Shrink extents in given inode from ei->i_es_shrink_lblk till end. Scan at
* most *nr_to_scan extents, update *nr_to_scan accordingly.
*
* Return 0 if we hit end of tree / interval, 1 if we exhausted nr_to_scan.
* Increment *nr_shrunk by the number of reclaimed extents. Also update
* ei->i_es_shrink_lblk to where we should continue scanning.
*/
static int es_do_reclaim_extents(struct ext4_inode_info *ei, ext4_lblk_t end,
int *nr_to_scan, int *nr_shrunk)
{
struct inode *inode = &ei->vfs_inode;
struct ext4_es_tree *tree = &ei->i_es_tree;
struct extent_status *es;
struct rb_node *node;
es = __es_tree_search(&tree->root, ei->i_es_shrink_lblk);
if (!es)
goto out_wrap;
while (*nr_to_scan > 0) {
if (es->es_lblk > end) {
ei->i_es_shrink_lblk = end + 1;
return 0;
}
(*nr_to_scan)--;
node = rb_next(&es->rb_node);
if (ext4_es_must_keep(es))
goto next;
if (ext4_es_is_referenced(es)) {
ext4_es_clear_referenced(es);
goto next;
}
rb_erase(&es->rb_node, &tree->root);
ext4_es_free_extent(inode, es);
(*nr_shrunk)++;
next:
if (!node)
goto out_wrap;
es = rb_entry(node, struct extent_status, rb_node);
}
ei->i_es_shrink_lblk = es->es_lblk;
return 1;
out_wrap:
ei->i_es_shrink_lblk = 0;
return 0;
}
static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan)
{
struct inode *inode = &ei->vfs_inode;
int nr_shrunk = 0;
ext4_lblk_t start = ei->i_es_shrink_lblk;
static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST);
if (ei->i_es_shk_nr == 0)
return 0;
if (ext4_test_inode_state(inode, EXT4_STATE_EXT_PRECACHED) &&
__ratelimit(&_rs))
ext4_warning(inode->i_sb, "forced shrink of precached extents");
if (!es_do_reclaim_extents(ei, EXT_MAX_BLOCKS, nr_to_scan, &nr_shrunk) &&
start != 0)
es_do_reclaim_extents(ei, start - 1, nr_to_scan, &nr_shrunk);
ei->i_es_tree.cache_es = NULL;
return nr_shrunk;
}
/*
* Called to support EXT4_IOC_CLEAR_ES_CACHE. We can only remove
* discretionary entries from the extent status cache. (Some entries
* must be present for proper operations.)
*/
void ext4_clear_inode_es(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct extent_status *es;
struct ext4_es_tree *tree;
struct rb_node *node;
write_lock(&ei->i_es_lock);
tree = &EXT4_I(inode)->i_es_tree;
tree->cache_es = NULL;
node = rb_first(&tree->root);
while (node) {
es = rb_entry(node, struct extent_status, rb_node);
node = rb_next(node);
if (!ext4_es_must_keep(es)) {
rb_erase(&es->rb_node, &tree->root);
ext4_es_free_extent(inode, es);
}
}
ext4_clear_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
write_unlock(&ei->i_es_lock);
}
#ifdef ES_DEBUG__
static void ext4_print_pending_tree(struct inode *inode)
{
struct ext4_pending_tree *tree;
struct rb_node *node;
struct pending_reservation *pr;
printk(KERN_DEBUG "pending reservations for inode %lu:", inode->i_ino);
tree = &EXT4_I(inode)->i_pending_tree;
node = rb_first(&tree->root);
while (node) {
pr = rb_entry(node, struct pending_reservation, rb_node);
printk(KERN_DEBUG " %u", pr->lclu);
node = rb_next(node);
}
printk(KERN_DEBUG "\n");
}
#else
#define ext4_print_pending_tree(inode)
#endif
int __init ext4_init_pending(void)
{
ext4_pending_cachep = KMEM_CACHE(pending_reservation, SLAB_RECLAIM_ACCOUNT);
if (ext4_pending_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_exit_pending(void)
{
kmem_cache_destroy(ext4_pending_cachep);
}
void ext4_init_pending_tree(struct ext4_pending_tree *tree)
{
tree->root = RB_ROOT;
}
/*
* __get_pending - retrieve a pointer to a pending reservation
*
* @inode - file containing the pending cluster reservation
* @lclu - logical cluster of interest
*
* Returns a pointer to a pending reservation if it's a member of
* the set, and NULL if not. Must be called holding i_es_lock.
*/
static struct pending_reservation *__get_pending(struct inode *inode,
ext4_lblk_t lclu)
{
struct ext4_pending_tree *tree;
struct rb_node *node;
struct pending_reservation *pr = NULL;
tree = &EXT4_I(inode)->i_pending_tree;
node = (&tree->root)->rb_node;
while (node) {
pr = rb_entry(node, struct pending_reservation, rb_node);
if (lclu < pr->lclu)
node = node->rb_left;
else if (lclu > pr->lclu)
node = node->rb_right;
else if (lclu == pr->lclu)
return pr;
}
return NULL;
}
/*
* __insert_pending - adds a pending cluster reservation to the set of
* pending reservations
*
* @inode - file containing the cluster
* @lblk - logical block in the cluster to be added
*
* Returns 0 on successful insertion and -ENOMEM on failure. If the
* pending reservation is already in the set, returns successfully.
*/
static int __insert_pending(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_pending_tree *tree = &EXT4_I(inode)->i_pending_tree;
struct rb_node **p = &tree->root.rb_node;
struct rb_node *parent = NULL;
struct pending_reservation *pr;
ext4_lblk_t lclu;
int ret = 0;
lclu = EXT4_B2C(sbi, lblk);
/* search to find parent for insertion */
while (*p) {
parent = *p;
pr = rb_entry(parent, struct pending_reservation, rb_node);
if (lclu < pr->lclu) {
p = &(*p)->rb_left;
} else if (lclu > pr->lclu) {
p = &(*p)->rb_right;
} else {
/* pending reservation already inserted */
goto out;
}
}
pr = kmem_cache_alloc(ext4_pending_cachep, GFP_ATOMIC);
if (pr == NULL) {
ret = -ENOMEM;
goto out;
}
pr->lclu = lclu;
rb_link_node(&pr->rb_node, parent, p);
rb_insert_color(&pr->rb_node, &tree->root);
out:
return ret;
}
/*
* __remove_pending - removes a pending cluster reservation from the set
* of pending reservations
*
* @inode - file containing the cluster
* @lblk - logical block in the pending cluster reservation to be removed
*
* Returns successfully if pending reservation is not a member of the set.
*/
static void __remove_pending(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct pending_reservation *pr;
struct ext4_pending_tree *tree;
pr = __get_pending(inode, EXT4_B2C(sbi, lblk));
if (pr != NULL) {
tree = &EXT4_I(inode)->i_pending_tree;
rb_erase(&pr->rb_node, &tree->root);
kmem_cache_free(ext4_pending_cachep, pr);
}
}
/*
* ext4_remove_pending - removes a pending cluster reservation from the set
* of pending reservations
*
* @inode - file containing the cluster
* @lblk - logical block in the pending cluster reservation to be removed
*
* Locking for external use of __remove_pending.
*/
void ext4_remove_pending(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_inode_info *ei = EXT4_I(inode);
write_lock(&ei->i_es_lock);
__remove_pending(inode, lblk);
write_unlock(&ei->i_es_lock);
}
/*
* ext4_is_pending - determine whether a cluster has a pending reservation
* on it
*
* @inode - file containing the cluster
* @lblk - logical block in the cluster
*
* Returns true if there's a pending reservation for the cluster in the
* set of pending reservations, and false if not.
*/
bool ext4_is_pending(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
bool ret;
read_lock(&ei->i_es_lock);
ret = (bool)(__get_pending(inode, EXT4_B2C(sbi, lblk)) != NULL);
read_unlock(&ei->i_es_lock);
return ret;
}
/*
* ext4_es_insert_delayed_block - adds a delayed block to the extents status
* tree, adding a pending reservation where
* needed
*
* @inode - file containing the newly added block
* @lblk - logical block to be added
* @allocated - indicates whether a physical cluster has been allocated for
* the logical cluster that contains the block
*/
void ext4_es_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk,
bool allocated)
{
struct extent_status newes;
int err1 = 0;
int err2 = 0;
struct extent_status *es1 = NULL;
struct extent_status *es2 = NULL;
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
return;
es_debug("add [%u/1) delayed to extent status tree of inode %lu\n",
lblk, inode->i_ino);
newes.es_lblk = lblk;
newes.es_len = 1;
ext4_es_store_pblock_status(&newes, ~0, EXTENT_STATUS_DELAYED);
trace_ext4_es_insert_delayed_block(inode, &newes, allocated);
ext4_es_insert_extent_check(inode, &newes);
retry:
if (err1 && !es1)
es1 = __es_alloc_extent(true);
if ((err1 || err2) && !es2)
es2 = __es_alloc_extent(true);
write_lock(&EXT4_I(inode)->i_es_lock);
err1 = __es_remove_extent(inode, lblk, lblk, NULL, es1);
if (err1 != 0)
goto error;
/* Free preallocated extent if it didn't get used. */
if (es1) {
if (!es1->es_len)
__es_free_extent(es1);
es1 = NULL;
}
err2 = __es_insert_extent(inode, &newes, es2);
if (err2 != 0)
goto error;
/* Free preallocated extent if it didn't get used. */
if (es2) {
if (!es2->es_len)
__es_free_extent(es2);
es2 = NULL;
}
if (allocated)
__insert_pending(inode, lblk);
error:
write_unlock(&EXT4_I(inode)->i_es_lock);
if (err1 || err2)
goto retry;
ext4_es_print_tree(inode);
ext4_print_pending_tree(inode);
return;
}
/*
* __es_delayed_clu - count number of clusters containing blocks that
* are delayed only
*
* @inode - file containing block range
* @start - logical block defining start of range
* @end - logical block defining end of range
*
* Returns the number of clusters containing only delayed (not delayed
* and unwritten) blocks in the range specified by @start and @end. Any
* cluster or part of a cluster within the range and containing a delayed
* and not unwritten block within the range is counted as a whole cluster.
*/
static unsigned int __es_delayed_clu(struct inode *inode, ext4_lblk_t start,
ext4_lblk_t end)
{
struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
struct extent_status *es;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct rb_node *node;
ext4_lblk_t first_lclu, last_lclu;
unsigned long long last_counted_lclu;
unsigned int n = 0;
/* guaranteed to be unequal to any ext4_lblk_t value */
last_counted_lclu = ~0ULL;
es = __es_tree_search(&tree->root, start);
while (es && (es->es_lblk <= end)) {
if (ext4_es_is_delonly(es)) {
if (es->es_lblk <= start)
first_lclu = EXT4_B2C(sbi, start);
else
first_lclu = EXT4_B2C(sbi, es->es_lblk);
if (ext4_es_end(es) >= end)
last_lclu = EXT4_B2C(sbi, end);
else
last_lclu = EXT4_B2C(sbi, ext4_es_end(es));
if (first_lclu == last_counted_lclu)
n += last_lclu - first_lclu;
else
n += last_lclu - first_lclu + 1;
last_counted_lclu = last_lclu;
}
node = rb_next(&es->rb_node);
if (!node)
break;
es = rb_entry(node, struct extent_status, rb_node);
}
return n;
}
/*
* ext4_es_delayed_clu - count number of clusters containing blocks that
* are both delayed and unwritten
*
* @inode - file containing block range
* @lblk - logical block defining start of range
* @len - number of blocks in range
*
* Locking for external use of __es_delayed_clu().
*/
unsigned int ext4_es_delayed_clu(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len)
{
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_lblk_t end;
unsigned int n;
if (len == 0)
return 0;
end = lblk + len - 1;
WARN_ON(end < lblk);
read_lock(&ei->i_es_lock);
n = __es_delayed_clu(inode, lblk, end);
read_unlock(&ei->i_es_lock);
return n;
}
/*
* __revise_pending - makes, cancels, or leaves unchanged pending cluster
* reservations for a specified block range depending
* upon the presence or absence of delayed blocks
* outside the range within clusters at the ends of the
* range
*
* @inode - file containing the range
* @lblk - logical block defining the start of range
* @len - length of range in blocks
*
* Used after a newly allocated extent is added to the extents status tree.
* Requires that the extents in the range have either written or unwritten
* status. Must be called while holding i_es_lock.
*/
static void __revise_pending(struct inode *inode, ext4_lblk_t lblk,
ext4_lblk_t len)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_lblk_t end = lblk + len - 1;
ext4_lblk_t first, last;
bool f_del = false, l_del = false;
if (len == 0)
return;
/*
* Two cases - block range within single cluster and block range
* spanning two or more clusters. Note that a cluster belonging
* to a range starting and/or ending on a cluster boundary is treated
* as if it does not contain a delayed extent. The new range may
* have allocated space for previously delayed blocks out to the
* cluster boundary, requiring that any pre-existing pending
* reservation be canceled. Because this code only looks at blocks
* outside the range, it should revise pending reservations
* correctly even if the extent represented by the range can't be
* inserted in the extents status tree due to ENOSPC.
*/
if (EXT4_B2C(sbi, lblk) == EXT4_B2C(sbi, end)) {
first = EXT4_LBLK_CMASK(sbi, lblk);
if (first != lblk)
f_del = __es_scan_range(inode, &ext4_es_is_delonly,
first, lblk - 1);
if (f_del) {
__insert_pending(inode, first);
} else {
last = EXT4_LBLK_CMASK(sbi, end) +
sbi->s_cluster_ratio - 1;
if (last != end)
l_del = __es_scan_range(inode,
&ext4_es_is_delonly,
end + 1, last);
if (l_del)
__insert_pending(inode, last);
else
__remove_pending(inode, last);
}
} else {
first = EXT4_LBLK_CMASK(sbi, lblk);
if (first != lblk)
f_del = __es_scan_range(inode, &ext4_es_is_delonly,
first, lblk - 1);
if (f_del)
__insert_pending(inode, first);
else
__remove_pending(inode, first);
last = EXT4_LBLK_CMASK(sbi, end) + sbi->s_cluster_ratio - 1;
if (last != end)
l_del = __es_scan_range(inode, &ext4_es_is_delonly,
end + 1, last);
if (l_del)
__insert_pending(inode, last);
else
__remove_pending(inode, last);
}
}
| linux-master | fs/ext4/extents_status.c |
// SPDX-License-Identifier: GPL-2.0
/*
* KUnit test of ext4 inode that verify the seconds part of [a/c/m]
* timestamps in ext4 inode structs are decoded correctly.
*/
#include <kunit/test.h>
#include <linux/kernel.h>
#include <linux/time64.h>
#include "ext4.h"
/*
* For constructing the nonnegative timestamp lower bound value.
* binary: 00000000 00000000 00000000 00000000
*/
#define LOWER_MSB_0 0L
/*
* For constructing the nonnegative timestamp upper bound value.
* binary: 01111111 11111111 11111111 11111111
*
*/
#define UPPER_MSB_0 0x7fffffffL
/*
* For constructing the negative timestamp lower bound value.
* binary: 10000000 00000000 00000000 00000000
*/
#define LOWER_MSB_1 (-(UPPER_MSB_0) - 1L) /* avoid overflow */
/*
* For constructing the negative timestamp upper bound value.
* binary: 11111111 11111111 11111111 11111111
*/
#define UPPER_MSB_1 (-1L)
/*
* Upper bound for nanoseconds value supported by the encoding.
* binary: 00111111 11111111 11111111 11111111
*/
#define MAX_NANOSECONDS ((1L << 30) - 1)
#define CASE_NAME_FORMAT "%s: msb:%x lower_bound:%x extra_bits: %x"
#define LOWER_BOUND_NEG_NO_EXTRA_BITS_CASE\
"1901-12-13 Lower bound of 32bit < 0 timestamp, no extra bits"
#define UPPER_BOUND_NEG_NO_EXTRA_BITS_CASE\
"1969-12-31 Upper bound of 32bit < 0 timestamp, no extra bits"
#define LOWER_BOUND_NONNEG_NO_EXTRA_BITS_CASE\
"1970-01-01 Lower bound of 32bit >=0 timestamp, no extra bits"
#define UPPER_BOUND_NONNEG_NO_EXTRA_BITS_CASE\
"2038-01-19 Upper bound of 32bit >=0 timestamp, no extra bits"
#define LOWER_BOUND_NEG_LO_1_CASE\
"2038-01-19 Lower bound of 32bit <0 timestamp, lo extra sec bit on"
#define UPPER_BOUND_NEG_LO_1_CASE\
"2106-02-07 Upper bound of 32bit <0 timestamp, lo extra sec bit on"
#define LOWER_BOUND_NONNEG_LO_1_CASE\
"2106-02-07 Lower bound of 32bit >=0 timestamp, lo extra sec bit on"
#define UPPER_BOUND_NONNEG_LO_1_CASE\
"2174-02-25 Upper bound of 32bit >=0 timestamp, lo extra sec bit on"
#define LOWER_BOUND_NEG_HI_1_CASE\
"2174-02-25 Lower bound of 32bit <0 timestamp, hi extra sec bit on"
#define UPPER_BOUND_NEG_HI_1_CASE\
"2242-03-16 Upper bound of 32bit <0 timestamp, hi extra sec bit on"
#define LOWER_BOUND_NONNEG_HI_1_CASE\
"2242-03-16 Lower bound of 32bit >=0 timestamp, hi extra sec bit on"
#define UPPER_BOUND_NONNEG_HI_1_CASE\
"2310-04-04 Upper bound of 32bit >=0 timestamp, hi extra sec bit on"
#define UPPER_BOUND_NONNEG_HI_1_NS_1_CASE\
"2310-04-04 Upper bound of 32bit>=0 timestamp, hi extra sec bit 1. 1 ns"
#define LOWER_BOUND_NONNEG_HI_1_NS_MAX_CASE\
"2378-04-22 Lower bound of 32bit>= timestamp. Extra sec bits 1. Max ns"
#define LOWER_BOUND_NONNEG_EXTRA_BITS_1_CASE\
"2378-04-22 Lower bound of 32bit >=0 timestamp. All extra sec bits on"
#define UPPER_BOUND_NONNEG_EXTRA_BITS_1_CASE\
"2446-05-10 Upper bound of 32bit >=0 timestamp. All extra sec bits on"
struct timestamp_expectation {
const char *test_case_name;
struct timespec64 expected;
u32 extra_bits;
bool msb_set;
bool lower_bound;
};
static const struct timestamp_expectation test_data[] = {
{
.test_case_name = LOWER_BOUND_NEG_NO_EXTRA_BITS_CASE,
.msb_set = true,
.lower_bound = true,
.extra_bits = 0,
.expected = {.tv_sec = -0x80000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NEG_NO_EXTRA_BITS_CASE,
.msb_set = true,
.lower_bound = false,
.extra_bits = 0,
.expected = {.tv_sec = -1LL, .tv_nsec = 0L},
},
{
.test_case_name = LOWER_BOUND_NONNEG_NO_EXTRA_BITS_CASE,
.msb_set = false,
.lower_bound = true,
.extra_bits = 0,
.expected = {0LL, 0L},
},
{
.test_case_name = UPPER_BOUND_NONNEG_NO_EXTRA_BITS_CASE,
.msb_set = false,
.lower_bound = false,
.extra_bits = 0,
.expected = {.tv_sec = 0x7fffffffLL, .tv_nsec = 0L},
},
{
.test_case_name = LOWER_BOUND_NEG_LO_1_CASE,
.msb_set = true,
.lower_bound = true,
.extra_bits = 1,
.expected = {.tv_sec = 0x80000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NEG_LO_1_CASE,
.msb_set = true,
.lower_bound = false,
.extra_bits = 1,
.expected = {.tv_sec = 0xffffffffLL, .tv_nsec = 0L},
},
{
.test_case_name = LOWER_BOUND_NONNEG_LO_1_CASE,
.msb_set = false,
.lower_bound = true,
.extra_bits = 1,
.expected = {.tv_sec = 0x100000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NONNEG_LO_1_CASE,
.msb_set = false,
.lower_bound = false,
.extra_bits = 1,
.expected = {.tv_sec = 0x17fffffffLL, .tv_nsec = 0L},
},
{
.test_case_name = LOWER_BOUND_NEG_HI_1_CASE,
.msb_set = true,
.lower_bound = true,
.extra_bits = 2,
.expected = {.tv_sec = 0x180000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NEG_HI_1_CASE,
.msb_set = true,
.lower_bound = false,
.extra_bits = 2,
.expected = {.tv_sec = 0x1ffffffffLL, .tv_nsec = 0L},
},
{
.test_case_name = LOWER_BOUND_NONNEG_HI_1_CASE,
.msb_set = false,
.lower_bound = true,
.extra_bits = 2,
.expected = {.tv_sec = 0x200000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NONNEG_HI_1_CASE,
.msb_set = false,
.lower_bound = false,
.extra_bits = 2,
.expected = {.tv_sec = 0x27fffffffLL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NONNEG_HI_1_NS_1_CASE,
.msb_set = false,
.lower_bound = false,
.extra_bits = 6,
.expected = {.tv_sec = 0x27fffffffLL, .tv_nsec = 1L},
},
{
.test_case_name = LOWER_BOUND_NONNEG_HI_1_NS_MAX_CASE,
.msb_set = false,
.lower_bound = true,
.extra_bits = 0xFFFFFFFF,
.expected = {.tv_sec = 0x300000000LL,
.tv_nsec = MAX_NANOSECONDS},
},
{
.test_case_name = LOWER_BOUND_NONNEG_EXTRA_BITS_1_CASE,
.msb_set = false,
.lower_bound = true,
.extra_bits = 3,
.expected = {.tv_sec = 0x300000000LL, .tv_nsec = 0L},
},
{
.test_case_name = UPPER_BOUND_NONNEG_EXTRA_BITS_1_CASE,
.msb_set = false,
.lower_bound = false,
.extra_bits = 3,
.expected = {.tv_sec = 0x37fffffffLL, .tv_nsec = 0L},
}
};
static void timestamp_expectation_to_desc(const struct timestamp_expectation *t,
char *desc)
{
strscpy(desc, t->test_case_name, KUNIT_PARAM_DESC_SIZE);
}
KUNIT_ARRAY_PARAM(ext4_inode, test_data, timestamp_expectation_to_desc);
static time64_t get_32bit_time(const struct timestamp_expectation * const test)
{
if (test->msb_set) {
if (test->lower_bound)
return LOWER_MSB_1;
return UPPER_MSB_1;
}
if (test->lower_bound)
return LOWER_MSB_0;
return UPPER_MSB_0;
}
/*
* Test data is derived from the table in the Inode Timestamps section of
* Documentation/filesystems/ext4/inodes.rst.
*/
static void inode_test_xtimestamp_decoding(struct kunit *test)
{
struct timespec64 timestamp;
struct timestamp_expectation *test_param =
(struct timestamp_expectation *)(test->param_value);
timestamp = ext4_decode_extra_time(
cpu_to_le32(get_32bit_time(test_param)),
cpu_to_le32(test_param->extra_bits));
KUNIT_EXPECT_EQ_MSG(test,
test_param->expected.tv_sec,
timestamp.tv_sec,
CASE_NAME_FORMAT,
test_param->test_case_name,
test_param->msb_set,
test_param->lower_bound,
test_param->extra_bits);
KUNIT_EXPECT_EQ_MSG(test,
test_param->expected.tv_nsec,
timestamp.tv_nsec,
CASE_NAME_FORMAT,
test_param->test_case_name,
test_param->msb_set,
test_param->lower_bound,
test_param->extra_bits);
}
static struct kunit_case ext4_inode_test_cases[] = {
KUNIT_CASE_PARAM(inode_test_xtimestamp_decoding, ext4_inode_gen_params),
{}
};
static struct kunit_suite ext4_inode_test_suite = {
.name = "ext4_inode_test",
.test_cases = ext4_inode_test_cases,
};
kunit_test_suites(&ext4_inode_test_suite);
MODULE_LICENSE("GPL v2");
| linux-master | fs/ext4/inode-test.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/fsync.c
*
* Copyright (C) 1993 Stephen Tweedie ([email protected])
* from
* Copyright (C) 1992 Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
* from
* linux/fs/minix/truncate.c Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4fs fsync primitive
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*
* Removed unnecessary code duplication for little endian machines
* and excessive __inline__s.
* Andi Kleen, 1997
*
* Major simplications and cleanup - we only need to do the metadata, because
* we can depend on generic_block_fdatasync() to sync the data blocks.
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include <trace/events/ext4.h>
/*
* If we're not journaling and this is a just-created file, we have to
* sync our parent directory (if it was freshly created) since
* otherwise it will only be written by writeback, leaving a huge
* window during which a crash may lose the file. This may apply for
* the parent directory's parent as well, and so on recursively, if
* they are also freshly created.
*/
static int ext4_sync_parent(struct inode *inode)
{
struct dentry *dentry, *next;
int ret = 0;
if (!ext4_test_inode_state(inode, EXT4_STATE_NEWENTRY))
return 0;
dentry = d_find_any_alias(inode);
if (!dentry)
return 0;
while (ext4_test_inode_state(inode, EXT4_STATE_NEWENTRY)) {
ext4_clear_inode_state(inode, EXT4_STATE_NEWENTRY);
next = dget_parent(dentry);
dput(dentry);
dentry = next;
inode = dentry->d_inode;
/*
* The directory inode may have gone through rmdir by now. But
* the inode itself and its blocks are still allocated (we hold
* a reference to the inode via its dentry), so it didn't go
* through ext4_evict_inode()) and so we are safe to flush
* metadata blocks and the inode.
*/
ret = sync_mapping_buffers(inode->i_mapping);
if (ret)
break;
ret = sync_inode_metadata(inode, 1);
if (ret)
break;
}
dput(dentry);
return ret;
}
static int ext4_fsync_nojournal(struct file *file, loff_t start, loff_t end,
int datasync, bool *needs_barrier)
{
struct inode *inode = file->f_inode;
int ret;
ret = generic_buffers_fsync_noflush(file, start, end, datasync);
if (!ret)
ret = ext4_sync_parent(inode);
if (test_opt(inode->i_sb, BARRIER))
*needs_barrier = true;
return ret;
}
static int ext4_fsync_journal(struct inode *inode, bool datasync,
bool *needs_barrier)
{
struct ext4_inode_info *ei = EXT4_I(inode);
journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
tid_t commit_tid = datasync ? ei->i_datasync_tid : ei->i_sync_tid;
/*
* Fastcommit does not really support fsync on directories or other
* special files. Force a full commit.
*/
if (!S_ISREG(inode->i_mode))
return ext4_force_commit(inode->i_sb);
if (journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(journal, commit_tid))
*needs_barrier = true;
return ext4_fc_commit(journal, commit_tid);
}
/*
* akpm: A new design for ext4_sync_file().
*
* This is only called from sys_fsync(), sys_fdatasync() and sys_msync().
* There cannot be a transaction open by this task.
* Another task could have dirtied this inode. Its data can be in any
* state in the journalling system.
*
* What we do is just kick off a commit and wait on it. This will snapshot the
* inode to disk.
*/
int ext4_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
{
int ret = 0, err;
bool needs_barrier = false;
struct inode *inode = file->f_mapping->host;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
ASSERT(ext4_journal_current_handle() == NULL);
trace_ext4_sync_file_enter(file, datasync);
if (sb_rdonly(inode->i_sb)) {
/* Make sure that we read updated s_ext4_flags value */
smp_rmb();
if (ext4_forced_shutdown(inode->i_sb))
ret = -EROFS;
goto out;
}
if (!EXT4_SB(inode->i_sb)->s_journal) {
ret = ext4_fsync_nojournal(file, start, end, datasync,
&needs_barrier);
if (needs_barrier)
goto issue_flush;
goto out;
}
ret = file_write_and_wait_range(file, start, end);
if (ret)
goto out;
/*
* The caller's filemap_fdatawrite()/wait will sync the data.
* Metadata is in the journal, we wait for proper transaction to
* commit here.
*/
ret = ext4_fsync_journal(inode, datasync, &needs_barrier);
issue_flush:
if (needs_barrier) {
err = blkdev_issue_flush(inode->i_sb->s_bdev);
if (!ret)
ret = err;
}
out:
err = file_check_and_advance_wb_err(file);
if (ret == 0)
ret = err;
trace_ext4_sync_file_exit(inode, ret);
return ret;
}
| linux-master | fs/ext4/fsync.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/hash.c
*
* Copyright (C) 2002 by Theodore Ts'o
*/
#include <linux/fs.h>
#include <linux/unicode.h>
#include <linux/compiler.h>
#include <linux/bitops.h>
#include "ext4.h"
#define DELTA 0x9E3779B9
static void TEA_transform(__u32 buf[4], __u32 const in[])
{
__u32 sum = 0;
__u32 b0 = buf[0], b1 = buf[1];
__u32 a = in[0], b = in[1], c = in[2], d = in[3];
int n = 16;
do {
sum += DELTA;
b0 += ((b1 << 4)+a) ^ (b1+sum) ^ ((b1 >> 5)+b);
b1 += ((b0 << 4)+c) ^ (b0+sum) ^ ((b0 >> 5)+d);
} while (--n);
buf[0] += b0;
buf[1] += b1;
}
/* F, G and H are basic MD4 functions: selection, majority, parity */
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
/*
* The generic round function. The application is so specific that
* we don't bother protecting all the arguments with parens, as is generally
* good macro practice, in favor of extra legibility.
* Rotation is separate from addition to prevent recomputation
*/
#define ROUND(f, a, b, c, d, x, s) \
(a += f(b, c, d) + x, a = rol32(a, s))
#define K1 0
#define K2 013240474631UL
#define K3 015666365641UL
/*
* Basic cut-down MD4 transform. Returns only 32 bits of result.
*/
static __u32 half_md4_transform(__u32 buf[4], __u32 const in[8])
{
__u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
/* Round 1 */
ROUND(F, a, b, c, d, in[0] + K1, 3);
ROUND(F, d, a, b, c, in[1] + K1, 7);
ROUND(F, c, d, a, b, in[2] + K1, 11);
ROUND(F, b, c, d, a, in[3] + K1, 19);
ROUND(F, a, b, c, d, in[4] + K1, 3);
ROUND(F, d, a, b, c, in[5] + K1, 7);
ROUND(F, c, d, a, b, in[6] + K1, 11);
ROUND(F, b, c, d, a, in[7] + K1, 19);
/* Round 2 */
ROUND(G, a, b, c, d, in[1] + K2, 3);
ROUND(G, d, a, b, c, in[3] + K2, 5);
ROUND(G, c, d, a, b, in[5] + K2, 9);
ROUND(G, b, c, d, a, in[7] + K2, 13);
ROUND(G, a, b, c, d, in[0] + K2, 3);
ROUND(G, d, a, b, c, in[2] + K2, 5);
ROUND(G, c, d, a, b, in[4] + K2, 9);
ROUND(G, b, c, d, a, in[6] + K2, 13);
/* Round 3 */
ROUND(H, a, b, c, d, in[3] + K3, 3);
ROUND(H, d, a, b, c, in[7] + K3, 9);
ROUND(H, c, d, a, b, in[2] + K3, 11);
ROUND(H, b, c, d, a, in[6] + K3, 15);
ROUND(H, a, b, c, d, in[1] + K3, 3);
ROUND(H, d, a, b, c, in[5] + K3, 9);
ROUND(H, c, d, a, b, in[0] + K3, 11);
ROUND(H, b, c, d, a, in[4] + K3, 15);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
return buf[1]; /* "most hashed" word */
}
#undef ROUND
#undef K1
#undef K2
#undef K3
#undef F
#undef G
#undef H
/* The old legacy hash */
static __u32 dx_hack_hash_unsigned(const char *name, int len)
{
__u32 hash, hash0 = 0x12a3fe2d, hash1 = 0x37abe8f9;
const unsigned char *ucp = (const unsigned char *) name;
while (len--) {
hash = hash1 + (hash0 ^ (((int) *ucp++) * 7152373));
if (hash & 0x80000000)
hash -= 0x7fffffff;
hash1 = hash0;
hash0 = hash;
}
return hash0 << 1;
}
static __u32 dx_hack_hash_signed(const char *name, int len)
{
__u32 hash, hash0 = 0x12a3fe2d, hash1 = 0x37abe8f9;
const signed char *scp = (const signed char *) name;
while (len--) {
hash = hash1 + (hash0 ^ (((int) *scp++) * 7152373));
if (hash & 0x80000000)
hash -= 0x7fffffff;
hash1 = hash0;
hash0 = hash;
}
return hash0 << 1;
}
static void str2hashbuf_signed(const char *msg, int len, __u32 *buf, int num)
{
__u32 pad, val;
int i;
const signed char *scp = (const signed char *) msg;
pad = (__u32)len | ((__u32)len << 8);
pad |= pad << 16;
val = pad;
if (len > num*4)
len = num * 4;
for (i = 0; i < len; i++) {
val = ((int) scp[i]) + (val << 8);
if ((i % 4) == 3) {
*buf++ = val;
val = pad;
num--;
}
}
if (--num >= 0)
*buf++ = val;
while (--num >= 0)
*buf++ = pad;
}
static void str2hashbuf_unsigned(const char *msg, int len, __u32 *buf, int num)
{
__u32 pad, val;
int i;
const unsigned char *ucp = (const unsigned char *) msg;
pad = (__u32)len | ((__u32)len << 8);
pad |= pad << 16;
val = pad;
if (len > num*4)
len = num * 4;
for (i = 0; i < len; i++) {
val = ((int) ucp[i]) + (val << 8);
if ((i % 4) == 3) {
*buf++ = val;
val = pad;
num--;
}
}
if (--num >= 0)
*buf++ = val;
while (--num >= 0)
*buf++ = pad;
}
/*
* Returns the hash of a filename. If len is 0 and name is NULL, then
* this function can be used to test whether or not a hash version is
* supported.
*
* The seed is an 4 longword (32 bits) "secret" which can be used to
* uniquify a hash. If the seed is all zero's, then some default seed
* may be used.
*
* A particular hash version specifies whether or not the seed is
* represented, and whether or not the returned hash is 32 bits or 64
* bits. 32 bit hashes will return 0 for the minor hash.
*/
static int __ext4fs_dirhash(const struct inode *dir, const char *name, int len,
struct dx_hash_info *hinfo)
{
__u32 hash;
__u32 minor_hash = 0;
const char *p;
int i;
__u32 in[8], buf[4];
void (*str2hashbuf)(const char *, int, __u32 *, int) =
str2hashbuf_signed;
/* Initialize the default seed for the hash checksum functions */
buf[0] = 0x67452301;
buf[1] = 0xefcdab89;
buf[2] = 0x98badcfe;
buf[3] = 0x10325476;
/* Check to see if the seed is all zero's */
if (hinfo->seed) {
for (i = 0; i < 4; i++) {
if (hinfo->seed[i]) {
memcpy(buf, hinfo->seed, sizeof(buf));
break;
}
}
}
switch (hinfo->hash_version) {
case DX_HASH_LEGACY_UNSIGNED:
hash = dx_hack_hash_unsigned(name, len);
break;
case DX_HASH_LEGACY:
hash = dx_hack_hash_signed(name, len);
break;
case DX_HASH_HALF_MD4_UNSIGNED:
str2hashbuf = str2hashbuf_unsigned;
fallthrough;
case DX_HASH_HALF_MD4:
p = name;
while (len > 0) {
(*str2hashbuf)(p, len, in, 8);
half_md4_transform(buf, in);
len -= 32;
p += 32;
}
minor_hash = buf[2];
hash = buf[1];
break;
case DX_HASH_TEA_UNSIGNED:
str2hashbuf = str2hashbuf_unsigned;
fallthrough;
case DX_HASH_TEA:
p = name;
while (len > 0) {
(*str2hashbuf)(p, len, in, 4);
TEA_transform(buf, in);
len -= 16;
p += 16;
}
hash = buf[0];
minor_hash = buf[1];
break;
case DX_HASH_SIPHASH:
{
struct qstr qname = QSTR_INIT(name, len);
__u64 combined_hash;
if (fscrypt_has_encryption_key(dir)) {
combined_hash = fscrypt_fname_siphash(dir, &qname);
} else {
ext4_warning_inode(dir, "Siphash requires key");
return -1;
}
hash = (__u32)(combined_hash >> 32);
minor_hash = (__u32)combined_hash;
break;
}
default:
hinfo->hash = 0;
hinfo->minor_hash = 0;
ext4_warning(dir->i_sb,
"invalid/unsupported hash tree version %u",
hinfo->hash_version);
return -EINVAL;
}
hash = hash & ~1;
if (hash == (EXT4_HTREE_EOF_32BIT << 1))
hash = (EXT4_HTREE_EOF_32BIT - 1) << 1;
hinfo->hash = hash;
hinfo->minor_hash = minor_hash;
return 0;
}
int ext4fs_dirhash(const struct inode *dir, const char *name, int len,
struct dx_hash_info *hinfo)
{
#if IS_ENABLED(CONFIG_UNICODE)
const struct unicode_map *um = dir->i_sb->s_encoding;
int r, dlen;
unsigned char *buff;
struct qstr qstr = {.name = name, .len = len };
if (len && IS_CASEFOLDED(dir) &&
(!IS_ENCRYPTED(dir) || fscrypt_has_encryption_key(dir))) {
buff = kzalloc(sizeof(char) * PATH_MAX, GFP_KERNEL);
if (!buff)
return -ENOMEM;
dlen = utf8_casefold(um, &qstr, buff, PATH_MAX);
if (dlen < 0) {
kfree(buff);
goto opaque_seq;
}
r = __ext4fs_dirhash(dir, buff, dlen, hinfo);
kfree(buff);
return r;
}
opaque_seq:
#endif
return __ext4fs_dirhash(dir, name, len, hinfo);
}
| linux-master | fs/ext4/hash.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/dir.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/dir.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4 directory handling functions
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*
* Hash Tree Directory indexing (c) 2001 Daniel Phillips
*
*/
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/iversion.h>
#include <linux/unicode.h>
#include "ext4.h"
#include "xattr.h"
static int ext4_dx_readdir(struct file *, struct dir_context *);
/**
* is_dx_dir() - check if a directory is using htree indexing
* @inode: directory inode
*
* Check if the given dir-inode refers to an htree-indexed directory
* (or a directory which could potentially get converted to use htree
* indexing).
*
* Return 1 if it is a dx dir, 0 if not
*/
static int is_dx_dir(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
if (ext4_has_feature_dir_index(inode->i_sb) &&
((ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) ||
((inode->i_size >> sb->s_blocksize_bits) == 1) ||
ext4_has_inline_data(inode)))
return 1;
return 0;
}
static bool is_fake_dir_entry(struct ext4_dir_entry_2 *de)
{
/* Check if . or .. , or skip if namelen is 0 */
if ((de->name_len > 0) && (de->name_len <= 2) && (de->name[0] == '.') &&
(de->name[1] == '.' || de->name[1] == '\0'))
return true;
/* Check if this is a csum entry */
if (de->file_type == EXT4_FT_DIR_CSUM)
return true;
return false;
}
/*
* Return 0 if the directory entry is OK, and 1 if there is a problem
*
* Note: this is the opposite of what ext2 and ext3 historically returned...
*
* bh passed here can be an inode block or a dir data block, depending
* on the inode inline data flag.
*/
int __ext4_check_dir_entry(const char *function, unsigned int line,
struct inode *dir, struct file *filp,
struct ext4_dir_entry_2 *de,
struct buffer_head *bh, char *buf, int size,
unsigned int offset)
{
const char *error_msg = NULL;
const int rlen = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
const int next_offset = ((char *) de - buf) + rlen;
bool fake = is_fake_dir_entry(de);
bool has_csum = ext4_has_metadata_csum(dir->i_sb);
if (unlikely(rlen < ext4_dir_rec_len(1, fake ? NULL : dir)))
error_msg = "rec_len is smaller than minimal";
else if (unlikely(rlen % 4 != 0))
error_msg = "rec_len % 4 != 0";
else if (unlikely(rlen < ext4_dir_rec_len(de->name_len,
fake ? NULL : dir)))
error_msg = "rec_len is too small for name_len";
else if (unlikely(next_offset > size))
error_msg = "directory entry overrun";
else if (unlikely(next_offset > size - ext4_dir_rec_len(1,
has_csum ? NULL : dir) &&
next_offset != size))
error_msg = "directory entry too close to block end";
else if (unlikely(le32_to_cpu(de->inode) >
le32_to_cpu(EXT4_SB(dir->i_sb)->s_es->s_inodes_count)))
error_msg = "inode out of bounds";
else
return 0;
if (filp)
ext4_error_file(filp, function, line, bh->b_blocknr,
"bad entry in directory: %s - offset=%u, "
"inode=%u, rec_len=%d, size=%d fake=%d",
error_msg, offset, le32_to_cpu(de->inode),
rlen, size, fake);
else
ext4_error_inode(dir, function, line, bh->b_blocknr,
"bad entry in directory: %s - offset=%u, "
"inode=%u, rec_len=%d, size=%d fake=%d",
error_msg, offset, le32_to_cpu(de->inode),
rlen, size, fake);
return 1;
}
static int ext4_readdir(struct file *file, struct dir_context *ctx)
{
unsigned int offset;
int i;
struct ext4_dir_entry_2 *de;
int err;
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
struct buffer_head *bh = NULL;
struct fscrypt_str fstr = FSTR_INIT(NULL, 0);
err = fscrypt_prepare_readdir(inode);
if (err)
return err;
if (is_dx_dir(inode)) {
err = ext4_dx_readdir(file, ctx);
if (err != ERR_BAD_DX_DIR)
return err;
/* Can we just clear INDEX flag to ignore htree information? */
if (!ext4_has_metadata_csum(sb)) {
/*
* We don't set the inode dirty flag since it's not
* critical that it gets flushed back to the disk.
*/
ext4_clear_inode_flag(inode, EXT4_INODE_INDEX);
}
}
if (ext4_has_inline_data(inode)) {
int has_inline_data = 1;
err = ext4_read_inline_dir(file, ctx,
&has_inline_data);
if (has_inline_data)
return err;
}
if (IS_ENCRYPTED(inode)) {
err = fscrypt_fname_alloc_buffer(EXT4_NAME_LEN, &fstr);
if (err < 0)
return err;
}
while (ctx->pos < inode->i_size) {
struct ext4_map_blocks map;
if (fatal_signal_pending(current)) {
err = -ERESTARTSYS;
goto errout;
}
cond_resched();
offset = ctx->pos & (sb->s_blocksize - 1);
map.m_lblk = ctx->pos >> EXT4_BLOCK_SIZE_BITS(sb);
map.m_len = 1;
err = ext4_map_blocks(NULL, inode, &map, 0);
if (err == 0) {
/* m_len should never be zero but let's avoid
* an infinite loop if it somehow is */
if (map.m_len == 0)
map.m_len = 1;
ctx->pos += map.m_len * sb->s_blocksize;
continue;
}
if (err > 0) {
pgoff_t index = map.m_pblk >>
(PAGE_SHIFT - inode->i_blkbits);
if (!ra_has_index(&file->f_ra, index))
page_cache_sync_readahead(
sb->s_bdev->bd_inode->i_mapping,
&file->f_ra, file,
index, 1);
file->f_ra.prev_pos = (loff_t)index << PAGE_SHIFT;
bh = ext4_bread(NULL, inode, map.m_lblk, 0);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
bh = NULL;
goto errout;
}
}
if (!bh) {
/* corrupt size? Maybe no more blocks to read */
if (ctx->pos > inode->i_blocks << 9)
break;
ctx->pos += sb->s_blocksize - offset;
continue;
}
/* Check the checksum */
if (!buffer_verified(bh) &&
!ext4_dirblock_csum_verify(inode, bh)) {
EXT4_ERROR_FILE(file, 0, "directory fails checksum "
"at offset %llu",
(unsigned long long)ctx->pos);
ctx->pos += sb->s_blocksize - offset;
brelse(bh);
bh = NULL;
continue;
}
set_buffer_verified(bh);
/* If the dir block has changed since the last call to
* readdir(2), then we might be pointing to an invalid
* dirent right now. Scan from the start of the block
* to make sure. */
if (!inode_eq_iversion(inode, file->f_version)) {
for (i = 0; i < sb->s_blocksize && i < offset; ) {
de = (struct ext4_dir_entry_2 *)
(bh->b_data + i);
/* It's too expensive to do a full
* dirent test each time round this
* loop, but we do have to test at
* least that it is non-zero. A
* failure will be detected in the
* dirent test below. */
if (ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize) < ext4_dir_rec_len(1,
inode))
break;
i += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
}
offset = i;
ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1))
| offset;
file->f_version = inode_query_iversion(inode);
}
while (ctx->pos < inode->i_size
&& offset < sb->s_blocksize) {
de = (struct ext4_dir_entry_2 *) (bh->b_data + offset);
if (ext4_check_dir_entry(inode, file, de, bh,
bh->b_data, bh->b_size,
offset)) {
/*
* On error, skip to the next block
*/
ctx->pos = (ctx->pos |
(sb->s_blocksize - 1)) + 1;
break;
}
offset += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
if (le32_to_cpu(de->inode)) {
if (!IS_ENCRYPTED(inode)) {
if (!dir_emit(ctx, de->name,
de->name_len,
le32_to_cpu(de->inode),
get_dtype(sb, de->file_type)))
goto done;
} else {
int save_len = fstr.len;
struct fscrypt_str de_name =
FSTR_INIT(de->name,
de->name_len);
/* Directory is encrypted */
err = fscrypt_fname_disk_to_usr(inode,
EXT4_DIRENT_HASH(de),
EXT4_DIRENT_MINOR_HASH(de),
&de_name, &fstr);
de_name = fstr;
fstr.len = save_len;
if (err)
goto errout;
if (!dir_emit(ctx,
de_name.name, de_name.len,
le32_to_cpu(de->inode),
get_dtype(sb, de->file_type)))
goto done;
}
}
ctx->pos += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
}
if ((ctx->pos < inode->i_size) && !dir_relax_shared(inode))
goto done;
brelse(bh);
bh = NULL;
}
done:
err = 0;
errout:
fscrypt_fname_free_buffer(&fstr);
brelse(bh);
return err;
}
static inline int is_32bit_api(void)
{
#ifdef CONFIG_COMPAT
return in_compat_syscall();
#else
return (BITS_PER_LONG == 32);
#endif
}
/*
* These functions convert from the major/minor hash to an f_pos
* value for dx directories
*
* Upper layer (for example NFS) should specify FMODE_32BITHASH or
* FMODE_64BITHASH explicitly. On the other hand, we allow ext4 to be mounted
* directly on both 32-bit and 64-bit nodes, under such case, neither
* FMODE_32BITHASH nor FMODE_64BITHASH is specified.
*/
static inline loff_t hash2pos(struct file *filp, __u32 major, __u32 minor)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return major >> 1;
else
return ((__u64)(major >> 1) << 32) | (__u64)minor;
}
static inline __u32 pos2maj_hash(struct file *filp, loff_t pos)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return (pos << 1) & 0xffffffff;
else
return ((pos >> 32) << 1) & 0xffffffff;
}
static inline __u32 pos2min_hash(struct file *filp, loff_t pos)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return 0;
else
return pos & 0xffffffff;
}
/*
* Return 32- or 64-bit end-of-file for dx directories
*/
static inline loff_t ext4_get_htree_eof(struct file *filp)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return EXT4_HTREE_EOF_32BIT;
else
return EXT4_HTREE_EOF_64BIT;
}
/*
* ext4_dir_llseek() calls generic_file_llseek_size to handle htree
* directories, where the "offset" is in terms of the filename hash
* value instead of the byte offset.
*
* Because we may return a 64-bit hash that is well beyond offset limits,
* we need to pass the max hash as the maximum allowable offset in
* the htree directory case.
*
* For non-htree, ext4_llseek already chooses the proper max offset.
*/
static loff_t ext4_dir_llseek(struct file *file, loff_t offset, int whence)
{
struct inode *inode = file->f_mapping->host;
int dx_dir = is_dx_dir(inode);
loff_t ret, htree_max = ext4_get_htree_eof(file);
if (likely(dx_dir))
ret = generic_file_llseek_size(file, offset, whence,
htree_max, htree_max);
else
ret = ext4_llseek(file, offset, whence);
file->f_version = inode_peek_iversion(inode) - 1;
return ret;
}
/*
* This structure holds the nodes of the red-black tree used to store
* the directory entry in hash order.
*/
struct fname {
__u32 hash;
__u32 minor_hash;
struct rb_node rb_hash;
struct fname *next;
__u32 inode;
__u8 name_len;
__u8 file_type;
char name[];
};
/*
* This function implements a non-recursive way of freeing all of the
* nodes in the red-black tree.
*/
static void free_rb_tree_fname(struct rb_root *root)
{
struct fname *fname, *next;
rbtree_postorder_for_each_entry_safe(fname, next, root, rb_hash)
while (fname) {
struct fname *old = fname;
fname = fname->next;
kfree(old);
}
*root = RB_ROOT;
}
static struct dir_private_info *ext4_htree_create_dir_info(struct file *filp,
loff_t pos)
{
struct dir_private_info *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p)
return NULL;
p->curr_hash = pos2maj_hash(filp, pos);
p->curr_minor_hash = pos2min_hash(filp, pos);
return p;
}
void ext4_htree_free_dir_info(struct dir_private_info *p)
{
free_rb_tree_fname(&p->root);
kfree(p);
}
/*
* Given a directory entry, enter it into the fname rb tree.
*
* When filename encryption is enabled, the dirent will hold the
* encrypted filename, while the htree will hold decrypted filename.
* The decrypted filename is passed in via ent_name. parameter.
*/
int ext4_htree_store_dirent(struct file *dir_file, __u32 hash,
__u32 minor_hash,
struct ext4_dir_entry_2 *dirent,
struct fscrypt_str *ent_name)
{
struct rb_node **p, *parent = NULL;
struct fname *fname, *new_fn;
struct dir_private_info *info;
int len;
info = dir_file->private_data;
p = &info->root.rb_node;
/* Create and allocate the fname structure */
len = sizeof(struct fname) + ent_name->len + 1;
new_fn = kzalloc(len, GFP_KERNEL);
if (!new_fn)
return -ENOMEM;
new_fn->hash = hash;
new_fn->minor_hash = minor_hash;
new_fn->inode = le32_to_cpu(dirent->inode);
new_fn->name_len = ent_name->len;
new_fn->file_type = dirent->file_type;
memcpy(new_fn->name, ent_name->name, ent_name->len);
while (*p) {
parent = *p;
fname = rb_entry(parent, struct fname, rb_hash);
/*
* If the hash and minor hash match up, then we put
* them on a linked list. This rarely happens...
*/
if ((new_fn->hash == fname->hash) &&
(new_fn->minor_hash == fname->minor_hash)) {
new_fn->next = fname->next;
fname->next = new_fn;
return 0;
}
if (new_fn->hash < fname->hash)
p = &(*p)->rb_left;
else if (new_fn->hash > fname->hash)
p = &(*p)->rb_right;
else if (new_fn->minor_hash < fname->minor_hash)
p = &(*p)->rb_left;
else /* if (new_fn->minor_hash > fname->minor_hash) */
p = &(*p)->rb_right;
}
rb_link_node(&new_fn->rb_hash, parent, p);
rb_insert_color(&new_fn->rb_hash, &info->root);
return 0;
}
/*
* This is a helper function for ext4_dx_readdir. It calls filldir
* for all entries on the fname linked list. (Normally there is only
* one entry on the linked list, unless there are 62 bit hash collisions.)
*/
static int call_filldir(struct file *file, struct dir_context *ctx,
struct fname *fname)
{
struct dir_private_info *info = file->private_data;
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
if (!fname) {
ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: comm %s: "
"called with null fname?!?", __func__, __LINE__,
inode->i_ino, current->comm);
return 0;
}
ctx->pos = hash2pos(file, fname->hash, fname->minor_hash);
while (fname) {
if (!dir_emit(ctx, fname->name,
fname->name_len,
fname->inode,
get_dtype(sb, fname->file_type))) {
info->extra_fname = fname;
return 1;
}
fname = fname->next;
}
return 0;
}
static int ext4_dx_readdir(struct file *file, struct dir_context *ctx)
{
struct dir_private_info *info = file->private_data;
struct inode *inode = file_inode(file);
struct fname *fname;
int ret = 0;
if (!info) {
info = ext4_htree_create_dir_info(file, ctx->pos);
if (!info)
return -ENOMEM;
file->private_data = info;
}
if (ctx->pos == ext4_get_htree_eof(file))
return 0; /* EOF */
/* Some one has messed with f_pos; reset the world */
if (info->last_pos != ctx->pos) {
free_rb_tree_fname(&info->root);
info->curr_node = NULL;
info->extra_fname = NULL;
info->curr_hash = pos2maj_hash(file, ctx->pos);
info->curr_minor_hash = pos2min_hash(file, ctx->pos);
}
/*
* If there are any leftover names on the hash collision
* chain, return them first.
*/
if (info->extra_fname) {
if (call_filldir(file, ctx, info->extra_fname))
goto finished;
info->extra_fname = NULL;
goto next_node;
} else if (!info->curr_node)
info->curr_node = rb_first(&info->root);
while (1) {
/*
* Fill the rbtree if we have no more entries,
* or the inode has changed since we last read in the
* cached entries.
*/
if ((!info->curr_node) ||
!inode_eq_iversion(inode, file->f_version)) {
info->curr_node = NULL;
free_rb_tree_fname(&info->root);
file->f_version = inode_query_iversion(inode);
ret = ext4_htree_fill_tree(file, info->curr_hash,
info->curr_minor_hash,
&info->next_hash);
if (ret < 0)
goto finished;
if (ret == 0) {
ctx->pos = ext4_get_htree_eof(file);
break;
}
info->curr_node = rb_first(&info->root);
}
fname = rb_entry(info->curr_node, struct fname, rb_hash);
info->curr_hash = fname->hash;
info->curr_minor_hash = fname->minor_hash;
if (call_filldir(file, ctx, fname))
break;
next_node:
info->curr_node = rb_next(info->curr_node);
if (info->curr_node) {
fname = rb_entry(info->curr_node, struct fname,
rb_hash);
info->curr_hash = fname->hash;
info->curr_minor_hash = fname->minor_hash;
} else {
if (info->next_hash == ~0) {
ctx->pos = ext4_get_htree_eof(file);
break;
}
info->curr_hash = info->next_hash;
info->curr_minor_hash = 0;
}
}
finished:
info->last_pos = ctx->pos;
return ret < 0 ? ret : 0;
}
static int ext4_release_dir(struct inode *inode, struct file *filp)
{
if (filp->private_data)
ext4_htree_free_dir_info(filp->private_data);
return 0;
}
int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf,
int buf_size)
{
struct ext4_dir_entry_2 *de;
int rlen;
unsigned int offset = 0;
char *top;
de = buf;
top = buf + buf_size;
while ((char *) de < top) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
buf, buf_size, offset))
return -EFSCORRUPTED;
rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
offset += rlen;
}
if ((char *) de > top)
return -EFSCORRUPTED;
return 0;
}
const struct file_operations ext4_dir_operations = {
.llseek = ext4_dir_llseek,
.read = generic_read_dir,
.iterate_shared = ext4_readdir,
.unlocked_ioctl = ext4_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ext4_compat_ioctl,
#endif
.fsync = ext4_sync_file,
.release = ext4_release_dir,
};
| linux-master | fs/ext4/dir.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/readpage.c
*
* Copyright (C) 2002, Linus Torvalds.
* Copyright (C) 2015, Google, Inc.
*
* This was originally taken from fs/mpage.c
*
* The ext4_mpage_readpages() function here is intended to
* replace mpage_readahead() in the general case, not just for
* encrypted files. It has some limitations (see below), where it
* will fall back to read_block_full_page(), but these limitations
* should only be hit when page_size != block_size.
*
* This will allow us to attach a callback function to support ext4
* encryption.
*
* If anything unusual happens, such as:
*
* - encountering a page which has buffers
* - encountering a page which has a non-hole after a hole
* - encountering a page with non-contiguous blocks
*
* then this code just gives up and calls the buffer_head-based read function.
* It does handle a page which has holes at the end - that is a common case:
* the end-of-file on blocksize < PAGE_SIZE setups.
*
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/kdev_t.h>
#include <linux/gfp.h>
#include <linux/bio.h>
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/highmem.h>
#include <linux/prefetch.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include "ext4.h"
#define NUM_PREALLOC_POST_READ_CTXS 128
static struct kmem_cache *bio_post_read_ctx_cache;
static mempool_t *bio_post_read_ctx_pool;
/* postprocessing steps for read bios */
enum bio_post_read_step {
STEP_INITIAL = 0,
STEP_DECRYPT,
STEP_VERITY,
STEP_MAX,
};
struct bio_post_read_ctx {
struct bio *bio;
struct work_struct work;
unsigned int cur_step;
unsigned int enabled_steps;
};
static void __read_end_io(struct bio *bio)
{
struct folio_iter fi;
bio_for_each_folio_all(fi, bio) {
struct folio *folio = fi.folio;
if (bio->bi_status)
folio_clear_uptodate(folio);
else
folio_mark_uptodate(folio);
folio_unlock(folio);
}
if (bio->bi_private)
mempool_free(bio->bi_private, bio_post_read_ctx_pool);
bio_put(bio);
}
static void bio_post_read_processing(struct bio_post_read_ctx *ctx);
static void decrypt_work(struct work_struct *work)
{
struct bio_post_read_ctx *ctx =
container_of(work, struct bio_post_read_ctx, work);
struct bio *bio = ctx->bio;
if (fscrypt_decrypt_bio(bio))
bio_post_read_processing(ctx);
else
__read_end_io(bio);
}
static void verity_work(struct work_struct *work)
{
struct bio_post_read_ctx *ctx =
container_of(work, struct bio_post_read_ctx, work);
struct bio *bio = ctx->bio;
/*
* fsverity_verify_bio() may call readahead() again, and although verity
* will be disabled for that, decryption may still be needed, causing
* another bio_post_read_ctx to be allocated. So to guarantee that
* mempool_alloc() never deadlocks we must free the current ctx first.
* This is safe because verity is the last post-read step.
*/
BUILD_BUG_ON(STEP_VERITY + 1 != STEP_MAX);
mempool_free(ctx, bio_post_read_ctx_pool);
bio->bi_private = NULL;
fsverity_verify_bio(bio);
__read_end_io(bio);
}
static void bio_post_read_processing(struct bio_post_read_ctx *ctx)
{
/*
* We use different work queues for decryption and for verity because
* verity may require reading metadata pages that need decryption, and
* we shouldn't recurse to the same workqueue.
*/
switch (++ctx->cur_step) {
case STEP_DECRYPT:
if (ctx->enabled_steps & (1 << STEP_DECRYPT)) {
INIT_WORK(&ctx->work, decrypt_work);
fscrypt_enqueue_decrypt_work(&ctx->work);
return;
}
ctx->cur_step++;
fallthrough;
case STEP_VERITY:
if (ctx->enabled_steps & (1 << STEP_VERITY)) {
INIT_WORK(&ctx->work, verity_work);
fsverity_enqueue_verify_work(&ctx->work);
return;
}
ctx->cur_step++;
fallthrough;
default:
__read_end_io(ctx->bio);
}
}
static bool bio_post_read_required(struct bio *bio)
{
return bio->bi_private && !bio->bi_status;
}
/*
* I/O completion handler for multipage BIOs.
*
* The mpage code never puts partial pages into a BIO (except for end-of-file).
* If a page does not map to a contiguous run of blocks then it simply falls
* back to block_read_full_folio().
*
* Why is this? If a page's completion depends on a number of different BIOs
* which can complete in any order (or at the same time) then determining the
* status of that page is hard. See end_buffer_async_read() for the details.
* There is no point in duplicating all that complexity.
*/
static void mpage_end_io(struct bio *bio)
{
if (bio_post_read_required(bio)) {
struct bio_post_read_ctx *ctx = bio->bi_private;
ctx->cur_step = STEP_INITIAL;
bio_post_read_processing(ctx);
return;
}
__read_end_io(bio);
}
static inline bool ext4_need_verity(const struct inode *inode, pgoff_t idx)
{
return fsverity_active(inode) &&
idx < DIV_ROUND_UP(inode->i_size, PAGE_SIZE);
}
static void ext4_set_bio_post_read_ctx(struct bio *bio,
const struct inode *inode,
pgoff_t first_idx)
{
unsigned int post_read_steps = 0;
if (fscrypt_inode_uses_fs_layer_crypto(inode))
post_read_steps |= 1 << STEP_DECRYPT;
if (ext4_need_verity(inode, first_idx))
post_read_steps |= 1 << STEP_VERITY;
if (post_read_steps) {
/* Due to the mempool, this never fails. */
struct bio_post_read_ctx *ctx =
mempool_alloc(bio_post_read_ctx_pool, GFP_NOFS);
ctx->bio = bio;
ctx->enabled_steps = post_read_steps;
bio->bi_private = ctx;
}
}
static inline loff_t ext4_readpage_limit(struct inode *inode)
{
if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
return inode->i_sb->s_maxbytes;
return i_size_read(inode);
}
int ext4_mpage_readpages(struct inode *inode,
struct readahead_control *rac, struct folio *folio)
{
struct bio *bio = NULL;
sector_t last_block_in_bio = 0;
const unsigned blkbits = inode->i_blkbits;
const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
const unsigned blocksize = 1 << blkbits;
sector_t next_block;
sector_t block_in_file;
sector_t last_block;
sector_t last_block_in_file;
sector_t blocks[MAX_BUF_PER_PAGE];
unsigned page_block;
struct block_device *bdev = inode->i_sb->s_bdev;
int length;
unsigned relative_block = 0;
struct ext4_map_blocks map;
unsigned int nr_pages = rac ? readahead_count(rac) : 1;
map.m_pblk = 0;
map.m_lblk = 0;
map.m_len = 0;
map.m_flags = 0;
for (; nr_pages; nr_pages--) {
int fully_mapped = 1;
unsigned first_hole = blocks_per_page;
if (rac)
folio = readahead_folio(rac);
prefetchw(&folio->flags);
if (folio_buffers(folio))
goto confused;
block_in_file = next_block =
(sector_t)folio->index << (PAGE_SHIFT - blkbits);
last_block = block_in_file + nr_pages * blocks_per_page;
last_block_in_file = (ext4_readpage_limit(inode) +
blocksize - 1) >> blkbits;
if (last_block > last_block_in_file)
last_block = last_block_in_file;
page_block = 0;
/*
* Map blocks using the previous result first.
*/
if ((map.m_flags & EXT4_MAP_MAPPED) &&
block_in_file > map.m_lblk &&
block_in_file < (map.m_lblk + map.m_len)) {
unsigned map_offset = block_in_file - map.m_lblk;
unsigned last = map.m_len - map_offset;
for (relative_block = 0; ; relative_block++) {
if (relative_block == last) {
/* needed? */
map.m_flags &= ~EXT4_MAP_MAPPED;
break;
}
if (page_block == blocks_per_page)
break;
blocks[page_block] = map.m_pblk + map_offset +
relative_block;
page_block++;
block_in_file++;
}
}
/*
* Then do more ext4_map_blocks() calls until we are
* done with this folio.
*/
while (page_block < blocks_per_page) {
if (block_in_file < last_block) {
map.m_lblk = block_in_file;
map.m_len = last_block - block_in_file;
if (ext4_map_blocks(NULL, inode, &map, 0) < 0) {
set_error_page:
folio_set_error(folio);
folio_zero_segment(folio, 0,
folio_size(folio));
folio_unlock(folio);
goto next_page;
}
}
if ((map.m_flags & EXT4_MAP_MAPPED) == 0) {
fully_mapped = 0;
if (first_hole == blocks_per_page)
first_hole = page_block;
page_block++;
block_in_file++;
continue;
}
if (first_hole != blocks_per_page)
goto confused; /* hole -> non-hole */
/* Contiguous blocks? */
if (page_block && blocks[page_block-1] != map.m_pblk-1)
goto confused;
for (relative_block = 0; ; relative_block++) {
if (relative_block == map.m_len) {
/* needed? */
map.m_flags &= ~EXT4_MAP_MAPPED;
break;
} else if (page_block == blocks_per_page)
break;
blocks[page_block] = map.m_pblk+relative_block;
page_block++;
block_in_file++;
}
}
if (first_hole != blocks_per_page) {
folio_zero_segment(folio, first_hole << blkbits,
folio_size(folio));
if (first_hole == 0) {
if (ext4_need_verity(inode, folio->index) &&
!fsverity_verify_folio(folio))
goto set_error_page;
folio_mark_uptodate(folio);
folio_unlock(folio);
continue;
}
} else if (fully_mapped) {
folio_set_mappedtodisk(folio);
}
/*
* This folio will go to BIO. Do we need to send this
* BIO off first?
*/
if (bio && (last_block_in_bio != blocks[0] - 1 ||
!fscrypt_mergeable_bio(bio, inode, next_block))) {
submit_and_realloc:
submit_bio(bio);
bio = NULL;
}
if (bio == NULL) {
/*
* bio_alloc will _always_ be able to allocate a bio if
* __GFP_DIRECT_RECLAIM is set, see bio_alloc_bioset().
*/
bio = bio_alloc(bdev, bio_max_segs(nr_pages),
REQ_OP_READ, GFP_KERNEL);
fscrypt_set_bio_crypt_ctx(bio, inode, next_block,
GFP_KERNEL);
ext4_set_bio_post_read_ctx(bio, inode, folio->index);
bio->bi_iter.bi_sector = blocks[0] << (blkbits - 9);
bio->bi_end_io = mpage_end_io;
if (rac)
bio->bi_opf |= REQ_RAHEAD;
}
length = first_hole << blkbits;
if (!bio_add_folio(bio, folio, length, 0))
goto submit_and_realloc;
if (((map.m_flags & EXT4_MAP_BOUNDARY) &&
(relative_block == map.m_len)) ||
(first_hole != blocks_per_page)) {
submit_bio(bio);
bio = NULL;
} else
last_block_in_bio = blocks[blocks_per_page - 1];
continue;
confused:
if (bio) {
submit_bio(bio);
bio = NULL;
}
if (!folio_test_uptodate(folio))
block_read_full_folio(folio, ext4_get_block);
else
folio_unlock(folio);
next_page:
; /* A label shall be followed by a statement until C23 */
}
if (bio)
submit_bio(bio);
return 0;
}
int __init ext4_init_post_read_processing(void)
{
bio_post_read_ctx_cache = KMEM_CACHE(bio_post_read_ctx, SLAB_RECLAIM_ACCOUNT);
if (!bio_post_read_ctx_cache)
goto fail;
bio_post_read_ctx_pool =
mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,
bio_post_read_ctx_cache);
if (!bio_post_read_ctx_pool)
goto fail_free_cache;
return 0;
fail_free_cache:
kmem_cache_destroy(bio_post_read_ctx_cache);
fail:
return -ENOMEM;
}
void ext4_exit_post_read_processing(void)
{
mempool_destroy(bio_post_read_ctx_pool);
kmem_cache_destroy(bio_post_read_ctx_cache);
}
| linux-master | fs/ext4/readpage.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* ([email protected])
*
* Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
*/
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/dax.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include <linux/pagevec.h>
#include <linux/mpage.h>
#include <linux/namei.h>
#include <linux/uio.h>
#include <linux/bio.h>
#include <linux/workqueue.h>
#include <linux/kernel.h>
#include <linux/printk.h>
#include <linux/slab.h>
#include <linux/bitops.h>
#include <linux/iomap.h>
#include <linux/iversion.h>
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "truncate.h"
#include <trace/events/ext4.h>
static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
struct ext4_inode_info *ei)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__u16 dummy_csum = 0;
int offset = offsetof(struct ext4_inode, i_checksum_lo);
unsigned int csum_size = sizeof(dummy_csum);
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
offset += csum_size;
csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
EXT4_GOOD_OLD_INODE_SIZE - offset);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
offset = offsetof(struct ext4_inode, i_checksum_hi);
csum = ext4_chksum(sbi, csum, (__u8 *)raw +
EXT4_GOOD_OLD_INODE_SIZE,
offset - EXT4_GOOD_OLD_INODE_SIZE);
if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
csum_size);
offset += csum_size;
}
csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
EXT4_INODE_SIZE(inode->i_sb) - offset);
}
return csum;
}
static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
struct ext4_inode_info *ei)
{
__u32 provided, calculated;
if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
cpu_to_le32(EXT4_OS_LINUX) ||
!ext4_has_metadata_csum(inode->i_sb))
return 1;
provided = le16_to_cpu(raw->i_checksum_lo);
calculated = ext4_inode_csum(inode, raw, ei);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
else
calculated &= 0xFFFF;
return provided == calculated;
}
void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
struct ext4_inode_info *ei)
{
__u32 csum;
if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
cpu_to_le32(EXT4_OS_LINUX) ||
!ext4_has_metadata_csum(inode->i_sb))
return;
csum = ext4_inode_csum(inode, raw, ei);
raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
raw->i_checksum_hi = cpu_to_le16(csum >> 16);
}
static inline int ext4_begin_ordered_truncate(struct inode *inode,
loff_t new_size)
{
trace_ext4_begin_ordered_truncate(inode, new_size);
/*
* If jinode is zero, then we never opened the file for
* writing, so there's no need to call
* jbd2_journal_begin_ordered_truncate() since there's no
* outstanding writes we need to flush.
*/
if (!EXT4_I(inode)->jinode)
return 0;
return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode,
new_size);
}
static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
int pextents);
/*
* Test whether an inode is a fast symlink.
* A fast symlink has its symlink data stored in ext4_inode_info->i_data.
*/
int ext4_inode_is_fast_symlink(struct inode *inode)
{
if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
int ea_blocks = EXT4_I(inode)->i_file_acl ?
EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
if (ext4_has_inline_data(inode))
return 0;
return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
}
return S_ISLNK(inode->i_mode) && inode->i_size &&
(inode->i_size < EXT4_N_BLOCKS * 4);
}
/*
* Called at the last iput() if i_nlink is zero.
*/
void ext4_evict_inode(struct inode *inode)
{
handle_t *handle;
int err;
/*
* Credits for final inode cleanup and freeing:
* sb + inode (ext4_orphan_del()), block bitmap, group descriptor
* (xattr block freeing), bitmap, group descriptor (inode freeing)
*/
int extra_credits = 6;
struct ext4_xattr_inode_array *ea_inode_array = NULL;
bool freeze_protected = false;
trace_ext4_evict_inode(inode);
if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
ext4_evict_ea_inode(inode);
if (inode->i_nlink) {
truncate_inode_pages_final(&inode->i_data);
goto no_delete;
}
if (is_bad_inode(inode))
goto no_delete;
dquot_initialize(inode);
if (ext4_should_order_data(inode))
ext4_begin_ordered_truncate(inode, 0);
truncate_inode_pages_final(&inode->i_data);
/*
* For inodes with journalled data, transaction commit could have
* dirtied the inode. And for inodes with dioread_nolock, unwritten
* extents converting worker could merge extents and also have dirtied
* the inode. Flush worker is ignoring it because of I_FREEING flag but
* we still need to remove the inode from the writeback lists.
*/
if (!list_empty_careful(&inode->i_io_list))
inode_io_list_del(inode);
/*
* Protect us against freezing - iput() caller didn't have to have any
* protection against it. When we are in a running transaction though,
* we are already protected against freezing and we cannot grab further
* protection due to lock ordering constraints.
*/
if (!ext4_journal_current_handle()) {
sb_start_intwrite(inode->i_sb);
freeze_protected = true;
}
if (!IS_NOQUOTA(inode))
extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
/*
* Block bitmap, group descriptor, and inode are accounted in both
* ext4_blocks_for_truncate() and extra_credits. So subtract 3.
*/
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
ext4_blocks_for_truncate(inode) + extra_credits - 3);
if (IS_ERR(handle)) {
ext4_std_error(inode->i_sb, PTR_ERR(handle));
/*
* If we're going to skip the normal cleanup, we still need to
* make sure that the in-core orphan linked list is properly
* cleaned up.
*/
ext4_orphan_del(NULL, inode);
if (freeze_protected)
sb_end_intwrite(inode->i_sb);
goto no_delete;
}
if (IS_SYNC(inode))
ext4_handle_sync(handle);
/*
* Set inode->i_size to 0 before calling ext4_truncate(). We need
* special handling of symlinks here because i_size is used to
* determine whether ext4_inode_info->i_data contains symlink data or
* block mappings. Setting i_size to 0 will remove its fast symlink
* status. Erase i_data so that it becomes a valid empty block map.
*/
if (ext4_inode_is_fast_symlink(inode))
memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
inode->i_size = 0;
err = ext4_mark_inode_dirty(handle, inode);
if (err) {
ext4_warning(inode->i_sb,
"couldn't mark inode dirty (err %d)", err);
goto stop_handle;
}
if (inode->i_blocks) {
err = ext4_truncate(inode);
if (err) {
ext4_error_err(inode->i_sb, -err,
"couldn't truncate inode %lu (err %d)",
inode->i_ino, err);
goto stop_handle;
}
}
/* Remove xattr references. */
err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
extra_credits);
if (err) {
ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
stop_handle:
ext4_journal_stop(handle);
ext4_orphan_del(NULL, inode);
if (freeze_protected)
sb_end_intwrite(inode->i_sb);
ext4_xattr_inode_array_free(ea_inode_array);
goto no_delete;
}
/*
* Kill off the orphan record which ext4_truncate created.
* AKPM: I think this can be inside the above `if'.
* Note that ext4_orphan_del() has to be able to cope with the
* deletion of a non-existent orphan - this is because we don't
* know if ext4_truncate() actually created an orphan record.
* (Well, we could do this if we need to, but heck - it works)
*/
ext4_orphan_del(handle, inode);
EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
/*
* One subtle ordering requirement: if anything has gone wrong
* (transaction abort, IO errors, whatever), then we can still
* do these next steps (the fs will already have been marked as
* having errors), but we can't free the inode if the mark_dirty
* fails.
*/
if (ext4_mark_inode_dirty(handle, inode))
/* If that failed, just do the required in-core inode clear. */
ext4_clear_inode(inode);
else
ext4_free_inode(handle, inode);
ext4_journal_stop(handle);
if (freeze_protected)
sb_end_intwrite(inode->i_sb);
ext4_xattr_inode_array_free(ea_inode_array);
return;
no_delete:
/*
* Check out some where else accidentally dirty the evicting inode,
* which may probably cause inode use-after-free issues later.
*/
WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
if (!list_empty(&EXT4_I(inode)->i_fc_list))
ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
}
#ifdef CONFIG_QUOTA
qsize_t *ext4_get_reserved_space(struct inode *inode)
{
return &EXT4_I(inode)->i_reserved_quota;
}
#endif
/*
* Called with i_data_sem down, which is important since we can call
* ext4_discard_preallocations() from here.
*/
void ext4_da_update_reserve_space(struct inode *inode,
int used, int quota_claim)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
spin_lock(&ei->i_block_reservation_lock);
trace_ext4_da_update_reserve_space(inode, used, quota_claim);
if (unlikely(used > ei->i_reserved_data_blocks)) {
ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
"with only %d reserved data blocks",
__func__, inode->i_ino, used,
ei->i_reserved_data_blocks);
WARN_ON(1);
used = ei->i_reserved_data_blocks;
}
/* Update per-inode reservations */
ei->i_reserved_data_blocks -= used;
percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
spin_unlock(&ei->i_block_reservation_lock);
/* Update quota subsystem for data blocks */
if (quota_claim)
dquot_claim_block(inode, EXT4_C2B(sbi, used));
else {
/*
* We did fallocate with an offset that is already delayed
* allocated. So on delayed allocated writeback we should
* not re-claim the quota for fallocated blocks.
*/
dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
}
/*
* If we have done all the pending block allocations and if
* there aren't any writers on the inode, we can discard the
* inode's preallocations.
*/
if ((ei->i_reserved_data_blocks == 0) &&
!inode_is_open_for_write(inode))
ext4_discard_preallocations(inode, 0);
}
static int __check_block_validity(struct inode *inode, const char *func,
unsigned int line,
struct ext4_map_blocks *map)
{
if (ext4_has_feature_journal(inode->i_sb) &&
(inode->i_ino ==
le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
return 0;
if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
ext4_error_inode(inode, func, line, map->m_pblk,
"lblock %lu mapped to illegal pblock %llu "
"(length %d)", (unsigned long) map->m_lblk,
map->m_pblk, map->m_len);
return -EFSCORRUPTED;
}
return 0;
}
int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
ext4_lblk_t len)
{
int ret;
if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
return fscrypt_zeroout_range(inode, lblk, pblk, len);
ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
if (ret > 0)
ret = 0;
return ret;
}
#define check_block_validity(inode, map) \
__check_block_validity((inode), __func__, __LINE__, (map))
#ifdef ES_AGGRESSIVE_TEST
static void ext4_map_blocks_es_recheck(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *es_map,
struct ext4_map_blocks *map,
int flags)
{
int retval;
map->m_flags = 0;
/*
* There is a race window that the result is not the same.
* e.g. xfstests #223 when dioread_nolock enables. The reason
* is that we lookup a block mapping in extent status tree with
* out taking i_data_sem. So at the time the unwritten extent
* could be converted.
*/
down_read(&EXT4_I(inode)->i_data_sem);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
retval = ext4_ext_map_blocks(handle, inode, map, 0);
} else {
retval = ext4_ind_map_blocks(handle, inode, map, 0);
}
up_read((&EXT4_I(inode)->i_data_sem));
/*
* We don't check m_len because extent will be collpased in status
* tree. So the m_len might not equal.
*/
if (es_map->m_lblk != map->m_lblk ||
es_map->m_flags != map->m_flags ||
es_map->m_pblk != map->m_pblk) {
printk("ES cache assertion failed for inode: %lu "
"es_cached ex [%d/%d/%llu/%x] != "
"found ex [%d/%d/%llu/%x] retval %d flags %x\n",
inode->i_ino, es_map->m_lblk, es_map->m_len,
es_map->m_pblk, es_map->m_flags, map->m_lblk,
map->m_len, map->m_pblk, map->m_flags,
retval, flags);
}
}
#endif /* ES_AGGRESSIVE_TEST */
/*
* The ext4_map_blocks() function tries to look up the requested blocks,
* and returns if the blocks are already mapped.
*
* Otherwise it takes the write lock of the i_data_sem and allocate blocks
* and store the allocated blocks in the result buffer head and mark it
* mapped.
*
* If file type is extents based, it will call ext4_ext_map_blocks(),
* Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
* based files
*
* On success, it returns the number of blocks being mapped or allocated. if
* create==0 and the blocks are pre-allocated and unwritten, the resulting @map
* is marked as unwritten. If the create == 1, it will mark @map as mapped.
*
* It returns 0 if plain look up failed (blocks have not been allocated), in
* that case, @map is returned as unmapped but we still do fill map->m_len to
* indicate the length of a hole starting at map->m_lblk.
*
* It returns the error in case of allocation failure.
*/
int ext4_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags)
{
struct extent_status es;
int retval;
int ret = 0;
#ifdef ES_AGGRESSIVE_TEST
struct ext4_map_blocks orig_map;
memcpy(&orig_map, map, sizeof(*map));
#endif
map->m_flags = 0;
ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
flags, map->m_len, (unsigned long) map->m_lblk);
/*
* ext4_map_blocks returns an int, and m_len is an unsigned int
*/
if (unlikely(map->m_len > INT_MAX))
map->m_len = INT_MAX;
/* We can handle the block number less than EXT_MAX_BLOCKS */
if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
return -EFSCORRUPTED;
/* Lookup extent status tree firstly */
if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
map->m_pblk = ext4_es_pblock(&es) +
map->m_lblk - es.es_lblk;
map->m_flags |= ext4_es_is_written(&es) ?
EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
retval = es.es_len - (map->m_lblk - es.es_lblk);
if (retval > map->m_len)
retval = map->m_len;
map->m_len = retval;
} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
map->m_pblk = 0;
retval = es.es_len - (map->m_lblk - es.es_lblk);
if (retval > map->m_len)
retval = map->m_len;
map->m_len = retval;
retval = 0;
} else {
BUG();
}
if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
return retval;
#ifdef ES_AGGRESSIVE_TEST
ext4_map_blocks_es_recheck(handle, inode, map,
&orig_map, flags);
#endif
goto found;
}
/*
* In the query cache no-wait mode, nothing we can do more if we
* cannot find extent in the cache.
*/
if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
return 0;
/*
* Try to see if we can get the block without requesting a new
* file system block.
*/
down_read(&EXT4_I(inode)->i_data_sem);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
retval = ext4_ext_map_blocks(handle, inode, map, 0);
} else {
retval = ext4_ind_map_blocks(handle, inode, map, 0);
}
if (retval > 0) {
unsigned int status;
if (unlikely(retval != map->m_len)) {
ext4_warning(inode->i_sb,
"ES len assertion failed for inode "
"%lu: retval %d != map->m_len %d",
inode->i_ino, retval, map->m_len);
WARN_ON(1);
}
status = map->m_flags & EXT4_MAP_UNWRITTEN ?
EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
!(status & EXTENT_STATUS_WRITTEN) &&
ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
map->m_lblk + map->m_len - 1))
status |= EXTENT_STATUS_DELAYED;
ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
map->m_pblk, status);
}
up_read((&EXT4_I(inode)->i_data_sem));
found:
if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
ret = check_block_validity(inode, map);
if (ret != 0)
return ret;
}
/* If it is only a block(s) look up */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
return retval;
/*
* Returns if the blocks have already allocated
*
* Note that if blocks have been preallocated
* ext4_ext_get_block() returns the create = 0
* with buffer head unmapped.
*/
if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
/*
* If we need to convert extent to unwritten
* we continue and do the actual work in
* ext4_ext_map_blocks()
*/
if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
return retval;
/*
* Here we clear m_flags because after allocating an new extent,
* it will be set again.
*/
map->m_flags &= ~EXT4_MAP_FLAGS;
/*
* New blocks allocate and/or writing to unwritten extent
* will possibly result in updating i_data, so we take
* the write lock of i_data_sem, and call get_block()
* with create == 1 flag.
*/
down_write(&EXT4_I(inode)->i_data_sem);
/*
* We need to check for EXT4 here because migrate
* could have changed the inode type in between
*/
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
retval = ext4_ext_map_blocks(handle, inode, map, flags);
} else {
retval = ext4_ind_map_blocks(handle, inode, map, flags);
if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
/*
* We allocated new blocks which will result in
* i_data's format changing. Force the migrate
* to fail by clearing migrate flags
*/
ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
}
}
if (retval > 0) {
unsigned int status;
if (unlikely(retval != map->m_len)) {
ext4_warning(inode->i_sb,
"ES len assertion failed for inode "
"%lu: retval %d != map->m_len %d",
inode->i_ino, retval, map->m_len);
WARN_ON(1);
}
/*
* We have to zeroout blocks before inserting them into extent
* status tree. Otherwise someone could look them up there and
* use them before they are really zeroed. We also have to
* unmap metadata before zeroing as otherwise writeback can
* overwrite zeros with stale data from block device.
*/
if (flags & EXT4_GET_BLOCKS_ZERO &&
map->m_flags & EXT4_MAP_MAPPED &&
map->m_flags & EXT4_MAP_NEW) {
ret = ext4_issue_zeroout(inode, map->m_lblk,
map->m_pblk, map->m_len);
if (ret) {
retval = ret;
goto out_sem;
}
}
/*
* If the extent has been zeroed out, we don't need to update
* extent status tree.
*/
if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
if (ext4_es_is_written(&es))
goto out_sem;
}
status = map->m_flags & EXT4_MAP_UNWRITTEN ?
EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
!(status & EXTENT_STATUS_WRITTEN) &&
ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
map->m_lblk + map->m_len - 1))
status |= EXTENT_STATUS_DELAYED;
ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
map->m_pblk, status);
}
out_sem:
up_write((&EXT4_I(inode)->i_data_sem));
if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
ret = check_block_validity(inode, map);
if (ret != 0)
return ret;
/*
* Inodes with freshly allocated blocks where contents will be
* visible after transaction commit must be on transaction's
* ordered data list.
*/
if (map->m_flags & EXT4_MAP_NEW &&
!(map->m_flags & EXT4_MAP_UNWRITTEN) &&
!(flags & EXT4_GET_BLOCKS_ZERO) &&
!ext4_is_quota_file(inode) &&
ext4_should_order_data(inode)) {
loff_t start_byte =
(loff_t)map->m_lblk << inode->i_blkbits;
loff_t length = (loff_t)map->m_len << inode->i_blkbits;
if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
ret = ext4_jbd2_inode_add_wait(handle, inode,
start_byte, length);
else
ret = ext4_jbd2_inode_add_write(handle, inode,
start_byte, length);
if (ret)
return ret;
}
}
if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
map->m_flags & EXT4_MAP_MAPPED))
ext4_fc_track_range(handle, inode, map->m_lblk,
map->m_lblk + map->m_len - 1);
if (retval < 0)
ext_debug(inode, "failed with err %d\n", retval);
return retval;
}
/*
* Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
* we have to be careful as someone else may be manipulating b_state as well.
*/
static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
{
unsigned long old_state;
unsigned long new_state;
flags &= EXT4_MAP_FLAGS;
/* Dummy buffer_head? Set non-atomically. */
if (!bh->b_page) {
bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
return;
}
/*
* Someone else may be modifying b_state. Be careful! This is ugly but
* once we get rid of using bh as a container for mapping information
* to pass to / from get_block functions, this can go away.
*/
old_state = READ_ONCE(bh->b_state);
do {
new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
}
static int _ext4_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int flags)
{
struct ext4_map_blocks map;
int ret = 0;
if (ext4_has_inline_data(inode))
return -ERANGE;
map.m_lblk = iblock;
map.m_len = bh->b_size >> inode->i_blkbits;
ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
flags);
if (ret > 0) {
map_bh(bh, inode->i_sb, map.m_pblk);
ext4_update_bh_state(bh, map.m_flags);
bh->b_size = inode->i_sb->s_blocksize * map.m_len;
ret = 0;
} else if (ret == 0) {
/* hole case, need to fill in bh->b_size */
bh->b_size = inode->i_sb->s_blocksize * map.m_len;
}
return ret;
}
int ext4_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int create)
{
return _ext4_get_block(inode, iblock, bh,
create ? EXT4_GET_BLOCKS_CREATE : 0);
}
/*
* Get block function used when preparing for buffered write if we require
* creating an unwritten extent if blocks haven't been allocated. The extent
* will be converted to written after the IO is complete.
*/
int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
inode->i_ino, create);
return _ext4_get_block(inode, iblock, bh_result,
EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
}
/* Maximum number of blocks we map for direct IO at once. */
#define DIO_MAX_BLOCKS 4096
/*
* `handle' can be NULL if create is zero
*/
struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
ext4_lblk_t block, int map_flags)
{
struct ext4_map_blocks map;
struct buffer_head *bh;
int create = map_flags & EXT4_GET_BLOCKS_CREATE;
bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
int err;
ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
|| handle != NULL || create == 0);
ASSERT(create == 0 || !nowait);
map.m_lblk = block;
map.m_len = 1;
err = ext4_map_blocks(handle, inode, &map, map_flags);
if (err == 0)
return create ? ERR_PTR(-ENOSPC) : NULL;
if (err < 0)
return ERR_PTR(err);
if (nowait)
return sb_find_get_block(inode->i_sb, map.m_pblk);
bh = sb_getblk(inode->i_sb, map.m_pblk);
if (unlikely(!bh))
return ERR_PTR(-ENOMEM);
if (map.m_flags & EXT4_MAP_NEW) {
ASSERT(create != 0);
ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
|| (handle != NULL));
/*
* Now that we do not always journal data, we should
* keep in mind whether this should always journal the
* new buffer as metadata. For now, regular file
* writes use ext4_get_block instead, so it's not a
* problem.
*/
lock_buffer(bh);
BUFFER_TRACE(bh, "call get_create_access");
err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (unlikely(err)) {
unlock_buffer(bh);
goto errout;
}
if (!buffer_uptodate(bh)) {
memset(bh->b_data, 0, inode->i_sb->s_blocksize);
set_buffer_uptodate(bh);
}
unlock_buffer(bh);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (unlikely(err))
goto errout;
} else
BUFFER_TRACE(bh, "not a new buffer");
return bh;
errout:
brelse(bh);
return ERR_PTR(err);
}
struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
ext4_lblk_t block, int map_flags)
{
struct buffer_head *bh;
int ret;
bh = ext4_getblk(handle, inode, block, map_flags);
if (IS_ERR(bh))
return bh;
if (!bh || ext4_buffer_uptodate(bh))
return bh;
ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
if (ret) {
put_bh(bh);
return ERR_PTR(ret);
}
return bh;
}
/* Read a contiguous batch of blocks. */
int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
bool wait, struct buffer_head **bhs)
{
int i, err;
for (i = 0; i < bh_count; i++) {
bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
if (IS_ERR(bhs[i])) {
err = PTR_ERR(bhs[i]);
bh_count = i;
goto out_brelse;
}
}
for (i = 0; i < bh_count; i++)
/* Note that NULL bhs[i] is valid because of holes. */
if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
if (!wait)
return 0;
for (i = 0; i < bh_count; i++)
if (bhs[i])
wait_on_buffer(bhs[i]);
for (i = 0; i < bh_count; i++) {
if (bhs[i] && !buffer_uptodate(bhs[i])) {
err = -EIO;
goto out_brelse;
}
}
return 0;
out_brelse:
for (i = 0; i < bh_count; i++) {
brelse(bhs[i]);
bhs[i] = NULL;
}
return err;
}
int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
struct buffer_head *head,
unsigned from,
unsigned to,
int *partial,
int (*fn)(handle_t *handle, struct inode *inode,
struct buffer_head *bh))
{
struct buffer_head *bh;
unsigned block_start, block_end;
unsigned blocksize = head->b_size;
int err, ret = 0;
struct buffer_head *next;
for (bh = head, block_start = 0;
ret == 0 && (bh != head || !block_start);
block_start = block_end, bh = next) {
next = bh->b_this_page;
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (partial && !buffer_uptodate(bh))
*partial = 1;
continue;
}
err = (*fn)(handle, inode, bh);
if (!ret)
ret = err;
}
return ret;
}
/*
* Helper for handling dirtying of journalled data. We also mark the folio as
* dirty so that writeback code knows about this page (and inode) contains
* dirty data. ext4_writepages() then commits appropriate transaction to
* make data stable.
*/
static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
{
folio_mark_dirty(bh->b_folio);
return ext4_handle_dirty_metadata(handle, NULL, bh);
}
int do_journal_get_write_access(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
int dirty = buffer_dirty(bh);
int ret;
if (!buffer_mapped(bh) || buffer_freed(bh))
return 0;
/*
* __block_write_begin() could have dirtied some buffers. Clean
* the dirty bit as jbd2_journal_get_write_access() could complain
* otherwise about fs integrity issues. Setting of the dirty bit
* by __block_write_begin() isn't a real problem here as we clear
* the bit before releasing a page lock and thus writeback cannot
* ever write the buffer.
*/
if (dirty)
clear_buffer_dirty(bh);
BUFFER_TRACE(bh, "get write access");
ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (!ret && dirty)
ret = ext4_dirty_journalled_data(handle, bh);
return ret;
}
#ifdef CONFIG_FS_ENCRYPTION
static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
get_block_t *get_block)
{
unsigned from = pos & (PAGE_SIZE - 1);
unsigned to = from + len;
struct inode *inode = folio->mapping->host;
unsigned block_start, block_end;
sector_t block;
int err = 0;
unsigned blocksize = inode->i_sb->s_blocksize;
unsigned bbits;
struct buffer_head *bh, *head, *wait[2];
int nr_wait = 0;
int i;
BUG_ON(!folio_test_locked(folio));
BUG_ON(from > PAGE_SIZE);
BUG_ON(to > PAGE_SIZE);
BUG_ON(from > to);
head = folio_buffers(folio);
if (!head) {
create_empty_buffers(&folio->page, blocksize, 0);
head = folio_buffers(folio);
}
bbits = ilog2(blocksize);
block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
for (bh = head, block_start = 0; bh != head || !block_start;
block++, block_start = block_end, bh = bh->b_this_page) {
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (folio_test_uptodate(folio)) {
set_buffer_uptodate(bh);
}
continue;
}
if (buffer_new(bh))
clear_buffer_new(bh);
if (!buffer_mapped(bh)) {
WARN_ON(bh->b_size != blocksize);
err = get_block(inode, block, bh, 1);
if (err)
break;
if (buffer_new(bh)) {
if (folio_test_uptodate(folio)) {
clear_buffer_new(bh);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
continue;
}
if (block_end > to || block_start < from)
folio_zero_segments(folio, to,
block_end,
block_start, from);
continue;
}
}
if (folio_test_uptodate(folio)) {
set_buffer_uptodate(bh);
continue;
}
if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
!buffer_unwritten(bh) &&
(block_start < from || block_end > to)) {
ext4_read_bh_lock(bh, 0, false);
wait[nr_wait++] = bh;
}
}
/*
* If we issued read requests, let them complete.
*/
for (i = 0; i < nr_wait; i++) {
wait_on_buffer(wait[i]);
if (!buffer_uptodate(wait[i]))
err = -EIO;
}
if (unlikely(err)) {
folio_zero_new_buffers(folio, from, to);
} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
for (i = 0; i < nr_wait; i++) {
int err2;
err2 = fscrypt_decrypt_pagecache_blocks(folio,
blocksize, bh_offset(wait[i]));
if (err2) {
clear_buffer_uptodate(wait[i]);
err = err2;
}
}
}
return err;
}
#endif
/*
* To preserve ordering, it is essential that the hole instantiation and
* the data write be encapsulated in a single transaction. We cannot
* close off a transaction and start a new one between the ext4_get_block()
* and the ext4_write_end(). So doing the jbd2_journal_start at the start of
* ext4_write_begin() is the right place.
*/
static int ext4_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
int ret, needed_blocks;
handle_t *handle;
int retries = 0;
struct folio *folio;
pgoff_t index;
unsigned from, to;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
trace_ext4_write_begin(inode, pos, len);
/*
* Reserve one block more for addition to orphan list in case
* we allocate blocks but write fails for some reason
*/
needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
index = pos >> PAGE_SHIFT;
from = pos & (PAGE_SIZE - 1);
to = from + len;
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
pagep);
if (ret < 0)
return ret;
if (ret == 1)
return 0;
}
/*
* __filemap_get_folio() can take a long time if the
* system is thrashing due to memory pressure, or if the folio
* is being written back. So grab it first before we start
* the transaction handle. This also allows us to allocate
* the folio (if needed) without using GFP_NOFS.
*/
retry_grab:
folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping));
if (IS_ERR(folio))
return PTR_ERR(folio);
/*
* The same as page allocation, we prealloc buffer heads before
* starting the handle.
*/
if (!folio_buffers(folio))
create_empty_buffers(&folio->page, inode->i_sb->s_blocksize, 0);
folio_unlock(folio);
retry_journal:
handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
if (IS_ERR(handle)) {
folio_put(folio);
return PTR_ERR(handle);
}
folio_lock(folio);
if (folio->mapping != mapping) {
/* The folio got truncated from under us */
folio_unlock(folio);
folio_put(folio);
ext4_journal_stop(handle);
goto retry_grab;
}
/* In case writeback began while the folio was unlocked */
folio_wait_stable(folio);
#ifdef CONFIG_FS_ENCRYPTION
if (ext4_should_dioread_nolock(inode))
ret = ext4_block_write_begin(folio, pos, len,
ext4_get_block_unwritten);
else
ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
#else
if (ext4_should_dioread_nolock(inode))
ret = __block_write_begin(&folio->page, pos, len,
ext4_get_block_unwritten);
else
ret = __block_write_begin(&folio->page, pos, len, ext4_get_block);
#endif
if (!ret && ext4_should_journal_data(inode)) {
ret = ext4_walk_page_buffers(handle, inode,
folio_buffers(folio), from, to,
NULL, do_journal_get_write_access);
}
if (ret) {
bool extended = (pos + len > inode->i_size) &&
!ext4_verity_in_progress(inode);
folio_unlock(folio);
/*
* __block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_rwsem.
*
* Add inode to orphan list in case we crash before
* truncate finishes
*/
if (extended && ext4_can_truncate(inode))
ext4_orphan_add(handle, inode);
ext4_journal_stop(handle);
if (extended) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might
* still be on the orphan list; we need to
* make sure the inode is removed from the
* orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry_journal;
folio_put(folio);
return ret;
}
*pagep = &folio->page;
return ret;
}
/* For write_end() in data=journal mode */
static int write_end_fn(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
int ret;
if (!buffer_mapped(bh) || buffer_freed(bh))
return 0;
set_buffer_uptodate(bh);
ret = ext4_dirty_journalled_data(handle, bh);
clear_buffer_meta(bh);
clear_buffer_prio(bh);
return ret;
}
/*
* We need to pick up the new inode size which generic_commit_write gave us
* `file' can be NULL - eg, when called from page_symlink().
*
* ext4 never places buffers on inode->i_mapping->private_list. metadata
* buffers are managed internally.
*/
static int ext4_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct folio *folio = page_folio(page);
handle_t *handle = ext4_journal_current_handle();
struct inode *inode = mapping->host;
loff_t old_size = inode->i_size;
int ret = 0, ret2;
int i_size_changed = 0;
bool verity = ext4_verity_in_progress(inode);
trace_ext4_write_end(inode, pos, len, copied);
if (ext4_has_inline_data(inode) &&
ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
return ext4_write_inline_data_end(inode, pos, len, copied,
folio);
copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
/*
* it's important to update i_size while still holding folio lock:
* page writeout could otherwise come in and zero beyond i_size.
*
* If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
* blocks are being written past EOF, so skip the i_size update.
*/
if (!verity)
i_size_changed = ext4_update_inode_size(inode, pos + copied);
folio_unlock(folio);
folio_put(folio);
if (old_size < pos && !verity)
pagecache_isize_extended(inode, old_size, pos);
/*
* Don't mark the inode dirty under folio lock. First, it unnecessarily
* makes the holding time of folio lock longer. Second, it forces lock
* ordering of folio lock and transaction start for journaling
* filesystems.
*/
if (i_size_changed)
ret = ext4_mark_inode_dirty(handle, inode);
if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
/* if we have allocated more blocks and copied
* less. We will have blocks allocated outside
* inode->i_size. So truncate them
*/
ext4_orphan_add(handle, inode);
ret2 = ext4_journal_stop(handle);
if (!ret)
ret = ret2;
if (pos + len > inode->i_size && !verity) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might still be
* on the orphan list; we need to make sure the inode
* is removed from the orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
return ret ? ret : copied;
}
/*
* This is a private version of folio_zero_new_buffers() which doesn't
* set the buffer to be dirty, since in data=journalled mode we need
* to call ext4_dirty_journalled_data() instead.
*/
static void ext4_journalled_zero_new_buffers(handle_t *handle,
struct inode *inode,
struct folio *folio,
unsigned from, unsigned to)
{
unsigned int block_start = 0, block_end;
struct buffer_head *head, *bh;
bh = head = folio_buffers(folio);
do {
block_end = block_start + bh->b_size;
if (buffer_new(bh)) {
if (block_end > from && block_start < to) {
if (!folio_test_uptodate(folio)) {
unsigned start, size;
start = max(from, block_start);
size = min(to, block_end) - start;
folio_zero_range(folio, start, size);
write_end_fn(handle, inode, bh);
}
clear_buffer_new(bh);
}
}
block_start = block_end;
bh = bh->b_this_page;
} while (bh != head);
}
static int ext4_journalled_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct folio *folio = page_folio(page);
handle_t *handle = ext4_journal_current_handle();
struct inode *inode = mapping->host;
loff_t old_size = inode->i_size;
int ret = 0, ret2;
int partial = 0;
unsigned from, to;
int size_changed = 0;
bool verity = ext4_verity_in_progress(inode);
trace_ext4_journalled_write_end(inode, pos, len, copied);
from = pos & (PAGE_SIZE - 1);
to = from + len;
BUG_ON(!ext4_handle_valid(handle));
if (ext4_has_inline_data(inode))
return ext4_write_inline_data_end(inode, pos, len, copied,
folio);
if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
copied = 0;
ext4_journalled_zero_new_buffers(handle, inode, folio,
from, to);
} else {
if (unlikely(copied < len))
ext4_journalled_zero_new_buffers(handle, inode, folio,
from + copied, to);
ret = ext4_walk_page_buffers(handle, inode,
folio_buffers(folio),
from, from + copied, &partial,
write_end_fn);
if (!partial)
folio_mark_uptodate(folio);
}
if (!verity)
size_changed = ext4_update_inode_size(inode, pos + copied);
EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
folio_unlock(folio);
folio_put(folio);
if (old_size < pos && !verity)
pagecache_isize_extended(inode, old_size, pos);
if (size_changed) {
ret2 = ext4_mark_inode_dirty(handle, inode);
if (!ret)
ret = ret2;
}
if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
/* if we have allocated more blocks and copied
* less. We will have blocks allocated outside
* inode->i_size. So truncate them
*/
ext4_orphan_add(handle, inode);
ret2 = ext4_journal_stop(handle);
if (!ret)
ret = ret2;
if (pos + len > inode->i_size && !verity) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might still be
* on the orphan list; we need to make sure the inode
* is removed from the orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
return ret ? ret : copied;
}
/*
* Reserve space for a single cluster
*/
static int ext4_da_reserve_space(struct inode *inode)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
int ret;
/*
* We will charge metadata quota at writeout time; this saves
* us from metadata over-estimation, though we may go over by
* a small amount in the end. Here we just reserve for data.
*/
ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
if (ret)
return ret;
spin_lock(&ei->i_block_reservation_lock);
if (ext4_claim_free_clusters(sbi, 1, 0)) {
spin_unlock(&ei->i_block_reservation_lock);
dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
return -ENOSPC;
}
ei->i_reserved_data_blocks++;
trace_ext4_da_reserve_space(inode);
spin_unlock(&ei->i_block_reservation_lock);
return 0; /* success */
}
void ext4_da_release_space(struct inode *inode, int to_free)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
if (!to_free)
return; /* Nothing to release, exit */
spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
trace_ext4_da_release_space(inode, to_free);
if (unlikely(to_free > ei->i_reserved_data_blocks)) {
/*
* if there aren't enough reserved blocks, then the
* counter is messed up somewhere. Since this
* function is called from invalidate page, it's
* harmless to return without any action.
*/
ext4_warning(inode->i_sb, "ext4_da_release_space: "
"ino %lu, to_free %d with only %d reserved "
"data blocks", inode->i_ino, to_free,
ei->i_reserved_data_blocks);
WARN_ON(1);
to_free = ei->i_reserved_data_blocks;
}
ei->i_reserved_data_blocks -= to_free;
/* update fs dirty data blocks counter */
percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
}
/*
* Delayed allocation stuff
*/
struct mpage_da_data {
/* These are input fields for ext4_do_writepages() */
struct inode *inode;
struct writeback_control *wbc;
unsigned int can_map:1; /* Can writepages call map blocks? */
/* These are internal state of ext4_do_writepages() */
pgoff_t first_page; /* The first page to write */
pgoff_t next_page; /* Current page to examine */
pgoff_t last_page; /* Last page to examine */
/*
* Extent to map - this can be after first_page because that can be
* fully mapped. We somewhat abuse m_flags to store whether the extent
* is delalloc or unwritten.
*/
struct ext4_map_blocks map;
struct ext4_io_submit io_submit; /* IO submission data */
unsigned int do_map:1;
unsigned int scanned_until_end:1;
unsigned int journalled_more_data:1;
};
static void mpage_release_unused_pages(struct mpage_da_data *mpd,
bool invalidate)
{
unsigned nr, i;
pgoff_t index, end;
struct folio_batch fbatch;
struct inode *inode = mpd->inode;
struct address_space *mapping = inode->i_mapping;
/* This is necessary when next_page == 0. */
if (mpd->first_page >= mpd->next_page)
return;
mpd->scanned_until_end = 0;
index = mpd->first_page;
end = mpd->next_page - 1;
if (invalidate) {
ext4_lblk_t start, last;
start = index << (PAGE_SHIFT - inode->i_blkbits);
last = end << (PAGE_SHIFT - inode->i_blkbits);
/*
* avoid racing with extent status tree scans made by
* ext4_insert_delayed_block()
*/
down_write(&EXT4_I(inode)->i_data_sem);
ext4_es_remove_extent(inode, start, last - start + 1);
up_write(&EXT4_I(inode)->i_data_sem);
}
folio_batch_init(&fbatch);
while (index <= end) {
nr = filemap_get_folios(mapping, &index, end, &fbatch);
if (nr == 0)
break;
for (i = 0; i < nr; i++) {
struct folio *folio = fbatch.folios[i];
if (folio->index < mpd->first_page)
continue;
if (folio_next_index(folio) - 1 > end)
continue;
BUG_ON(!folio_test_locked(folio));
BUG_ON(folio_test_writeback(folio));
if (invalidate) {
if (folio_mapped(folio))
folio_clear_dirty_for_io(folio);
block_invalidate_folio(folio, 0,
folio_size(folio));
folio_clear_uptodate(folio);
}
folio_unlock(folio);
}
folio_batch_release(&fbatch);
}
}
static void ext4_print_free_blocks(struct inode *inode)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct super_block *sb = inode->i_sb;
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
EXT4_C2B(EXT4_SB(inode->i_sb),
ext4_count_free_clusters(sb)));
ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
(long long) EXT4_C2B(EXT4_SB(sb),
percpu_counter_sum(&sbi->s_freeclusters_counter)));
ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
(long long) EXT4_C2B(EXT4_SB(sb),
percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
ext4_msg(sb, KERN_CRIT, "Block reservation details");
ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
ei->i_reserved_data_blocks);
return;
}
/*
* ext4_insert_delayed_block - adds a delayed block to the extents status
* tree, incrementing the reserved cluster/block
* count or making a pending reservation
* where needed
*
* @inode - file containing the newly added block
* @lblk - logical block to be added
*
* Returns 0 on success, negative error code on failure.
*/
static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int ret;
bool allocated = false;
/*
* If the cluster containing lblk is shared with a delayed,
* written, or unwritten extent in a bigalloc file system, it's
* already been accounted for and does not need to be reserved.
* A pending reservation must be made for the cluster if it's
* shared with a written or unwritten extent and doesn't already
* have one. Written and unwritten extents can be purged from the
* extents status tree if the system is under memory pressure, so
* it's necessary to examine the extent tree if a search of the
* extents status tree doesn't get a match.
*/
if (sbi->s_cluster_ratio == 1) {
ret = ext4_da_reserve_space(inode);
if (ret != 0) /* ENOSPC */
return ret;
} else { /* bigalloc */
if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
if (!ext4_es_scan_clu(inode,
&ext4_es_is_mapped, lblk)) {
ret = ext4_clu_mapped(inode,
EXT4_B2C(sbi, lblk));
if (ret < 0)
return ret;
if (ret == 0) {
ret = ext4_da_reserve_space(inode);
if (ret != 0) /* ENOSPC */
return ret;
} else {
allocated = true;
}
} else {
allocated = true;
}
}
}
ext4_es_insert_delayed_block(inode, lblk, allocated);
return 0;
}
/*
* This function is grabs code from the very beginning of
* ext4_map_blocks, but assumes that the caller is from delayed write
* time. This function looks up the requested blocks and sets the
* buffer delay bit under the protection of i_data_sem.
*/
static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
struct ext4_map_blocks *map,
struct buffer_head *bh)
{
struct extent_status es;
int retval;
sector_t invalid_block = ~((sector_t) 0xffff);
#ifdef ES_AGGRESSIVE_TEST
struct ext4_map_blocks orig_map;
memcpy(&orig_map, map, sizeof(*map));
#endif
if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
invalid_block = ~0;
map->m_flags = 0;
ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
(unsigned long) map->m_lblk);
/* Lookup extent status tree firstly */
if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
if (ext4_es_is_hole(&es)) {
retval = 0;
down_read(&EXT4_I(inode)->i_data_sem);
goto add_delayed;
}
/*
* Delayed extent could be allocated by fallocate.
* So we need to check it.
*/
if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
map_bh(bh, inode->i_sb, invalid_block);
set_buffer_new(bh);
set_buffer_delay(bh);
return 0;
}
map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
retval = es.es_len - (iblock - es.es_lblk);
if (retval > map->m_len)
retval = map->m_len;
map->m_len = retval;
if (ext4_es_is_written(&es))
map->m_flags |= EXT4_MAP_MAPPED;
else if (ext4_es_is_unwritten(&es))
map->m_flags |= EXT4_MAP_UNWRITTEN;
else
BUG();
#ifdef ES_AGGRESSIVE_TEST
ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
#endif
return retval;
}
/*
* Try to see if we can get the block without requesting a new
* file system block.
*/
down_read(&EXT4_I(inode)->i_data_sem);
if (ext4_has_inline_data(inode))
retval = 0;
else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
retval = ext4_ext_map_blocks(NULL, inode, map, 0);
else
retval = ext4_ind_map_blocks(NULL, inode, map, 0);
add_delayed:
if (retval == 0) {
int ret;
/*
* XXX: __block_prepare_write() unmaps passed block,
* is it OK?
*/
ret = ext4_insert_delayed_block(inode, map->m_lblk);
if (ret != 0) {
retval = ret;
goto out_unlock;
}
map_bh(bh, inode->i_sb, invalid_block);
set_buffer_new(bh);
set_buffer_delay(bh);
} else if (retval > 0) {
unsigned int status;
if (unlikely(retval != map->m_len)) {
ext4_warning(inode->i_sb,
"ES len assertion failed for inode "
"%lu: retval %d != map->m_len %d",
inode->i_ino, retval, map->m_len);
WARN_ON(1);
}
status = map->m_flags & EXT4_MAP_UNWRITTEN ?
EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
map->m_pblk, status);
}
out_unlock:
up_read((&EXT4_I(inode)->i_data_sem));
return retval;
}
/*
* This is a special get_block_t callback which is used by
* ext4_da_write_begin(). It will either return mapped block or
* reserve space for a single block.
*
* For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
* We also have b_blocknr = -1 and b_bdev initialized properly
*
* For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
* We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
* initialized properly.
*/
int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int create)
{
struct ext4_map_blocks map;
int ret = 0;
BUG_ON(create == 0);
BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
map.m_lblk = iblock;
map.m_len = 1;
/*
* first, we need to know whether the block is allocated already
* preallocated blocks are unmapped but should treated
* the same as allocated blocks.
*/
ret = ext4_da_map_blocks(inode, iblock, &map, bh);
if (ret <= 0)
return ret;
map_bh(bh, inode->i_sb, map.m_pblk);
ext4_update_bh_state(bh, map.m_flags);
if (buffer_unwritten(bh)) {
/* A delayed write to unwritten bh should be marked
* new and mapped. Mapped ensures that we don't do
* get_block multiple times when we write to the same
* offset and new ensures that we do proper zero out
* for partial write.
*/
set_buffer_new(bh);
set_buffer_mapped(bh);
}
return 0;
}
static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
{
mpd->first_page += folio_nr_pages(folio);
folio_unlock(folio);
}
static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
{
size_t len;
loff_t size;
int err;
BUG_ON(folio->index != mpd->first_page);
folio_clear_dirty_for_io(folio);
/*
* We have to be very careful here! Nothing protects writeback path
* against i_size changes and the page can be writeably mapped into
* page tables. So an application can be growing i_size and writing
* data through mmap while writeback runs. folio_clear_dirty_for_io()
* write-protects our page in page tables and the page cannot get
* written to again until we release folio lock. So only after
* folio_clear_dirty_for_io() we are safe to sample i_size for
* ext4_bio_write_folio() to zero-out tail of the written page. We rely
* on the barrier provided by folio_test_clear_dirty() in
* folio_clear_dirty_for_io() to make sure i_size is really sampled only
* after page tables are updated.
*/
size = i_size_read(mpd->inode);
len = folio_size(folio);
if (folio_pos(folio) + len > size &&
!ext4_verity_in_progress(mpd->inode))
len = size & ~PAGE_MASK;
err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
if (!err)
mpd->wbc->nr_to_write--;
return err;
}
#define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
/*
* mballoc gives us at most this number of blocks...
* XXX: That seems to be only a limitation of ext4_mb_normalize_request().
* The rest of mballoc seems to handle chunks up to full group size.
*/
#define MAX_WRITEPAGES_EXTENT_LEN 2048
/*
* mpage_add_bh_to_extent - try to add bh to extent of blocks to map
*
* @mpd - extent of blocks
* @lblk - logical number of the block in the file
* @bh - buffer head we want to add to the extent
*
* The function is used to collect contig. blocks in the same state. If the
* buffer doesn't require mapping for writeback and we haven't started the
* extent of buffers to map yet, the function returns 'true' immediately - the
* caller can write the buffer right away. Otherwise the function returns true
* if the block has been added to the extent, false if the block couldn't be
* added.
*/
static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
struct buffer_head *bh)
{
struct ext4_map_blocks *map = &mpd->map;
/* Buffer that doesn't need mapping for writeback? */
if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
(!buffer_delay(bh) && !buffer_unwritten(bh))) {
/* So far no extent to map => we write the buffer right away */
if (map->m_len == 0)
return true;
return false;
}
/* First block in the extent? */
if (map->m_len == 0) {
/* We cannot map unless handle is started... */
if (!mpd->do_map)
return false;
map->m_lblk = lblk;
map->m_len = 1;
map->m_flags = bh->b_state & BH_FLAGS;
return true;
}
/* Don't go larger than mballoc is willing to allocate */
if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
return false;
/* Can we merge the block to our big extent? */
if (lblk == map->m_lblk + map->m_len &&
(bh->b_state & BH_FLAGS) == map->m_flags) {
map->m_len++;
return true;
}
return false;
}
/*
* mpage_process_page_bufs - submit page buffers for IO or add them to extent
*
* @mpd - extent of blocks for mapping
* @head - the first buffer in the page
* @bh - buffer we should start processing from
* @lblk - logical number of the block in the file corresponding to @bh
*
* Walk through page buffers from @bh upto @head (exclusive) and either submit
* the page for IO if all buffers in this page were mapped and there's no
* accumulated extent of buffers to map or add buffers in the page to the
* extent of buffers to map. The function returns 1 if the caller can continue
* by processing the next page, 0 if it should stop adding buffers to the
* extent to map because we cannot extend it anymore. It can also return value
* < 0 in case of error during IO submission.
*/
static int mpage_process_page_bufs(struct mpage_da_data *mpd,
struct buffer_head *head,
struct buffer_head *bh,
ext4_lblk_t lblk)
{
struct inode *inode = mpd->inode;
int err;
ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
>> inode->i_blkbits;
if (ext4_verity_in_progress(inode))
blocks = EXT_MAX_BLOCKS;
do {
BUG_ON(buffer_locked(bh));
if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
/* Found extent to map? */
if (mpd->map.m_len)
return 0;
/* Buffer needs mapping and handle is not started? */
if (!mpd->do_map)
return 0;
/* Everything mapped so far and we hit EOF */
break;
}
} while (lblk++, (bh = bh->b_this_page) != head);
/* So far everything mapped? Submit the page for IO. */
if (mpd->map.m_len == 0) {
err = mpage_submit_folio(mpd, head->b_folio);
if (err < 0)
return err;
mpage_folio_done(mpd, head->b_folio);
}
if (lblk >= blocks) {
mpd->scanned_until_end = 1;
return 0;
}
return 1;
}
/*
* mpage_process_folio - update folio buffers corresponding to changed extent
* and may submit fully mapped page for IO
* @mpd: description of extent to map, on return next extent to map
* @folio: Contains these buffers.
* @m_lblk: logical block mapping.
* @m_pblk: corresponding physical mapping.
* @map_bh: determines on return whether this page requires any further
* mapping or not.
*
* Scan given folio buffers corresponding to changed extent and update buffer
* state according to new extent state.
* We map delalloc buffers to their physical location, clear unwritten bits.
* If the given folio is not fully mapped, we update @mpd to the next extent in
* the given folio that needs mapping & return @map_bh as true.
*/
static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
bool *map_bh)
{
struct buffer_head *head, *bh;
ext4_io_end_t *io_end = mpd->io_submit.io_end;
ext4_lblk_t lblk = *m_lblk;
ext4_fsblk_t pblock = *m_pblk;
int err = 0;
int blkbits = mpd->inode->i_blkbits;
ssize_t io_end_size = 0;
struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
bh = head = folio_buffers(folio);
do {
if (lblk < mpd->map.m_lblk)
continue;
if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
/*
* Buffer after end of mapped extent.
* Find next buffer in the folio to map.
*/
mpd->map.m_len = 0;
mpd->map.m_flags = 0;
io_end_vec->size += io_end_size;
err = mpage_process_page_bufs(mpd, head, bh, lblk);
if (err > 0)
err = 0;
if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
io_end_vec = ext4_alloc_io_end_vec(io_end);
if (IS_ERR(io_end_vec)) {
err = PTR_ERR(io_end_vec);
goto out;
}
io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
}
*map_bh = true;
goto out;
}
if (buffer_delay(bh)) {
clear_buffer_delay(bh);
bh->b_blocknr = pblock++;
}
clear_buffer_unwritten(bh);
io_end_size += (1 << blkbits);
} while (lblk++, (bh = bh->b_this_page) != head);
io_end_vec->size += io_end_size;
*map_bh = false;
out:
*m_lblk = lblk;
*m_pblk = pblock;
return err;
}
/*
* mpage_map_buffers - update buffers corresponding to changed extent and
* submit fully mapped pages for IO
*
* @mpd - description of extent to map, on return next extent to map
*
* Scan buffers corresponding to changed extent (we expect corresponding pages
* to be already locked) and update buffer state according to new extent state.
* We map delalloc buffers to their physical location, clear unwritten bits,
* and mark buffers as uninit when we perform writes to unwritten extents
* and do extent conversion after IO is finished. If the last page is not fully
* mapped, we update @map to the next extent in the last page that needs
* mapping. Otherwise we submit the page for IO.
*/
static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
{
struct folio_batch fbatch;
unsigned nr, i;
struct inode *inode = mpd->inode;
int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
pgoff_t start, end;
ext4_lblk_t lblk;
ext4_fsblk_t pblock;
int err;
bool map_bh = false;
start = mpd->map.m_lblk >> bpp_bits;
end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
lblk = start << bpp_bits;
pblock = mpd->map.m_pblk;
folio_batch_init(&fbatch);
while (start <= end) {
nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
if (nr == 0)
break;
for (i = 0; i < nr; i++) {
struct folio *folio = fbatch.folios[i];
err = mpage_process_folio(mpd, folio, &lblk, &pblock,
&map_bh);
/*
* If map_bh is true, means page may require further bh
* mapping, or maybe the page was submitted for IO.
* So we return to call further extent mapping.
*/
if (err < 0 || map_bh)
goto out;
/* Page fully mapped - let IO run! */
err = mpage_submit_folio(mpd, folio);
if (err < 0)
goto out;
mpage_folio_done(mpd, folio);
}
folio_batch_release(&fbatch);
}
/* Extent fully mapped and matches with page boundary. We are done. */
mpd->map.m_len = 0;
mpd->map.m_flags = 0;
return 0;
out:
folio_batch_release(&fbatch);
return err;
}
static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
{
struct inode *inode = mpd->inode;
struct ext4_map_blocks *map = &mpd->map;
int get_blocks_flags;
int err, dioread_nolock;
trace_ext4_da_write_pages_extent(inode, map);
/*
* Call ext4_map_blocks() to allocate any delayed allocation blocks, or
* to convert an unwritten extent to be initialized (in the case
* where we have written into one or more preallocated blocks). It is
* possible that we're going to need more metadata blocks than
* previously reserved. However we must not fail because we're in
* writeback and there is nothing we can do about it so it might result
* in data loss. So use reserved blocks to allocate metadata if
* possible.
*
* We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
* the blocks in question are delalloc blocks. This indicates
* that the blocks and quotas has already been checked when
* the data was copied into the page cache.
*/
get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
EXT4_GET_BLOCKS_METADATA_NOFAIL |
EXT4_GET_BLOCKS_IO_SUBMIT;
dioread_nolock = ext4_should_dioread_nolock(inode);
if (dioread_nolock)
get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
if (map->m_flags & BIT(BH_Delay))
get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
if (err < 0)
return err;
if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
if (!mpd->io_submit.io_end->handle &&
ext4_handle_valid(handle)) {
mpd->io_submit.io_end->handle = handle->h_rsv_handle;
handle->h_rsv_handle = NULL;
}
ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
}
BUG_ON(map->m_len == 0);
return 0;
}
/*
* mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
* mpd->len and submit pages underlying it for IO
*
* @handle - handle for journal operations
* @mpd - extent to map
* @give_up_on_write - we set this to true iff there is a fatal error and there
* is no hope of writing the data. The caller should discard
* dirty pages to avoid infinite loops.
*
* The function maps extent starting at mpd->lblk of length mpd->len. If it is
* delayed, blocks are allocated, if it is unwritten, we may need to convert
* them to initialized or split the described range from larger unwritten
* extent. Note that we need not map all the described range since allocation
* can return less blocks or the range is covered by more unwritten extents. We
* cannot map more because we are limited by reserved transaction credits. On
* the other hand we always make sure that the last touched page is fully
* mapped so that it can be written out (and thus forward progress is
* guaranteed). After mapping we submit all mapped pages for IO.
*/
static int mpage_map_and_submit_extent(handle_t *handle,
struct mpage_da_data *mpd,
bool *give_up_on_write)
{
struct inode *inode = mpd->inode;
struct ext4_map_blocks *map = &mpd->map;
int err;
loff_t disksize;
int progress = 0;
ext4_io_end_t *io_end = mpd->io_submit.io_end;
struct ext4_io_end_vec *io_end_vec;
io_end_vec = ext4_alloc_io_end_vec(io_end);
if (IS_ERR(io_end_vec))
return PTR_ERR(io_end_vec);
io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
do {
err = mpage_map_one_extent(handle, mpd);
if (err < 0) {
struct super_block *sb = inode->i_sb;
if (ext4_forced_shutdown(sb))
goto invalidate_dirty_pages;
/*
* Let the uper layers retry transient errors.
* In the case of ENOSPC, if ext4_count_free_blocks()
* is non-zero, a commit should free up blocks.
*/
if ((err == -ENOMEM) ||
(err == -ENOSPC && ext4_count_free_clusters(sb))) {
if (progress)
goto update_disksize;
return err;
}
ext4_msg(sb, KERN_CRIT,
"Delayed block allocation failed for "
"inode %lu at logical offset %llu with"
" max blocks %u with error %d",
inode->i_ino,
(unsigned long long)map->m_lblk,
(unsigned)map->m_len, -err);
ext4_msg(sb, KERN_CRIT,
"This should not happen!! Data will "
"be lost\n");
if (err == -ENOSPC)
ext4_print_free_blocks(inode);
invalidate_dirty_pages:
*give_up_on_write = true;
return err;
}
progress = 1;
/*
* Update buffer state, submit mapped pages, and get us new
* extent to map
*/
err = mpage_map_and_submit_buffers(mpd);
if (err < 0)
goto update_disksize;
} while (map->m_len);
update_disksize:
/*
* Update on-disk size after IO is submitted. Races with
* truncate are avoided by checking i_size under i_data_sem.
*/
disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
int err2;
loff_t i_size;
down_write(&EXT4_I(inode)->i_data_sem);
i_size = i_size_read(inode);
if (disksize > i_size)
disksize = i_size;
if (disksize > EXT4_I(inode)->i_disksize)
EXT4_I(inode)->i_disksize = disksize;
up_write(&EXT4_I(inode)->i_data_sem);
err2 = ext4_mark_inode_dirty(handle, inode);
if (err2) {
ext4_error_err(inode->i_sb, -err2,
"Failed to mark inode %lu dirty",
inode->i_ino);
}
if (!err)
err = err2;
}
return err;
}
/*
* Calculate the total number of credits to reserve for one writepages
* iteration. This is called from ext4_writepages(). We map an extent of
* up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
* the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
* bpp - 1 blocks in bpp different extents.
*/
static int ext4_da_writepages_trans_blocks(struct inode *inode)
{
int bpp = ext4_journal_blocks_per_page(inode);
return ext4_meta_trans_blocks(inode,
MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
}
static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
size_t len)
{
struct buffer_head *page_bufs = folio_buffers(folio);
struct inode *inode = folio->mapping->host;
int ret, err;
ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
NULL, do_journal_get_write_access);
err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
NULL, write_end_fn);
if (ret == 0)
ret = err;
err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
if (ret == 0)
ret = err;
EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
return ret;
}
static int mpage_journal_page_buffers(handle_t *handle,
struct mpage_da_data *mpd,
struct folio *folio)
{
struct inode *inode = mpd->inode;
loff_t size = i_size_read(inode);
size_t len = folio_size(folio);
folio_clear_checked(folio);
mpd->wbc->nr_to_write--;
if (folio_pos(folio) + len > size &&
!ext4_verity_in_progress(inode))
len = size - folio_pos(folio);
return ext4_journal_folio_buffers(handle, folio, len);
}
/*
* mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
* needing mapping, submit mapped pages
*
* @mpd - where to look for pages
*
* Walk dirty pages in the mapping. If they are fully mapped, submit them for
* IO immediately. If we cannot map blocks, we submit just already mapped
* buffers in the page for IO and keep page dirty. When we can map blocks and
* we find a page which isn't mapped we start accumulating extent of buffers
* underlying these pages that needs mapping (formed by either delayed or
* unwritten buffers). We also lock the pages containing these buffers. The
* extent found is returned in @mpd structure (starting at mpd->lblk with
* length mpd->len blocks).
*
* Note that this function can attach bios to one io_end structure which are
* neither logically nor physically contiguous. Although it may seem as an
* unnecessary complication, it is actually inevitable in blocksize < pagesize
* case as we need to track IO to all buffers underlying a page in one io_end.
*/
static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
{
struct address_space *mapping = mpd->inode->i_mapping;
struct folio_batch fbatch;
unsigned int nr_folios;
pgoff_t index = mpd->first_page;
pgoff_t end = mpd->last_page;
xa_mark_t tag;
int i, err = 0;
int blkbits = mpd->inode->i_blkbits;
ext4_lblk_t lblk;
struct buffer_head *head;
handle_t *handle = NULL;
int bpp = ext4_journal_blocks_per_page(mpd->inode);
if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
tag = PAGECACHE_TAG_TOWRITE;
else
tag = PAGECACHE_TAG_DIRTY;
mpd->map.m_len = 0;
mpd->next_page = index;
if (ext4_should_journal_data(mpd->inode)) {
handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
bpp);
if (IS_ERR(handle))
return PTR_ERR(handle);
}
folio_batch_init(&fbatch);
while (index <= end) {
nr_folios = filemap_get_folios_tag(mapping, &index, end,
tag, &fbatch);
if (nr_folios == 0)
break;
for (i = 0; i < nr_folios; i++) {
struct folio *folio = fbatch.folios[i];
/*
* Accumulated enough dirty pages? This doesn't apply
* to WB_SYNC_ALL mode. For integrity sync we have to
* keep going because someone may be concurrently
* dirtying pages, and we might have synced a lot of
* newly appeared dirty pages, but have not synced all
* of the old dirty pages.
*/
if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
mpd->wbc->nr_to_write <=
mpd->map.m_len >> (PAGE_SHIFT - blkbits))
goto out;
/* If we can't merge this page, we are done. */
if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
goto out;
if (handle) {
err = ext4_journal_ensure_credits(handle, bpp,
0);
if (err < 0)
goto out;
}
folio_lock(folio);
/*
* If the page is no longer dirty, or its mapping no
* longer corresponds to inode we are writing (which
* means it has been truncated or invalidated), or the
* page is already under writeback and we are not doing
* a data integrity writeback, skip the page
*/
if (!folio_test_dirty(folio) ||
(folio_test_writeback(folio) &&
(mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
unlikely(folio->mapping != mapping)) {
folio_unlock(folio);
continue;
}
folio_wait_writeback(folio);
BUG_ON(folio_test_writeback(folio));
/*
* Should never happen but for buggy code in
* other subsystems that call
* set_page_dirty() without properly warning
* the file system first. See [1] for more
* information.
*
* [1] https://lore.kernel.org/linux-mm/[email protected]
*/
if (!folio_buffers(folio)) {
ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
folio_clear_dirty(folio);
folio_unlock(folio);
continue;
}
if (mpd->map.m_len == 0)
mpd->first_page = folio->index;
mpd->next_page = folio_next_index(folio);
/*
* Writeout when we cannot modify metadata is simple.
* Just submit the page. For data=journal mode we
* first handle writeout of the page for checkpoint and
* only after that handle delayed page dirtying. This
* makes sure current data is checkpointed to the final
* location before possibly journalling it again which
* is desirable when the page is frequently dirtied
* through a pin.
*/
if (!mpd->can_map) {
err = mpage_submit_folio(mpd, folio);
if (err < 0)
goto out;
/* Pending dirtying of journalled data? */
if (folio_test_checked(folio)) {
err = mpage_journal_page_buffers(handle,
mpd, folio);
if (err < 0)
goto out;
mpd->journalled_more_data = 1;
}
mpage_folio_done(mpd, folio);
} else {
/* Add all dirty buffers to mpd */
lblk = ((ext4_lblk_t)folio->index) <<
(PAGE_SHIFT - blkbits);
head = folio_buffers(folio);
err = mpage_process_page_bufs(mpd, head, head,
lblk);
if (err <= 0)
goto out;
err = 0;
}
}
folio_batch_release(&fbatch);
cond_resched();
}
mpd->scanned_until_end = 1;
if (handle)
ext4_journal_stop(handle);
return 0;
out:
folio_batch_release(&fbatch);
if (handle)
ext4_journal_stop(handle);
return err;
}
static int ext4_do_writepages(struct mpage_da_data *mpd)
{
struct writeback_control *wbc = mpd->wbc;
pgoff_t writeback_index = 0;
long nr_to_write = wbc->nr_to_write;
int range_whole = 0;
int cycled = 1;
handle_t *handle = NULL;
struct inode *inode = mpd->inode;
struct address_space *mapping = inode->i_mapping;
int needed_blocks, rsv_blocks = 0, ret = 0;
struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
struct blk_plug plug;
bool give_up_on_write = false;
trace_ext4_writepages(inode, wbc);
/*
* No pages to write? This is mainly a kludge to avoid starting
* a transaction for special inodes like journal inode on last iput()
* because that could violate lock ordering on umount
*/
if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
goto out_writepages;
/*
* If the filesystem has aborted, it is read-only, so return
* right away instead of dumping stack traces later on that
* will obscure the real source of the problem. We test
* fs shutdown state instead of sb->s_flag's SB_RDONLY because
* the latter could be true if the filesystem is mounted
* read-only, and in that case, ext4_writepages should
* *never* be called, so if that ever happens, we would want
* the stack trace.
*/
if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
ret = -EROFS;
goto out_writepages;
}
/*
* If we have inline data and arrive here, it means that
* we will soon create the block for the 1st page, so
* we'd better clear the inline data here.
*/
if (ext4_has_inline_data(inode)) {
/* Just inode will be modified... */
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_writepages;
}
BUG_ON(ext4_test_inode_state(inode,
EXT4_STATE_MAY_INLINE_DATA));
ext4_destroy_inline_data(handle, inode);
ext4_journal_stop(handle);
}
/*
* data=journal mode does not do delalloc so we just need to writeout /
* journal already mapped buffers. On the other hand we need to commit
* transaction to make data stable. We expect all the data to be
* already in the journal (the only exception are DMA pinned pages
* dirtied behind our back) so we commit transaction here and run the
* writeback loop to checkpoint them. The checkpointing is not actually
* necessary to make data persistent *but* quite a few places (extent
* shifting operations, fsverity, ...) depend on being able to drop
* pagecache pages after calling filemap_write_and_wait() and for that
* checkpointing needs to happen.
*/
if (ext4_should_journal_data(inode)) {
mpd->can_map = 0;
if (wbc->sync_mode == WB_SYNC_ALL)
ext4_fc_commit(sbi->s_journal,
EXT4_I(inode)->i_datasync_tid);
}
mpd->journalled_more_data = 0;
if (ext4_should_dioread_nolock(inode)) {
/*
* We may need to convert up to one extent per block in
* the page and we may dirty the inode.
*/
rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
PAGE_SIZE >> inode->i_blkbits);
}
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
if (wbc->range_cyclic) {
writeback_index = mapping->writeback_index;
if (writeback_index)
cycled = 0;
mpd->first_page = writeback_index;
mpd->last_page = -1;
} else {
mpd->first_page = wbc->range_start >> PAGE_SHIFT;
mpd->last_page = wbc->range_end >> PAGE_SHIFT;
}
ext4_io_submit_init(&mpd->io_submit, wbc);
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag_pages_for_writeback(mapping, mpd->first_page,
mpd->last_page);
blk_start_plug(&plug);
/*
* First writeback pages that don't need mapping - we can avoid
* starting a transaction unnecessarily and also avoid being blocked
* in the block layer on device congestion while having transaction
* started.
*/
mpd->do_map = 0;
mpd->scanned_until_end = 0;
mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
if (!mpd->io_submit.io_end) {
ret = -ENOMEM;
goto unplug;
}
ret = mpage_prepare_extent_to_map(mpd);
/* Unlock pages we didn't use */
mpage_release_unused_pages(mpd, false);
/* Submit prepared bio */
ext4_io_submit(&mpd->io_submit);
ext4_put_io_end_defer(mpd->io_submit.io_end);
mpd->io_submit.io_end = NULL;
if (ret < 0)
goto unplug;
while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
/* For each extent of pages we use new io_end */
mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
if (!mpd->io_submit.io_end) {
ret = -ENOMEM;
break;
}
WARN_ON_ONCE(!mpd->can_map);
/*
* We have two constraints: We find one extent to map and we
* must always write out whole page (makes a difference when
* blocksize < pagesize) so that we don't block on IO when we
* try to write out the rest of the page. Journalled mode is
* not supported by delalloc.
*/
BUG_ON(ext4_should_journal_data(inode));
needed_blocks = ext4_da_writepages_trans_blocks(inode);
/* start a new transaction */
handle = ext4_journal_start_with_reserve(inode,
EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
"%ld pages, ino %lu; err %d", __func__,
wbc->nr_to_write, inode->i_ino, ret);
/* Release allocated io_end */
ext4_put_io_end(mpd->io_submit.io_end);
mpd->io_submit.io_end = NULL;
break;
}
mpd->do_map = 1;
trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
ret = mpage_prepare_extent_to_map(mpd);
if (!ret && mpd->map.m_len)
ret = mpage_map_and_submit_extent(handle, mpd,
&give_up_on_write);
/*
* Caution: If the handle is synchronous,
* ext4_journal_stop() can wait for transaction commit
* to finish which may depend on writeback of pages to
* complete or on page lock to be released. In that
* case, we have to wait until after we have
* submitted all the IO, released page locks we hold,
* and dropped io_end reference (for extent conversion
* to be able to complete) before stopping the handle.
*/
if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
ext4_journal_stop(handle);
handle = NULL;
mpd->do_map = 0;
}
/* Unlock pages we didn't use */
mpage_release_unused_pages(mpd, give_up_on_write);
/* Submit prepared bio */
ext4_io_submit(&mpd->io_submit);
/*
* Drop our io_end reference we got from init. We have
* to be careful and use deferred io_end finishing if
* we are still holding the transaction as we can
* release the last reference to io_end which may end
* up doing unwritten extent conversion.
*/
if (handle) {
ext4_put_io_end_defer(mpd->io_submit.io_end);
ext4_journal_stop(handle);
} else
ext4_put_io_end(mpd->io_submit.io_end);
mpd->io_submit.io_end = NULL;
if (ret == -ENOSPC && sbi->s_journal) {
/*
* Commit the transaction which would
* free blocks released in the transaction
* and try again
*/
jbd2_journal_force_commit_nested(sbi->s_journal);
ret = 0;
continue;
}
/* Fatal error - ENOMEM, EIO... */
if (ret)
break;
}
unplug:
blk_finish_plug(&plug);
if (!ret && !cycled && wbc->nr_to_write > 0) {
cycled = 1;
mpd->last_page = writeback_index - 1;
mpd->first_page = 0;
goto retry;
}
/* Update index */
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
/*
* Set the writeback_index so that range_cyclic
* mode will write it back later
*/
mapping->writeback_index = mpd->first_page;
out_writepages:
trace_ext4_writepages_result(inode, wbc, ret,
nr_to_write - wbc->nr_to_write);
return ret;
}
static int ext4_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct super_block *sb = mapping->host->i_sb;
struct mpage_da_data mpd = {
.inode = mapping->host,
.wbc = wbc,
.can_map = 1,
};
int ret;
int alloc_ctx;
if (unlikely(ext4_forced_shutdown(sb)))
return -EIO;
alloc_ctx = ext4_writepages_down_read(sb);
ret = ext4_do_writepages(&mpd);
/*
* For data=journal writeback we could have come across pages marked
* for delayed dirtying (PageChecked) which were just added to the
* running transaction. Try once more to get them to stable storage.
*/
if (!ret && mpd.journalled_more_data)
ret = ext4_do_writepages(&mpd);
ext4_writepages_up_read(sb, alloc_ctx);
return ret;
}
int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = LONG_MAX,
.range_start = jinode->i_dirty_start,
.range_end = jinode->i_dirty_end,
};
struct mpage_da_data mpd = {
.inode = jinode->i_vfs_inode,
.wbc = &wbc,
.can_map = 0,
};
return ext4_do_writepages(&mpd);
}
static int ext4_dax_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
int ret;
long nr_to_write = wbc->nr_to_write;
struct inode *inode = mapping->host;
int alloc_ctx;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
alloc_ctx = ext4_writepages_down_read(inode->i_sb);
trace_ext4_writepages(inode, wbc);
ret = dax_writeback_mapping_range(mapping,
EXT4_SB(inode->i_sb)->s_daxdev, wbc);
trace_ext4_writepages_result(inode, wbc, ret,
nr_to_write - wbc->nr_to_write);
ext4_writepages_up_read(inode->i_sb, alloc_ctx);
return ret;
}
static int ext4_nonda_switch(struct super_block *sb)
{
s64 free_clusters, dirty_clusters;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* switch to non delalloc mode if we are running low
* on free block. The free block accounting via percpu
* counters can get slightly wrong with percpu_counter_batch getting
* accumulated on each CPU without updating global counters
* Delalloc need an accurate free block accounting. So switch
* to non delalloc when we are near to error range.
*/
free_clusters =
percpu_counter_read_positive(&sbi->s_freeclusters_counter);
dirty_clusters =
percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
/*
* Start pushing delalloc when 1/2 of free blocks are dirty.
*/
if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
if (2 * free_clusters < 3 * dirty_clusters ||
free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
/*
* free block count is less than 150% of dirty blocks
* or free blocks is less than watermark
*/
return 1;
}
return 0;
}
static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len,
struct page **pagep, void **fsdata)
{
int ret, retries = 0;
struct folio *folio;
pgoff_t index;
struct inode *inode = mapping->host;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
index = pos >> PAGE_SHIFT;
if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
return ext4_write_begin(file, mapping, pos,
len, pagep, fsdata);
}
*fsdata = (void *)0;
trace_ext4_da_write_begin(inode, pos, len);
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
pagep, fsdata);
if (ret < 0)
return ret;
if (ret == 1)
return 0;
}
retry:
folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping));
if (IS_ERR(folio))
return PTR_ERR(folio);
/* In case writeback began while the folio was unlocked */
folio_wait_stable(folio);
#ifdef CONFIG_FS_ENCRYPTION
ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
#else
ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
#endif
if (ret < 0) {
folio_unlock(folio);
folio_put(folio);
/*
* block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold inode lock.
*/
if (pos + len > inode->i_size)
ext4_truncate_failed_write(inode);
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return ret;
}
*pagep = &folio->page;
return ret;
}
/*
* Check if we should update i_disksize
* when write to the end of file but not require block allocation
*/
static int ext4_da_should_update_i_disksize(struct folio *folio,
unsigned long offset)
{
struct buffer_head *bh;
struct inode *inode = folio->mapping->host;
unsigned int idx;
int i;
bh = folio_buffers(folio);
idx = offset >> inode->i_blkbits;
for (i = 0; i < idx; i++)
bh = bh->b_this_page;
if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
return 0;
return 1;
}
static int ext4_da_do_write_end(struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page)
{
struct inode *inode = mapping->host;
loff_t old_size = inode->i_size;
bool disksize_changed = false;
loff_t new_i_size;
/*
* block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
* flag, which all that's needed to trigger page writeback.
*/
copied = block_write_end(NULL, mapping, pos, len, copied, page, NULL);
new_i_size = pos + copied;
/*
* It's important to update i_size while still holding page lock,
* because page writeout could otherwise come in and zero beyond
* i_size.
*
* Since we are holding inode lock, we are sure i_disksize <=
* i_size. We also know that if i_disksize < i_size, there are
* delalloc writes pending in the range up to i_size. If the end of
* the current write is <= i_size, there's no need to touch
* i_disksize since writeback will push i_disksize up to i_size
* eventually. If the end of the current write is > i_size and
* inside an allocated block which ext4_da_should_update_i_disksize()
* checked, we need to update i_disksize here as certain
* ext4_writepages() paths not allocating blocks and update i_disksize.
*/
if (new_i_size > inode->i_size) {
unsigned long end;
i_size_write(inode, new_i_size);
end = (new_i_size - 1) & (PAGE_SIZE - 1);
if (copied && ext4_da_should_update_i_disksize(page_folio(page), end)) {
ext4_update_i_disksize(inode, new_i_size);
disksize_changed = true;
}
}
unlock_page(page);
put_page(page);
if (old_size < pos)
pagecache_isize_extended(inode, old_size, pos);
if (disksize_changed) {
handle_t *handle;
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
}
return copied;
}
static int ext4_da_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
int write_mode = (int)(unsigned long)fsdata;
struct folio *folio = page_folio(page);
if (write_mode == FALL_BACK_TO_NONDELALLOC)
return ext4_write_end(file, mapping, pos,
len, copied, &folio->page, fsdata);
trace_ext4_da_write_end(inode, pos, len, copied);
if (write_mode != CONVERT_INLINE_DATA &&
ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
ext4_has_inline_data(inode))
return ext4_write_inline_data_end(inode, pos, len, copied,
folio);
if (unlikely(copied < len) && !PageUptodate(page))
copied = 0;
return ext4_da_do_write_end(mapping, pos, len, copied, &folio->page);
}
/*
* Force all delayed allocation blocks to be allocated for a given inode.
*/
int ext4_alloc_da_blocks(struct inode *inode)
{
trace_ext4_alloc_da_blocks(inode);
if (!EXT4_I(inode)->i_reserved_data_blocks)
return 0;
/*
* We do something simple for now. The filemap_flush() will
* also start triggering a write of the data blocks, which is
* not strictly speaking necessary (and for users of
* laptop_mode, not even desirable). However, to do otherwise
* would require replicating code paths in:
*
* ext4_writepages() ->
* write_cache_pages() ---> (via passed in callback function)
* __mpage_da_writepage() -->
* mpage_add_bh_to_extent()
* mpage_da_map_blocks()
*
* The problem is that write_cache_pages(), located in
* mm/page-writeback.c, marks pages clean in preparation for
* doing I/O, which is not desirable if we're not planning on
* doing I/O at all.
*
* We could call write_cache_pages(), and then redirty all of
* the pages by calling redirty_page_for_writepage() but that
* would be ugly in the extreme. So instead we would need to
* replicate parts of the code in the above functions,
* simplifying them because we wouldn't actually intend to
* write out the pages, but rather only collect contiguous
* logical block extents, call the multi-block allocator, and
* then update the buffer heads with the block allocations.
*
* For now, though, we'll cheat by calling filemap_flush(),
* which will map the blocks, and start the I/O, but not
* actually wait for the I/O to complete.
*/
return filemap_flush(inode->i_mapping);
}
/*
* bmap() is special. It gets used by applications such as lilo and by
* the swapper to find the on-disk block of a specific piece of data.
*
* Naturally, this is dangerous if the block concerned is still in the
* journal. If somebody makes a swapfile on an ext4 data-journaling
* filesystem and enables swap, then they may get a nasty shock when the
* data getting swapped to that swapfile suddenly gets overwritten by
* the original zero's written out previously to the journal and
* awaiting writeback in the kernel's buffer cache.
*
* So, if we see any bmap calls here on a modified, data-journaled file,
* take extra steps to flush any blocks which might be in the cache.
*/
static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
{
struct inode *inode = mapping->host;
sector_t ret = 0;
inode_lock_shared(inode);
/*
* We can get here for an inline file via the FIBMAP ioctl
*/
if (ext4_has_inline_data(inode))
goto out;
if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
(test_opt(inode->i_sb, DELALLOC) ||
ext4_should_journal_data(inode))) {
/*
* With delalloc or journalled data we want to sync the file so
* that we can make sure we allocate blocks for file and data
* is in place for the user to see it
*/
filemap_write_and_wait(mapping);
}
ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
out:
inode_unlock_shared(inode);
return ret;
}
static int ext4_read_folio(struct file *file, struct folio *folio)
{
int ret = -EAGAIN;
struct inode *inode = folio->mapping->host;
trace_ext4_read_folio(inode, folio);
if (ext4_has_inline_data(inode))
ret = ext4_readpage_inline(inode, folio);
if (ret == -EAGAIN)
return ext4_mpage_readpages(inode, NULL, folio);
return ret;
}
static void ext4_readahead(struct readahead_control *rac)
{
struct inode *inode = rac->mapping->host;
/* If the file has inline data, no need to do readahead. */
if (ext4_has_inline_data(inode))
return;
ext4_mpage_readpages(inode, rac, NULL);
}
static void ext4_invalidate_folio(struct folio *folio, size_t offset,
size_t length)
{
trace_ext4_invalidate_folio(folio, offset, length);
/* No journalling happens on data buffers when this function is used */
WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
block_invalidate_folio(folio, offset, length);
}
static int __ext4_journalled_invalidate_folio(struct folio *folio,
size_t offset, size_t length)
{
journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
trace_ext4_journalled_invalidate_folio(folio, offset, length);
/*
* If it's a full truncate we just forget about the pending dirtying
*/
if (offset == 0 && length == folio_size(folio))
folio_clear_checked(folio);
return jbd2_journal_invalidate_folio(journal, folio, offset, length);
}
/* Wrapper for aops... */
static void ext4_journalled_invalidate_folio(struct folio *folio,
size_t offset,
size_t length)
{
WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
}
static bool ext4_release_folio(struct folio *folio, gfp_t wait)
{
struct inode *inode = folio->mapping->host;
journal_t *journal = EXT4_JOURNAL(inode);
trace_ext4_release_folio(inode, folio);
/* Page has dirty journalled data -> cannot release */
if (folio_test_checked(folio))
return false;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, folio);
else
return try_to_free_buffers(folio);
}
static bool ext4_inode_datasync_dirty(struct inode *inode)
{
journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
if (journal) {
if (jbd2_transaction_committed(journal,
EXT4_I(inode)->i_datasync_tid))
return false;
if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
return !list_empty(&EXT4_I(inode)->i_fc_list);
return true;
}
/* Any metadata buffers to write? */
if (!list_empty(&inode->i_mapping->private_list))
return true;
return inode->i_state & I_DIRTY_DATASYNC;
}
static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
struct ext4_map_blocks *map, loff_t offset,
loff_t length, unsigned int flags)
{
u8 blkbits = inode->i_blkbits;
/*
* Writes that span EOF might trigger an I/O size update on completion,
* so consider them to be dirty for the purpose of O_DSYNC, even if
* there is no other metadata changes being made or are pending.
*/
iomap->flags = 0;
if (ext4_inode_datasync_dirty(inode) ||
offset + length > i_size_read(inode))
iomap->flags |= IOMAP_F_DIRTY;
if (map->m_flags & EXT4_MAP_NEW)
iomap->flags |= IOMAP_F_NEW;
if (flags & IOMAP_DAX)
iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
else
iomap->bdev = inode->i_sb->s_bdev;
iomap->offset = (u64) map->m_lblk << blkbits;
iomap->length = (u64) map->m_len << blkbits;
if ((map->m_flags & EXT4_MAP_MAPPED) &&
!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
iomap->flags |= IOMAP_F_MERGED;
/*
* Flags passed to ext4_map_blocks() for direct I/O writes can result
* in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
* set. In order for any allocated unwritten extents to be converted
* into written extents correctly within the ->end_io() handler, we
* need to ensure that the iomap->type is set appropriately. Hence, the
* reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
* been set first.
*/
if (map->m_flags & EXT4_MAP_UNWRITTEN) {
iomap->type = IOMAP_UNWRITTEN;
iomap->addr = (u64) map->m_pblk << blkbits;
if (flags & IOMAP_DAX)
iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
} else if (map->m_flags & EXT4_MAP_MAPPED) {
iomap->type = IOMAP_MAPPED;
iomap->addr = (u64) map->m_pblk << blkbits;
if (flags & IOMAP_DAX)
iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
} else {
iomap->type = IOMAP_HOLE;
iomap->addr = IOMAP_NULL_ADDR;
}
}
static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
unsigned int flags)
{
handle_t *handle;
u8 blkbits = inode->i_blkbits;
int ret, dio_credits, m_flags = 0, retries = 0;
/*
* Trim the mapping request to the maximum value that we can map at
* once for direct I/O.
*/
if (map->m_len > DIO_MAX_BLOCKS)
map->m_len = DIO_MAX_BLOCKS;
dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
retry:
/*
* Either we allocate blocks and then don't get an unwritten extent, so
* in that case we have reserved enough credits. Or, the blocks are
* already allocated and unwritten. In that case, the extent conversion
* fits into the credits as well.
*/
handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
/*
* DAX and direct I/O are the only two operations that are currently
* supported with IOMAP_WRITE.
*/
WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
if (flags & IOMAP_DAX)
m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
/*
* We use i_size instead of i_disksize here because delalloc writeback
* can complete at any point during the I/O and subsequently push the
* i_disksize out to i_size. This could be beyond where direct I/O is
* happening and thus expose allocated blocks to direct I/O reads.
*/
else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
m_flags = EXT4_GET_BLOCKS_CREATE;
else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
ret = ext4_map_blocks(handle, inode, map, m_flags);
/*
* We cannot fill holes in indirect tree based inodes as that could
* expose stale data in the case of a crash. Use the magic error code
* to fallback to buffered I/O.
*/
if (!m_flags && !ret)
ret = -ENOTBLK;
ext4_journal_stop(handle);
if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return ret;
}
static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
unsigned flags, struct iomap *iomap, struct iomap *srcmap)
{
int ret;
struct ext4_map_blocks map;
u8 blkbits = inode->i_blkbits;
if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
return -EINVAL;
if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
return -ERANGE;
/*
* Calculate the first and last logical blocks respectively.
*/
map.m_lblk = offset >> blkbits;
map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
if (flags & IOMAP_WRITE) {
/*
* We check here if the blocks are already allocated, then we
* don't need to start a journal txn and we can directly return
* the mapping information. This could boost performance
* especially in multi-threaded overwrite requests.
*/
if (offset + length <= i_size_read(inode)) {
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
goto out;
}
ret = ext4_iomap_alloc(inode, &map, flags);
} else {
ret = ext4_map_blocks(NULL, inode, &map, 0);
}
if (ret < 0)
return ret;
out:
/*
* When inline encryption is enabled, sometimes I/O to an encrypted file
* has to be broken up to guarantee DUN contiguity. Handle this by
* limiting the length of the mapping returned.
*/
map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
ext4_set_iomap(inode, iomap, &map, offset, length, flags);
return 0;
}
static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
loff_t length, unsigned flags, struct iomap *iomap,
struct iomap *srcmap)
{
int ret;
/*
* Even for writes we don't need to allocate blocks, so just pretend
* we are reading to save overhead of starting a transaction.
*/
flags &= ~IOMAP_WRITE;
ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
return ret;
}
static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
ssize_t written, unsigned flags, struct iomap *iomap)
{
/*
* Check to see whether an error occurred while writing out the data to
* the allocated blocks. If so, return the magic error code so that we
* fallback to buffered I/O and attempt to complete the remainder of
* the I/O. Any blocks that may have been allocated in preparation for
* the direct I/O will be reused during buffered I/O.
*/
if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
return -ENOTBLK;
return 0;
}
const struct iomap_ops ext4_iomap_ops = {
.iomap_begin = ext4_iomap_begin,
.iomap_end = ext4_iomap_end,
};
const struct iomap_ops ext4_iomap_overwrite_ops = {
.iomap_begin = ext4_iomap_overwrite_begin,
.iomap_end = ext4_iomap_end,
};
static bool ext4_iomap_is_delalloc(struct inode *inode,
struct ext4_map_blocks *map)
{
struct extent_status es;
ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
map->m_lblk, end, &es);
if (!es.es_len || es.es_lblk > end)
return false;
if (es.es_lblk > map->m_lblk) {
map->m_len = es.es_lblk - map->m_lblk;
return false;
}
offset = map->m_lblk - es.es_lblk;
map->m_len = es.es_len - offset;
return true;
}
static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
loff_t length, unsigned int flags,
struct iomap *iomap, struct iomap *srcmap)
{
int ret;
bool delalloc = false;
struct ext4_map_blocks map;
u8 blkbits = inode->i_blkbits;
if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
return -EINVAL;
if (ext4_has_inline_data(inode)) {
ret = ext4_inline_data_iomap(inode, iomap);
if (ret != -EAGAIN) {
if (ret == 0 && offset >= iomap->length)
ret = -ENOENT;
return ret;
}
}
/*
* Calculate the first and last logical block respectively.
*/
map.m_lblk = offset >> blkbits;
map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
/*
* Fiemap callers may call for offset beyond s_bitmap_maxbytes.
* So handle it here itself instead of querying ext4_map_blocks().
* Since ext4_map_blocks() will warn about it and will return
* -EIO error.
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (offset >= sbi->s_bitmap_maxbytes) {
map.m_flags = 0;
goto set_iomap;
}
}
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
return ret;
if (ret == 0)
delalloc = ext4_iomap_is_delalloc(inode, &map);
set_iomap:
ext4_set_iomap(inode, iomap, &map, offset, length, flags);
if (delalloc && iomap->type == IOMAP_HOLE)
iomap->type = IOMAP_DELALLOC;
return 0;
}
const struct iomap_ops ext4_iomap_report_ops = {
.iomap_begin = ext4_iomap_begin_report,
};
/*
* For data=journal mode, folio should be marked dirty only when it was
* writeably mapped. When that happens, it was already attached to the
* transaction and marked as jbddirty (we take care of this in
* ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
* so we should have nothing to do here, except for the case when someone
* had the page pinned and dirtied the page through this pin (e.g. by doing
* direct IO to it). In that case we'd need to attach buffers here to the
* transaction but we cannot due to lock ordering. We cannot just dirty the
* folio and leave attached buffers clean, because the buffers' dirty state is
* "definitive". We cannot just set the buffers dirty or jbddirty because all
* the journalling code will explode. So what we do is to mark the folio
* "pending dirty" and next time ext4_writepages() is called, attach buffers
* to the transaction appropriately.
*/
static bool ext4_journalled_dirty_folio(struct address_space *mapping,
struct folio *folio)
{
WARN_ON_ONCE(!folio_buffers(folio));
if (folio_maybe_dma_pinned(folio))
folio_set_checked(folio);
return filemap_dirty_folio(mapping, folio);
}
static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
{
WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
WARN_ON_ONCE(!folio_buffers(folio));
return block_dirty_folio(mapping, folio);
}
static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
struct file *file, sector_t *span)
{
return iomap_swapfile_activate(sis, file, span,
&ext4_iomap_report_ops);
}
static const struct address_space_operations ext4_aops = {
.read_folio = ext4_read_folio,
.readahead = ext4_readahead,
.writepages = ext4_writepages,
.write_begin = ext4_write_begin,
.write_end = ext4_write_end,
.dirty_folio = ext4_dirty_folio,
.bmap = ext4_bmap,
.invalidate_folio = ext4_invalidate_folio,
.release_folio = ext4_release_folio,
.direct_IO = noop_direct_IO,
.migrate_folio = buffer_migrate_folio,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
.swap_activate = ext4_iomap_swap_activate,
};
static const struct address_space_operations ext4_journalled_aops = {
.read_folio = ext4_read_folio,
.readahead = ext4_readahead,
.writepages = ext4_writepages,
.write_begin = ext4_write_begin,
.write_end = ext4_journalled_write_end,
.dirty_folio = ext4_journalled_dirty_folio,
.bmap = ext4_bmap,
.invalidate_folio = ext4_journalled_invalidate_folio,
.release_folio = ext4_release_folio,
.direct_IO = noop_direct_IO,
.migrate_folio = buffer_migrate_folio_norefs,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
.swap_activate = ext4_iomap_swap_activate,
};
static const struct address_space_operations ext4_da_aops = {
.read_folio = ext4_read_folio,
.readahead = ext4_readahead,
.writepages = ext4_writepages,
.write_begin = ext4_da_write_begin,
.write_end = ext4_da_write_end,
.dirty_folio = ext4_dirty_folio,
.bmap = ext4_bmap,
.invalidate_folio = ext4_invalidate_folio,
.release_folio = ext4_release_folio,
.direct_IO = noop_direct_IO,
.migrate_folio = buffer_migrate_folio,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
.swap_activate = ext4_iomap_swap_activate,
};
static const struct address_space_operations ext4_dax_aops = {
.writepages = ext4_dax_writepages,
.direct_IO = noop_direct_IO,
.dirty_folio = noop_dirty_folio,
.bmap = ext4_bmap,
.swap_activate = ext4_iomap_swap_activate,
};
void ext4_set_aops(struct inode *inode)
{
switch (ext4_inode_journal_mode(inode)) {
case EXT4_INODE_ORDERED_DATA_MODE:
case EXT4_INODE_WRITEBACK_DATA_MODE:
break;
case EXT4_INODE_JOURNAL_DATA_MODE:
inode->i_mapping->a_ops = &ext4_journalled_aops;
return;
default:
BUG();
}
if (IS_DAX(inode))
inode->i_mapping->a_ops = &ext4_dax_aops;
else if (test_opt(inode->i_sb, DELALLOC))
inode->i_mapping->a_ops = &ext4_da_aops;
else
inode->i_mapping->a_ops = &ext4_aops;
}
static int __ext4_block_zero_page_range(handle_t *handle,
struct address_space *mapping, loff_t from, loff_t length)
{
ext4_fsblk_t index = from >> PAGE_SHIFT;
unsigned offset = from & (PAGE_SIZE-1);
unsigned blocksize, pos;
ext4_lblk_t iblock;
struct inode *inode = mapping->host;
struct buffer_head *bh;
struct folio *folio;
int err = 0;
folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
mapping_gfp_constraint(mapping, ~__GFP_FS));
if (IS_ERR(folio))
return PTR_ERR(folio);
blocksize = inode->i_sb->s_blocksize;
iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
bh = folio_buffers(folio);
if (!bh) {
create_empty_buffers(&folio->page, blocksize, 0);
bh = folio_buffers(folio);
}
/* Find the buffer that contains "offset" */
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
if (buffer_freed(bh)) {
BUFFER_TRACE(bh, "freed: skip");
goto unlock;
}
if (!buffer_mapped(bh)) {
BUFFER_TRACE(bh, "unmapped");
ext4_get_block(inode, iblock, bh, 0);
/* unmapped? It's a hole - nothing to do */
if (!buffer_mapped(bh)) {
BUFFER_TRACE(bh, "still unmapped");
goto unlock;
}
}
/* Ok, it's mapped. Make sure it's up-to-date */
if (folio_test_uptodate(folio))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
err = ext4_read_bh_lock(bh, 0, true);
if (err)
goto unlock;
if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
/* We expect the key to be set. */
BUG_ON(!fscrypt_has_encryption_key(inode));
err = fscrypt_decrypt_pagecache_blocks(folio,
blocksize,
bh_offset(bh));
if (err) {
clear_buffer_uptodate(bh);
goto unlock;
}
}
}
if (ext4_should_journal_data(inode)) {
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (err)
goto unlock;
}
folio_zero_range(folio, offset, length);
BUFFER_TRACE(bh, "zeroed end of block");
if (ext4_should_journal_data(inode)) {
err = ext4_dirty_journalled_data(handle, bh);
} else {
err = 0;
mark_buffer_dirty(bh);
if (ext4_should_order_data(inode))
err = ext4_jbd2_inode_add_write(handle, inode, from,
length);
}
unlock:
folio_unlock(folio);
folio_put(folio);
return err;
}
/*
* ext4_block_zero_page_range() zeros out a mapping of length 'length'
* starting from file offset 'from'. The range to be zero'd must
* be contained with in one block. If the specified range exceeds
* the end of the block it will be shortened to end of the block
* that corresponds to 'from'
*/
static int ext4_block_zero_page_range(handle_t *handle,
struct address_space *mapping, loff_t from, loff_t length)
{
struct inode *inode = mapping->host;
unsigned offset = from & (PAGE_SIZE-1);
unsigned blocksize = inode->i_sb->s_blocksize;
unsigned max = blocksize - (offset & (blocksize - 1));
/*
* correct length if it does not fall between
* 'from' and the end of the block
*/
if (length > max || length < 0)
length = max;
if (IS_DAX(inode)) {
return dax_zero_range(inode, from, length, NULL,
&ext4_iomap_ops);
}
return __ext4_block_zero_page_range(handle, mapping, from, length);
}
/*
* ext4_block_truncate_page() zeroes out a mapping from file offset `from'
* up to the end of the block which corresponds to `from'.
* This required during truncate. We need to physically zero the tail end
* of that block so it doesn't yield old data if the file is later grown.
*/
static int ext4_block_truncate_page(handle_t *handle,
struct address_space *mapping, loff_t from)
{
unsigned offset = from & (PAGE_SIZE-1);
unsigned length;
unsigned blocksize;
struct inode *inode = mapping->host;
/* If we are processing an encrypted inode during orphan list handling */
if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
return 0;
blocksize = inode->i_sb->s_blocksize;
length = blocksize - (offset & (blocksize - 1));
return ext4_block_zero_page_range(handle, mapping, from, length);
}
int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
loff_t lstart, loff_t length)
{
struct super_block *sb = inode->i_sb;
struct address_space *mapping = inode->i_mapping;
unsigned partial_start, partial_end;
ext4_fsblk_t start, end;
loff_t byte_end = (lstart + length - 1);
int err = 0;
partial_start = lstart & (sb->s_blocksize - 1);
partial_end = byte_end & (sb->s_blocksize - 1);
start = lstart >> sb->s_blocksize_bits;
end = byte_end >> sb->s_blocksize_bits;
/* Handle partial zero within the single block */
if (start == end &&
(partial_start || (partial_end != sb->s_blocksize - 1))) {
err = ext4_block_zero_page_range(handle, mapping,
lstart, length);
return err;
}
/* Handle partial zero out on the start of the range */
if (partial_start) {
err = ext4_block_zero_page_range(handle, mapping,
lstart, sb->s_blocksize);
if (err)
return err;
}
/* Handle partial zero out on the end of the range */
if (partial_end != sb->s_blocksize - 1)
err = ext4_block_zero_page_range(handle, mapping,
byte_end - partial_end,
partial_end + 1);
return err;
}
int ext4_can_truncate(struct inode *inode)
{
if (S_ISREG(inode->i_mode))
return 1;
if (S_ISDIR(inode->i_mode))
return 1;
if (S_ISLNK(inode->i_mode))
return !ext4_inode_is_fast_symlink(inode);
return 0;
}
/*
* We have to make sure i_disksize gets properly updated before we truncate
* page cache due to hole punching or zero range. Otherwise i_disksize update
* can get lost as it may have been postponed to submission of writeback but
* that will never happen after we truncate page cache.
*/
int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
loff_t len)
{
handle_t *handle;
int ret;
loff_t size = i_size_read(inode);
WARN_ON(!inode_is_locked(inode));
if (offset > size || offset + len < size)
return 0;
if (EXT4_I(inode)->i_disksize >= size)
return 0;
handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
ext4_update_i_disksize(inode, size);
ret = ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
return ret;
}
static void ext4_wait_dax_page(struct inode *inode)
{
filemap_invalidate_unlock(inode->i_mapping);
schedule();
filemap_invalidate_lock(inode->i_mapping);
}
int ext4_break_layouts(struct inode *inode)
{
struct page *page;
int error;
if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
return -EINVAL;
do {
page = dax_layout_busy_page(inode->i_mapping);
if (!page)
return 0;
error = ___wait_var_event(&page->_refcount,
atomic_read(&page->_refcount) == 1,
TASK_INTERRUPTIBLE, 0, 0,
ext4_wait_dax_page(inode));
} while (error == 0);
return error;
}
/*
* ext4_punch_hole: punches a hole in a file by releasing the blocks
* associated with the given offset and length
*
* @inode: File inode
* @offset: The offset where the hole will begin
* @len: The length of the hole
*
* Returns: 0 on success or negative on failure
*/
int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
{
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
ext4_lblk_t first_block, stop_block;
struct address_space *mapping = inode->i_mapping;
loff_t first_block_offset, last_block_offset, max_length;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
handle_t *handle;
unsigned int credits;
int ret = 0, ret2 = 0;
trace_ext4_punch_hole(inode, offset, length, 0);
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + length - 1);
if (ret)
return ret;
}
inode_lock(inode);
/* No need to punch hole beyond i_size */
if (offset >= inode->i_size)
goto out_mutex;
/*
* If the hole extends beyond i_size, set the hole
* to end after the page that contains i_size
*/
if (offset + length > inode->i_size) {
length = inode->i_size +
PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
offset;
}
/*
* For punch hole the length + offset needs to be within one block
* before last range. Adjust the length if it goes beyond that limit.
*/
max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
if (offset + length > max_length)
length = max_length - offset;
if (offset & (sb->s_blocksize - 1) ||
(offset + length) & (sb->s_blocksize - 1)) {
/*
* Attach jinode to inode for jbd2 if we do any zeroing of
* partial block
*/
ret = ext4_inode_attach_jinode(inode);
if (ret < 0)
goto out_mutex;
}
/* Wait all existing dio workers, newcomers will block on i_rwsem */
inode_dio_wait(inode);
ret = file_modified(file);
if (ret)
goto out_mutex;
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
filemap_invalidate_lock(mapping);
ret = ext4_break_layouts(inode);
if (ret)
goto out_dio;
first_block_offset = round_up(offset, sb->s_blocksize);
last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
/* Now release the pages and zero block aligned part of pages*/
if (last_block_offset > first_block_offset) {
ret = ext4_update_disksize_before_punch(inode, offset, length);
if (ret)
goto out_dio;
truncate_pagecache_range(inode, first_block_offset,
last_block_offset);
}
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
credits = ext4_writepage_trans_blocks(inode);
else
credits = ext4_blocks_for_truncate(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(sb, ret);
goto out_dio;
}
ret = ext4_zero_partial_blocks(handle, inode, offset,
length);
if (ret)
goto out_stop;
first_block = (offset + sb->s_blocksize - 1) >>
EXT4_BLOCK_SIZE_BITS(sb);
stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
/* If there are blocks to remove, do it */
if (stop_block > first_block) {
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode, 0);
ext4_es_remove_extent(inode, first_block,
stop_block - first_block);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
ret = ext4_ext_remove_space(inode, first_block,
stop_block - 1);
else
ret = ext4_ind_remove_space(handle, inode, first_block,
stop_block);
up_write(&EXT4_I(inode)->i_data_sem);
}
ext4_fc_track_range(handle, inode, first_block, stop_block);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode_set_ctime_current(inode);
ret2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(ret2))
ret = ret2;
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out_stop:
ext4_journal_stop(handle);
out_dio:
filemap_invalidate_unlock(mapping);
out_mutex:
inode_unlock(inode);
return ret;
}
int ext4_inode_attach_jinode(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct jbd2_inode *jinode;
if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
return 0;
jinode = jbd2_alloc_inode(GFP_KERNEL);
spin_lock(&inode->i_lock);
if (!ei->jinode) {
if (!jinode) {
spin_unlock(&inode->i_lock);
return -ENOMEM;
}
ei->jinode = jinode;
jbd2_journal_init_jbd_inode(ei->jinode, inode);
jinode = NULL;
}
spin_unlock(&inode->i_lock);
if (unlikely(jinode != NULL))
jbd2_free_inode(jinode);
return 0;
}
/*
* ext4_truncate()
*
* We block out ext4_get_block() block instantiations across the entire
* transaction, and VFS/VM ensures that ext4_truncate() cannot run
* simultaneously on behalf of the same inode.
*
* As we work through the truncate and commit bits of it to the journal there
* is one core, guiding principle: the file's tree must always be consistent on
* disk. We must be able to restart the truncate after a crash.
*
* The file's tree may be transiently inconsistent in memory (although it
* probably isn't), but whenever we close off and commit a journal transaction,
* the contents of (the filesystem + the journal) must be consistent and
* restartable. It's pretty simple, really: bottom up, right to left (although
* left-to-right works OK too).
*
* Note that at recovery time, journal replay occurs *before* the restart of
* truncate against the orphan inode list.
*
* The committed inode has the new, desired i_size (which is the same as
* i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
* that this inode's truncate did not complete and it will again call
* ext4_truncate() to have another go. So there will be instantiated blocks
* to the right of the truncation point in a crashed ext4 filesystem. But
* that's fine - as long as they are linked from the inode, the post-crash
* ext4_truncate() run will find them and release them.
*/
int ext4_truncate(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned int credits;
int err = 0, err2;
handle_t *handle;
struct address_space *mapping = inode->i_mapping;
/*
* There is a possibility that we're either freeing the inode
* or it's a completely new inode. In those cases we might not
* have i_rwsem locked because it's not necessary.
*/
if (!(inode->i_state & (I_NEW|I_FREEING)))
WARN_ON(!inode_is_locked(inode));
trace_ext4_truncate_enter(inode);
if (!ext4_can_truncate(inode))
goto out_trace;
if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
if (ext4_has_inline_data(inode)) {
int has_inline = 1;
err = ext4_inline_data_truncate(inode, &has_inline);
if (err || has_inline)
goto out_trace;
}
/* If we zero-out tail of the page, we have to create jinode for jbd2 */
if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
err = ext4_inode_attach_jinode(inode);
if (err)
goto out_trace;
}
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
credits = ext4_writepage_trans_blocks(inode);
else
credits = ext4_blocks_for_truncate(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto out_trace;
}
if (inode->i_size & (inode->i_sb->s_blocksize - 1))
ext4_block_truncate_page(handle, mapping, inode->i_size);
/*
* We add the inode to the orphan list, so that if this
* truncate spans multiple transactions, and we crash, we will
* resume the truncate when the filesystem recovers. It also
* marks the inode dirty, to catch the new size.
*
* Implication: the file must always be in a sane, consistent
* truncatable state while each transaction commits.
*/
err = ext4_orphan_add(handle, inode);
if (err)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode, 0);
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
err = ext4_ext_truncate(handle, inode);
else
ext4_ind_truncate(handle, inode);
up_write(&ei->i_data_sem);
if (err)
goto out_stop;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
out_stop:
/*
* If this was a simple ftruncate() and the file will remain alive,
* then we need to clear up the orphan record which we created above.
* However, if this was a real unlink then we were called by
* ext4_evict_inode(), and we allow that function to clean up the
* orphan info for us.
*/
if (inode->i_nlink)
ext4_orphan_del(handle, inode);
inode->i_mtime = inode_set_ctime_current(inode);
err2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(err2 && !err))
err = err2;
ext4_journal_stop(handle);
out_trace:
trace_ext4_truncate_exit(inode);
return err;
}
static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
{
if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
return inode_peek_iversion_raw(inode);
else
return inode_peek_iversion(inode);
}
static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
struct ext4_inode_info *ei)
{
struct inode *inode = &(ei->vfs_inode);
u64 i_blocks = READ_ONCE(inode->i_blocks);
struct super_block *sb = inode->i_sb;
if (i_blocks <= ~0U) {
/*
* i_blocks can be represented in a 32 bit variable
* as multiple of 512 bytes
*/
raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
raw_inode->i_blocks_high = 0;
ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
return 0;
}
/*
* This should never happen since sb->s_maxbytes should not have
* allowed this, sb->s_maxbytes was set according to the huge_file
* feature in ext4_fill_super().
*/
if (!ext4_has_feature_huge_file(sb))
return -EFSCORRUPTED;
if (i_blocks <= 0xffffffffffffULL) {
/*
* i_blocks can be represented in a 48 bit variable
* as multiple of 512 bytes
*/
raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
} else {
ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
/* i_block is stored in file system block size */
i_blocks = i_blocks >> (inode->i_blkbits - 9);
raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
}
return 0;
}
static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
uid_t i_uid;
gid_t i_gid;
projid_t i_projid;
int block;
int err;
err = ext4_inode_blocks_set(raw_inode, ei);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
i_uid = i_uid_read(inode);
i_gid = i_gid_read(inode);
i_projid = from_kprojid(&init_user_ns, ei->i_projid);
if (!(test_opt(inode->i_sb, NO_UID32))) {
raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
/*
* Fix up interoperability with old kernels. Otherwise,
* old inodes get re-used with the upper 16 bits of the
* uid/gid intact.
*/
if (ei->i_dtime && list_empty(&ei->i_orphan)) {
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
} else {
raw_inode->i_uid_high =
cpu_to_le16(high_16_bits(i_uid));
raw_inode->i_gid_high =
cpu_to_le16(high_16_bits(i_gid));
}
} else {
raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
EXT4_INODE_SET_CTIME(inode, raw_inode);
EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
raw_inode->i_file_acl_high =
cpu_to_le16(ei->i_file_acl >> 32);
raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
ext4_isize_set(raw_inode, ei->i_disksize);
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
raw_inode->i_block[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
raw_inode->i_block[1] = 0;
} else {
raw_inode->i_block[0] = 0;
raw_inode->i_block[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
raw_inode->i_block[2] = 0;
}
} else if (!ext4_has_inline_data(inode)) {
for (block = 0; block < EXT4_N_BLOCKS; block++)
raw_inode->i_block[block] = ei->i_data[block];
}
if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
u64 ivers = ext4_inode_peek_iversion(inode);
raw_inode->i_disk_version = cpu_to_le32(ivers);
if (ei->i_extra_isize) {
if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
raw_inode->i_version_hi =
cpu_to_le32(ivers >> 32);
raw_inode->i_extra_isize =
cpu_to_le16(ei->i_extra_isize);
}
}
if (i_projid != EXT4_DEF_PROJID &&
!ext4_has_feature_project(inode->i_sb))
err = err ?: -EFSCORRUPTED;
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
raw_inode->i_projid = cpu_to_le32(i_projid);
ext4_inode_csum_set(inode, raw_inode, ei);
return err;
}
/*
* ext4_get_inode_loc returns with an extra refcount against the inode's
* underlying buffer_head on success. If we pass 'inode' and it does not
* have in-inode xattr, we have all inode data in memory that is needed
* to recreate the on-disk version of this inode.
*/
static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
struct inode *inode, struct ext4_iloc *iloc,
ext4_fsblk_t *ret_block)
{
struct ext4_group_desc *gdp;
struct buffer_head *bh;
ext4_fsblk_t block;
struct blk_plug plug;
int inodes_per_block, inode_offset;
iloc->bh = NULL;
if (ino < EXT4_ROOT_INO ||
ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return -EFSCORRUPTED;
iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
if (!gdp)
return -EIO;
/*
* Figure out the offset within the block group inode table
*/
inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
inode_offset = ((ino - 1) %
EXT4_INODES_PER_GROUP(sb));
iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
block = ext4_inode_table(sb, gdp);
if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
(block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
ext4_error(sb, "Invalid inode table block %llu in "
"block_group %u", block, iloc->block_group);
return -EFSCORRUPTED;
}
block += (inode_offset / inodes_per_block);
bh = sb_getblk(sb, block);
if (unlikely(!bh))
return -ENOMEM;
if (ext4_buffer_uptodate(bh))
goto has_buffer;
lock_buffer(bh);
if (ext4_buffer_uptodate(bh)) {
/* Someone brought it uptodate while we waited */
unlock_buffer(bh);
goto has_buffer;
}
/*
* If we have all information of the inode in memory and this
* is the only valid inode in the block, we need not read the
* block.
*/
if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
struct buffer_head *bitmap_bh;
int i, start;
start = inode_offset & ~(inodes_per_block - 1);
/* Is the inode bitmap in cache? */
bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
if (unlikely(!bitmap_bh))
goto make_io;
/*
* If the inode bitmap isn't in cache then the
* optimisation may end up performing two reads instead
* of one, so skip it.
*/
if (!buffer_uptodate(bitmap_bh)) {
brelse(bitmap_bh);
goto make_io;
}
for (i = start; i < start + inodes_per_block; i++) {
if (i == inode_offset)
continue;
if (ext4_test_bit(i, bitmap_bh->b_data))
break;
}
brelse(bitmap_bh);
if (i == start + inodes_per_block) {
struct ext4_inode *raw_inode =
(struct ext4_inode *) (bh->b_data + iloc->offset);
/* all other inodes are free, so skip I/O */
memset(bh->b_data, 0, bh->b_size);
if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
ext4_fill_raw_inode(inode, raw_inode);
set_buffer_uptodate(bh);
unlock_buffer(bh);
goto has_buffer;
}
}
make_io:
/*
* If we need to do any I/O, try to pre-readahead extra
* blocks from the inode table.
*/
blk_start_plug(&plug);
if (EXT4_SB(sb)->s_inode_readahead_blks) {
ext4_fsblk_t b, end, table;
unsigned num;
__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
table = ext4_inode_table(sb, gdp);
/* s_inode_readahead_blks is always a power of 2 */
b = block & ~((ext4_fsblk_t) ra_blks - 1);
if (table > b)
b = table;
end = b + ra_blks;
num = EXT4_INODES_PER_GROUP(sb);
if (ext4_has_group_desc_csum(sb))
num -= ext4_itable_unused_count(sb, gdp);
table += num / inodes_per_block;
if (end > table)
end = table;
while (b <= end)
ext4_sb_breadahead_unmovable(sb, b++);
}
/*
* There are other valid inodes in the buffer, this inode
* has in-inode xattrs, or we don't have this inode in memory.
* Read the block from disk.
*/
trace_ext4_load_inode(sb, ino);
ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
blk_finish_plug(&plug);
wait_on_buffer(bh);
ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
if (!buffer_uptodate(bh)) {
if (ret_block)
*ret_block = block;
brelse(bh);
return -EIO;
}
has_buffer:
iloc->bh = bh;
return 0;
}
static int __ext4_get_inode_loc_noinmem(struct inode *inode,
struct ext4_iloc *iloc)
{
ext4_fsblk_t err_blk = 0;
int ret;
ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
&err_blk);
if (ret == -EIO)
ext4_error_inode_block(inode, err_blk, EIO,
"unable to read itable block");
return ret;
}
int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
{
ext4_fsblk_t err_blk = 0;
int ret;
ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
&err_blk);
if (ret == -EIO)
ext4_error_inode_block(inode, err_blk, EIO,
"unable to read itable block");
return ret;
}
int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
struct ext4_iloc *iloc)
{
return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
}
static bool ext4_should_enable_dax(struct inode *inode)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (test_opt2(inode->i_sb, DAX_NEVER))
return false;
if (!S_ISREG(inode->i_mode))
return false;
if (ext4_should_journal_data(inode))
return false;
if (ext4_has_inline_data(inode))
return false;
if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
return false;
if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
return false;
if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
return false;
if (test_opt(inode->i_sb, DAX_ALWAYS))
return true;
return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
}
void ext4_set_inode_flags(struct inode *inode, bool init)
{
unsigned int flags = EXT4_I(inode)->i_flags;
unsigned int new_fl = 0;
WARN_ON_ONCE(IS_DAX(inode) && init);
if (flags & EXT4_SYNC_FL)
new_fl |= S_SYNC;
if (flags & EXT4_APPEND_FL)
new_fl |= S_APPEND;
if (flags & EXT4_IMMUTABLE_FL)
new_fl |= S_IMMUTABLE;
if (flags & EXT4_NOATIME_FL)
new_fl |= S_NOATIME;
if (flags & EXT4_DIRSYNC_FL)
new_fl |= S_DIRSYNC;
/* Because of the way inode_set_flags() works we must preserve S_DAX
* here if already set. */
new_fl |= (inode->i_flags & S_DAX);
if (init && ext4_should_enable_dax(inode))
new_fl |= S_DAX;
if (flags & EXT4_ENCRYPT_FL)
new_fl |= S_ENCRYPTED;
if (flags & EXT4_CASEFOLD_FL)
new_fl |= S_CASEFOLD;
if (flags & EXT4_VERITY_FL)
new_fl |= S_VERITY;
inode_set_flags(inode, new_fl,
S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
S_ENCRYPTED|S_CASEFOLD|S_VERITY);
}
static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
struct ext4_inode_info *ei)
{
blkcnt_t i_blocks ;
struct inode *inode = &(ei->vfs_inode);
struct super_block *sb = inode->i_sb;
if (ext4_has_feature_huge_file(sb)) {
/* we are using combined 48 bit field */
i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
le32_to_cpu(raw_inode->i_blocks_lo);
if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
/* i_blocks represent file system block size */
return i_blocks << (inode->i_blkbits - 9);
} else {
return i_blocks;
}
} else {
return le32_to_cpu(raw_inode->i_blocks_lo);
}
}
static inline int ext4_iget_extra_inode(struct inode *inode,
struct ext4_inode *raw_inode,
struct ext4_inode_info *ei)
{
__le32 *magic = (void *)raw_inode +
EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
int err;
ext4_set_inode_state(inode, EXT4_STATE_XATTR);
err = ext4_find_inline_data_nolock(inode);
if (!err && ext4_has_inline_data(inode))
ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
return err;
} else
EXT4_I(inode)->i_inline_off = 0;
return 0;
}
int ext4_get_projid(struct inode *inode, kprojid_t *projid)
{
if (!ext4_has_feature_project(inode->i_sb))
return -EOPNOTSUPP;
*projid = EXT4_I(inode)->i_projid;
return 0;
}
/*
* ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
* refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
* set.
*/
static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
{
if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
inode_set_iversion_raw(inode, val);
else
inode_set_iversion_queried(inode, val);
}
static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
{
if (flags & EXT4_IGET_EA_INODE) {
if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
return "missing EA_INODE flag";
if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
EXT4_I(inode)->i_file_acl)
return "ea_inode with extended attributes";
} else {
if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
return "unexpected EA_INODE flag";
}
if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
return "unexpected bad inode w/o EXT4_IGET_BAD";
return NULL;
}
struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
ext4_iget_flags flags, const char *function,
unsigned int line)
{
struct ext4_iloc iloc;
struct ext4_inode *raw_inode;
struct ext4_inode_info *ei;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct inode *inode;
const char *err_str;
journal_t *journal = EXT4_SB(sb)->s_journal;
long ret;
loff_t size;
int block;
uid_t i_uid;
gid_t i_gid;
projid_t i_projid;
if ((!(flags & EXT4_IGET_SPECIAL) &&
((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
ino == le32_to_cpu(es->s_usr_quota_inum) ||
ino == le32_to_cpu(es->s_grp_quota_inum) ||
ino == le32_to_cpu(es->s_prj_quota_inum) ||
ino == le32_to_cpu(es->s_orphan_file_inum))) ||
(ino < EXT4_ROOT_INO) ||
(ino > le32_to_cpu(es->s_inodes_count))) {
if (flags & EXT4_IGET_HANDLE)
return ERR_PTR(-ESTALE);
__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
"inode #%lu: comm %s: iget: illegal inode #",
ino, current->comm);
return ERR_PTR(-EFSCORRUPTED);
}
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW)) {
if ((err_str = check_igot_inode(inode, flags)) != NULL) {
ext4_error_inode(inode, function, line, 0, err_str);
iput(inode);
return ERR_PTR(-EFSCORRUPTED);
}
return inode;
}
ei = EXT4_I(inode);
iloc.bh = NULL;
ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
if (ret < 0)
goto bad_inode;
raw_inode = ext4_raw_inode(&iloc);
if ((flags & EXT4_IGET_HANDLE) &&
(raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
ret = -ESTALE;
goto bad_inode;
}
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
EXT4_INODE_SIZE(inode->i_sb) ||
(ei->i_extra_isize & 3)) {
ext4_error_inode(inode, function, line, 0,
"iget: bad extra_isize %u "
"(inode size %u)",
ei->i_extra_isize,
EXT4_INODE_SIZE(inode->i_sb));
ret = -EFSCORRUPTED;
goto bad_inode;
}
} else
ei->i_extra_isize = 0;
/* Precompute checksum seed for inode metadata */
if (ext4_has_metadata_csum(sb)) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 csum;
__le32 inum = cpu_to_le32(inode->i_ino);
__le32 gen = raw_inode->i_generation;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
sizeof(inum));
ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
sizeof(gen));
}
if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
(!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
ext4_error_inode_err(inode, function, line, 0,
EFSBADCRC, "iget: checksum invalid");
ret = -EFSBADCRC;
goto bad_inode;
}
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if (ext4_has_feature_project(sb) &&
EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
else
i_projid = EXT4_DEF_PROJID;
if (!(test_opt(inode->i_sb, NO_UID32))) {
i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
i_uid_write(inode, i_uid);
i_gid_write(inode, i_gid);
ei->i_projid = make_kprojid(&init_user_ns, i_projid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
ei->i_inline_off = 0;
ei->i_dir_start_lookup = 0;
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0) {
if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
ino != EXT4_BOOT_LOADER_INO) {
/* this inode is deleted or unallocated */
if (flags & EXT4_IGET_SPECIAL) {
ext4_error_inode(inode, function, line, 0,
"iget: special inode unallocated");
ret = -EFSCORRUPTED;
} else
ret = -ESTALE;
goto bad_inode;
}
/* The only unlinked inodes we let through here have
* valid i_mode and are being read by the orphan
* recovery code: that's fine, we're about to complete
* the process of deleting those.
* OR it is the EXT4_BOOT_LOADER_INO which is
* not initialized on a new filesystem. */
}
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
ext4_set_inode_flags(inode, true);
inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
if (ext4_has_feature_64bit(sb))
ei->i_file_acl |=
((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
inode->i_size = ext4_isize(sb, raw_inode);
if ((size = i_size_read(inode)) < 0) {
ext4_error_inode(inode, function, line, 0,
"iget: bad i_size value: %lld", size);
ret = -EFSCORRUPTED;
goto bad_inode;
}
/*
* If dir_index is not enabled but there's dir with INDEX flag set,
* we'd normally treat htree data as empty space. But with metadata
* checksumming that corrupts checksums so forbid that.
*/
if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
ext4_error_inode(inode, function, line, 0,
"iget: Dir with htree data on filesystem without dir_index feature.");
ret = -EFSCORRUPTED;
goto bad_inode;
}
ei->i_disksize = inode->i_size;
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_block_group = iloc.block_group;
ei->i_last_alloc_group = ~0;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (block = 0; block < EXT4_N_BLOCKS; block++)
ei->i_data[block] = raw_inode->i_block[block];
INIT_LIST_HEAD(&ei->i_orphan);
ext4_fc_init_inode(&ei->vfs_inode);
/*
* Set transaction id's of transactions that have to be committed
* to finish f[data]sync. We set them to currently running transaction
* as we cannot be sure that the inode or some of its metadata isn't
* part of the transaction - the inode could have been reclaimed and
* now it is reread from disk.
*/
if (journal) {
transaction_t *transaction;
tid_t tid;
read_lock(&journal->j_state_lock);
if (journal->j_running_transaction)
transaction = journal->j_running_transaction;
else
transaction = journal->j_committing_transaction;
if (transaction)
tid = transaction->t_tid;
else
tid = journal->j_commit_sequence;
read_unlock(&journal->j_state_lock);
ei->i_sync_tid = tid;
ei->i_datasync_tid = tid;
}
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
if (ei->i_extra_isize == 0) {
/* The extra space is currently unused. Use it. */
BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
ei->i_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
} else {
ret = ext4_iget_extra_inode(inode, raw_inode, ei);
if (ret)
goto bad_inode;
}
}
EXT4_INODE_GET_CTIME(inode, raw_inode);
EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
ivers |=
(__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
}
ext4_inode_set_iversion_queried(inode, ivers);
}
ret = 0;
if (ei->i_file_acl &&
!ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
ext4_error_inode(inode, function, line, 0,
"iget: bad extended attribute block %llu",
ei->i_file_acl);
ret = -EFSCORRUPTED;
goto bad_inode;
} else if (!ext4_has_inline_data(inode)) {
/* validate the block references in the inode */
if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
(S_ISLNK(inode->i_mode) &&
!ext4_inode_is_fast_symlink(inode)))) {
if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
ret = ext4_ext_check_inode(inode);
else
ret = ext4_ind_check_inode(inode);
}
}
if (ret)
goto bad_inode;
if (S_ISREG(inode->i_mode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext4_dir_inode_operations;
inode->i_fop = &ext4_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
/* VFS does not allow setting these so must be corruption */
if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
ext4_error_inode(inode, function, line, 0,
"iget: immutable or append flags "
"not allowed on symlinks");
ret = -EFSCORRUPTED;
goto bad_inode;
}
if (IS_ENCRYPTED(inode)) {
inode->i_op = &ext4_encrypted_symlink_inode_operations;
} else if (ext4_inode_is_fast_symlink(inode)) {
inode->i_link = (char *)ei->i_data;
inode->i_op = &ext4_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext4_symlink_inode_operations;
}
} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
inode->i_op = &ext4_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
} else if (ino == EXT4_BOOT_LOADER_INO) {
make_bad_inode(inode);
} else {
ret = -EFSCORRUPTED;
ext4_error_inode(inode, function, line, 0,
"iget: bogus i_mode (%o)", inode->i_mode);
goto bad_inode;
}
if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
ext4_error_inode(inode, function, line, 0,
"casefold flag without casefold feature");
ret = -EFSCORRUPTED;
goto bad_inode;
}
if ((err_str = check_igot_inode(inode, flags)) != NULL) {
ext4_error_inode(inode, function, line, 0, err_str);
ret = -EFSCORRUPTED;
goto bad_inode;
}
brelse(iloc.bh);
unlock_new_inode(inode);
return inode;
bad_inode:
brelse(iloc.bh);
iget_failed(inode);
return ERR_PTR(ret);
}
static void __ext4_update_other_inode_time(struct super_block *sb,
unsigned long orig_ino,
unsigned long ino,
struct ext4_inode *raw_inode)
{
struct inode *inode;
inode = find_inode_by_ino_rcu(sb, ino);
if (!inode)
return;
if (!inode_is_dirtytime_only(inode))
return;
spin_lock(&inode->i_lock);
if (inode_is_dirtytime_only(inode)) {
struct ext4_inode_info *ei = EXT4_I(inode);
inode->i_state &= ~I_DIRTY_TIME;
spin_unlock(&inode->i_lock);
spin_lock(&ei->i_raw_lock);
EXT4_INODE_SET_CTIME(inode, raw_inode);
EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
ext4_inode_csum_set(inode, raw_inode, ei);
spin_unlock(&ei->i_raw_lock);
trace_ext4_other_inode_update_time(inode, orig_ino);
return;
}
spin_unlock(&inode->i_lock);
}
/*
* Opportunistically update the other time fields for other inodes in
* the same inode table block.
*/
static void ext4_update_other_inodes_time(struct super_block *sb,
unsigned long orig_ino, char *buf)
{
unsigned long ino;
int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
int inode_size = EXT4_INODE_SIZE(sb);
/*
* Calculate the first inode in the inode table block. Inode
* numbers are one-based. That is, the first inode in a block
* (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
*/
ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
rcu_read_lock();
for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
if (ino == orig_ino)
continue;
__ext4_update_other_inode_time(sb, orig_ino, ino,
(struct ext4_inode *)buf);
}
rcu_read_unlock();
}
/*
* Post the struct inode info into an on-disk inode location in the
* buffer-cache. This gobbles the caller's reference to the
* buffer_head in the inode location struct.
*
* The caller must have write access to iloc->bh.
*/
static int ext4_do_update_inode(handle_t *handle,
struct inode *inode,
struct ext4_iloc *iloc)
{
struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
struct ext4_inode_info *ei = EXT4_I(inode);
struct buffer_head *bh = iloc->bh;
struct super_block *sb = inode->i_sb;
int err;
int need_datasync = 0, set_large_file = 0;
spin_lock(&ei->i_raw_lock);
/*
* For fields not tracked in the in-memory inode, initialise them
* to zero for new inodes.
*/
if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
need_datasync = 1;
if (ei->i_disksize > 0x7fffffffULL) {
if (!ext4_has_feature_large_file(sb) ||
EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
set_large_file = 1;
}
err = ext4_fill_raw_inode(inode, raw_inode);
spin_unlock(&ei->i_raw_lock);
if (err) {
EXT4_ERROR_INODE(inode, "corrupted inode contents");
goto out_brelse;
}
if (inode->i_sb->s_flags & SB_LAZYTIME)
ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
bh->b_data);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, NULL, bh);
if (err)
goto out_error;
ext4_clear_inode_state(inode, EXT4_STATE_NEW);
if (set_large_file) {
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
err = ext4_journal_get_write_access(handle, sb,
EXT4_SB(sb)->s_sbh,
EXT4_JTR_NONE);
if (err)
goto out_error;
lock_buffer(EXT4_SB(sb)->s_sbh);
ext4_set_feature_large_file(sb);
ext4_superblock_csum_set(sb);
unlock_buffer(EXT4_SB(sb)->s_sbh);
ext4_handle_sync(handle);
err = ext4_handle_dirty_metadata(handle, NULL,
EXT4_SB(sb)->s_sbh);
}
ext4_update_inode_fsync_trans(handle, inode, need_datasync);
out_error:
ext4_std_error(inode->i_sb, err);
out_brelse:
brelse(bh);
return err;
}
/*
* ext4_write_inode()
*
* We are called from a few places:
*
* - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
* Here, there will be no transaction running. We wait for any running
* transaction to commit.
*
* - Within flush work (sys_sync(), kupdate and such).
* We wait on commit, if told to.
*
* - Within iput_final() -> write_inode_now()
* We wait on commit, if told to.
*
* In all cases it is actually safe for us to return without doing anything,
* because the inode has been copied into a raw inode buffer in
* ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
* writeback.
*
* Note that we are absolutely dependent upon all inode dirtiers doing the
* right thing: they *must* call mark_inode_dirty() after dirtying info in
* which we are interested.
*
* It would be a bug for them to not do this. The code:
*
* mark_inode_dirty(inode)
* stuff();
* inode->i_size = expr;
*
* is in error because write_inode() could occur while `stuff()' is running,
* and the new i_size will be lost. Plus the inode will no longer be on the
* superblock's dirty inode list.
*/
int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
{
int err;
if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
return 0;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
if (EXT4_SB(inode->i_sb)->s_journal) {
if (ext4_journal_current_handle()) {
ext4_debug("called recursively, non-PF_MEMALLOC!\n");
dump_stack();
return -EIO;
}
/*
* No need to force transaction in WB_SYNC_NONE mode. Also
* ext4_sync_fs() will force the commit after everything is
* written.
*/
if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
return 0;
err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
EXT4_I(inode)->i_sync_tid);
} else {
struct ext4_iloc iloc;
err = __ext4_get_inode_loc_noinmem(inode, &iloc);
if (err)
return err;
/*
* sync(2) will flush the whole buffer cache. No need to do
* it here separately for each inode.
*/
if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
sync_dirty_buffer(iloc.bh);
if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
"IO error syncing inode");
err = -EIO;
}
brelse(iloc.bh);
}
return err;
}
/*
* In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
* buffers that are attached to a folio straddling i_size and are undergoing
* commit. In that case we have to wait for commit to finish and try again.
*/
static void ext4_wait_for_tail_page_commit(struct inode *inode)
{
unsigned offset;
journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
tid_t commit_tid = 0;
int ret;
offset = inode->i_size & (PAGE_SIZE - 1);
/*
* If the folio is fully truncated, we don't need to wait for any commit
* (and we even should not as __ext4_journalled_invalidate_folio() may
* strip all buffers from the folio but keep the folio dirty which can then
* confuse e.g. concurrent ext4_writepages() seeing dirty folio without
* buffers). Also we don't need to wait for any commit if all buffers in
* the folio remain valid. This is most beneficial for the common case of
* blocksize == PAGESIZE.
*/
if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
return;
while (1) {
struct folio *folio = filemap_lock_folio(inode->i_mapping,
inode->i_size >> PAGE_SHIFT);
if (IS_ERR(folio))
return;
ret = __ext4_journalled_invalidate_folio(folio, offset,
folio_size(folio) - offset);
folio_unlock(folio);
folio_put(folio);
if (ret != -EBUSY)
return;
commit_tid = 0;
read_lock(&journal->j_state_lock);
if (journal->j_committing_transaction)
commit_tid = journal->j_committing_transaction->t_tid;
read_unlock(&journal->j_state_lock);
if (commit_tid)
jbd2_log_wait_commit(journal, commit_tid);
}
}
/*
* ext4_setattr()
*
* Called from notify_change.
*
* We want to trap VFS attempts to truncate the file as soon as
* possible. In particular, we want to make sure that when the VFS
* shrinks i_size, we put the inode on the orphan list and modify
* i_disksize immediately, so that during the subsequent flushing of
* dirty pages and freeing of disk blocks, we can guarantee that any
* commit will leave the blocks being flushed in an unused state on
* disk. (On recovery, the inode will get truncated and the blocks will
* be freed, so we have a strong guarantee that no future commit will
* leave these blocks visible to the user.)
*
* Another thing we have to assure is that if we are in ordered mode
* and inode is still attached to the committing transaction, we must
* we start writeout of all the dirty pages which are being truncated.
* This way we are sure that all the data written in the previous
* transaction are already on disk (truncate waits for pages under
* writeback).
*
* Called with inode->i_rwsem down.
*/
int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
struct iattr *attr)
{
struct inode *inode = d_inode(dentry);
int error, rc = 0;
int orphan = 0;
const unsigned int ia_valid = attr->ia_valid;
bool inc_ivers = true;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
if (unlikely(IS_IMMUTABLE(inode)))
return -EPERM;
if (unlikely(IS_APPEND(inode) &&
(ia_valid & (ATTR_MODE | ATTR_UID |
ATTR_GID | ATTR_TIMES_SET))))
return -EPERM;
error = setattr_prepare(idmap, dentry, attr);
if (error)
return error;
error = fscrypt_prepare_setattr(dentry, attr);
if (error)
return error;
error = fsverity_prepare_setattr(dentry, attr);
if (error)
return error;
if (is_quota_modification(idmap, inode, attr)) {
error = dquot_initialize(inode);
if (error)
return error;
}
if (i_uid_needs_update(idmap, attr, inode) ||
i_gid_needs_update(idmap, attr, inode)) {
handle_t *handle;
/* (user+group)*(old+new) structure, inode write (sb,
* inode block, ? - but truncate inode update has it) */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto err_out;
}
/* dquot_transfer() calls back ext4_get_inode_usage() which
* counts xattr inode references.
*/
down_read(&EXT4_I(inode)->xattr_sem);
error = dquot_transfer(idmap, inode, attr);
up_read(&EXT4_I(inode)->xattr_sem);
if (error) {
ext4_journal_stop(handle);
return error;
}
/* Update corresponding info in inode so that everything is in
* one transaction */
i_uid_update(idmap, attr, inode);
i_gid_update(idmap, attr, inode);
error = ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
if (unlikely(error)) {
return error;
}
}
if (attr->ia_valid & ATTR_SIZE) {
handle_t *handle;
loff_t oldsize = inode->i_size;
loff_t old_disksize;
int shrink = (attr->ia_size < inode->i_size);
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (attr->ia_size > sbi->s_bitmap_maxbytes) {
return -EFBIG;
}
}
if (!S_ISREG(inode->i_mode)) {
return -EINVAL;
}
if (attr->ia_size == inode->i_size)
inc_ivers = false;
if (shrink) {
if (ext4_should_order_data(inode)) {
error = ext4_begin_ordered_truncate(inode,
attr->ia_size);
if (error)
goto err_out;
}
/*
* Blocks are going to be removed from the inode. Wait
* for dio in flight.
*/
inode_dio_wait(inode);
}
filemap_invalidate_lock(inode->i_mapping);
rc = ext4_break_layouts(inode);
if (rc) {
filemap_invalidate_unlock(inode->i_mapping);
goto err_out;
}
if (attr->ia_size != inode->i_size) {
handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto out_mmap_sem;
}
if (ext4_handle_valid(handle) && shrink) {
error = ext4_orphan_add(handle, inode);
orphan = 1;
}
/*
* Update c/mtime on truncate up, ext4_truncate() will
* update c/mtime in shrink case below
*/
if (!shrink)
inode->i_mtime = inode_set_ctime_current(inode);
if (shrink)
ext4_fc_track_range(handle, inode,
(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
inode->i_sb->s_blocksize_bits,
EXT_MAX_BLOCKS - 1);
else
ext4_fc_track_range(
handle, inode,
(oldsize > 0 ? oldsize - 1 : oldsize) >>
inode->i_sb->s_blocksize_bits,
(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
inode->i_sb->s_blocksize_bits);
down_write(&EXT4_I(inode)->i_data_sem);
old_disksize = EXT4_I(inode)->i_disksize;
EXT4_I(inode)->i_disksize = attr->ia_size;
rc = ext4_mark_inode_dirty(handle, inode);
if (!error)
error = rc;
/*
* We have to update i_size under i_data_sem together
* with i_disksize to avoid races with writeback code
* running ext4_wb_update_i_disksize().
*/
if (!error)
i_size_write(inode, attr->ia_size);
else
EXT4_I(inode)->i_disksize = old_disksize;
up_write(&EXT4_I(inode)->i_data_sem);
ext4_journal_stop(handle);
if (error)
goto out_mmap_sem;
if (!shrink) {
pagecache_isize_extended(inode, oldsize,
inode->i_size);
} else if (ext4_should_journal_data(inode)) {
ext4_wait_for_tail_page_commit(inode);
}
}
/*
* Truncate pagecache after we've waited for commit
* in data=journal mode to make pages freeable.
*/
truncate_pagecache(inode, inode->i_size);
/*
* Call ext4_truncate() even if i_size didn't change to
* truncate possible preallocated blocks.
*/
if (attr->ia_size <= oldsize) {
rc = ext4_truncate(inode);
if (rc)
error = rc;
}
out_mmap_sem:
filemap_invalidate_unlock(inode->i_mapping);
}
if (!error) {
if (inc_ivers)
inode_inc_iversion(inode);
setattr_copy(idmap, inode, attr);
mark_inode_dirty(inode);
}
/*
* If the call to ext4_truncate failed to get a transaction handle at
* all, we need to clean up the in-core orphan list manually.
*/
if (orphan && inode->i_nlink)
ext4_orphan_del(NULL, inode);
if (!error && (ia_valid & ATTR_MODE))
rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
err_out:
if (error)
ext4_std_error(inode->i_sb, error);
if (!error)
error = rc;
return error;
}
u32 ext4_dio_alignment(struct inode *inode)
{
if (fsverity_active(inode))
return 0;
if (ext4_should_journal_data(inode))
return 0;
if (ext4_has_inline_data(inode))
return 0;
if (IS_ENCRYPTED(inode)) {
if (!fscrypt_dio_supported(inode))
return 0;
return i_blocksize(inode);
}
return 1; /* use the iomap defaults */
}
int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
struct kstat *stat, u32 request_mask, unsigned int query_flags)
{
struct inode *inode = d_inode(path->dentry);
struct ext4_inode *raw_inode;
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned int flags;
if ((request_mask & STATX_BTIME) &&
EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
stat->result_mask |= STATX_BTIME;
stat->btime.tv_sec = ei->i_crtime.tv_sec;
stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
}
/*
* Return the DIO alignment restrictions if requested. We only return
* this information when requested, since on encrypted files it might
* take a fair bit of work to get if the file wasn't opened recently.
*/
if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
u32 dio_align = ext4_dio_alignment(inode);
stat->result_mask |= STATX_DIOALIGN;
if (dio_align == 1) {
struct block_device *bdev = inode->i_sb->s_bdev;
/* iomap defaults */
stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
stat->dio_offset_align = bdev_logical_block_size(bdev);
} else {
stat->dio_mem_align = dio_align;
stat->dio_offset_align = dio_align;
}
}
flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
if (flags & EXT4_APPEND_FL)
stat->attributes |= STATX_ATTR_APPEND;
if (flags & EXT4_COMPR_FL)
stat->attributes |= STATX_ATTR_COMPRESSED;
if (flags & EXT4_ENCRYPT_FL)
stat->attributes |= STATX_ATTR_ENCRYPTED;
if (flags & EXT4_IMMUTABLE_FL)
stat->attributes |= STATX_ATTR_IMMUTABLE;
if (flags & EXT4_NODUMP_FL)
stat->attributes |= STATX_ATTR_NODUMP;
if (flags & EXT4_VERITY_FL)
stat->attributes |= STATX_ATTR_VERITY;
stat->attributes_mask |= (STATX_ATTR_APPEND |
STATX_ATTR_COMPRESSED |
STATX_ATTR_ENCRYPTED |
STATX_ATTR_IMMUTABLE |
STATX_ATTR_NODUMP |
STATX_ATTR_VERITY);
generic_fillattr(idmap, request_mask, inode, stat);
return 0;
}
int ext4_file_getattr(struct mnt_idmap *idmap,
const struct path *path, struct kstat *stat,
u32 request_mask, unsigned int query_flags)
{
struct inode *inode = d_inode(path->dentry);
u64 delalloc_blocks;
ext4_getattr(idmap, path, stat, request_mask, query_flags);
/*
* If there is inline data in the inode, the inode will normally not
* have data blocks allocated (it may have an external xattr block).
* Report at least one sector for such files, so tools like tar, rsync,
* others don't incorrectly think the file is completely sparse.
*/
if (unlikely(ext4_has_inline_data(inode)))
stat->blocks += (stat->size + 511) >> 9;
/*
* We can't update i_blocks if the block allocation is delayed
* otherwise in the case of system crash before the real block
* allocation is done, we will have i_blocks inconsistent with
* on-disk file blocks.
* We always keep i_blocks updated together with real
* allocation. But to not confuse with user, stat
* will return the blocks that include the delayed allocation
* blocks for this file.
*/
delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
EXT4_I(inode)->i_reserved_data_blocks);
stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
return 0;
}
static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
int pextents)
{
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
return ext4_ind_trans_blocks(inode, lblocks);
return ext4_ext_index_trans_blocks(inode, pextents);
}
/*
* Account for index blocks, block groups bitmaps and block group
* descriptor blocks if modify datablocks and index blocks
* worse case, the indexs blocks spread over different block groups
*
* If datablocks are discontiguous, they are possible to spread over
* different block groups too. If they are contiguous, with flexbg,
* they could still across block group boundary.
*
* Also account for superblock, inode, quota and xattr blocks
*/
static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
int pextents)
{
ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
int gdpblocks;
int idxblocks;
int ret;
/*
* How many index blocks need to touch to map @lblocks logical blocks
* to @pextents physical extents?
*/
idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
ret = idxblocks;
/*
* Now let's see how many group bitmaps and group descriptors need
* to account
*/
groups = idxblocks + pextents;
gdpblocks = groups;
if (groups > ngroups)
groups = ngroups;
if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
/* bitmaps and block group descriptor blocks */
ret += groups + gdpblocks;
/* Blocks for super block, inode, quota and xattr blocks */
ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
return ret;
}
/*
* Calculate the total number of credits to reserve to fit
* the modification of a single pages into a single transaction,
* which may include multiple chunks of block allocations.
*
* This could be called via ext4_write_begin()
*
* We need to consider the worse case, when
* one new block per extent.
*/
int ext4_writepage_trans_blocks(struct inode *inode)
{
int bpp = ext4_journal_blocks_per_page(inode);
int ret;
ret = ext4_meta_trans_blocks(inode, bpp, bpp);
/* Account for data blocks for journalled mode */
if (ext4_should_journal_data(inode))
ret += bpp;
return ret;
}
/*
* Calculate the journal credits for a chunk of data modification.
*
* This is called from DIO, fallocate or whoever calling
* ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
*
* journal buffers for data blocks are not included here, as DIO
* and fallocate do no need to journal data buffers.
*/
int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
{
return ext4_meta_trans_blocks(inode, nrblocks, 1);
}
/*
* The caller must have previously called ext4_reserve_inode_write().
* Give this, we know that the caller already has write access to iloc->bh.
*/
int ext4_mark_iloc_dirty(handle_t *handle,
struct inode *inode, struct ext4_iloc *iloc)
{
int err = 0;
if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
put_bh(iloc->bh);
return -EIO;
}
ext4_fc_track_inode(handle, inode);
/* the do_update_inode consumes one bh->b_count */
get_bh(iloc->bh);
/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
err = ext4_do_update_inode(handle, inode, iloc);
put_bh(iloc->bh);
return err;
}
/*
* On success, We end up with an outstanding reference count against
* iloc->bh. This _must_ be cleaned up later.
*/
int
ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
struct ext4_iloc *iloc)
{
int err;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
err = ext4_get_inode_loc(inode, iloc);
if (!err) {
BUFFER_TRACE(iloc->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb,
iloc->bh, EXT4_JTR_NONE);
if (err) {
brelse(iloc->bh);
iloc->bh = NULL;
}
}
ext4_std_error(inode->i_sb, err);
return err;
}
static int __ext4_expand_extra_isize(struct inode *inode,
unsigned int new_extra_isize,
struct ext4_iloc *iloc,
handle_t *handle, int *no_expand)
{
struct ext4_inode *raw_inode;
struct ext4_xattr_ibody_header *header;
unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
int error;
/* this was checked at iget time, but double check for good measure */
if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
(ei->i_extra_isize & 3)) {
EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
ei->i_extra_isize,
EXT4_INODE_SIZE(inode->i_sb));
return -EFSCORRUPTED;
}
if ((new_extra_isize < ei->i_extra_isize) ||
(new_extra_isize < 4) ||
(new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
return -EINVAL; /* Should never happen */
raw_inode = ext4_raw_inode(iloc);
header = IHDR(inode, raw_inode);
/* No extended attributes present */
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
EXT4_I(inode)->i_extra_isize, 0,
new_extra_isize - EXT4_I(inode)->i_extra_isize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
return 0;
}
/*
* We may need to allocate external xattr block so we need quotas
* initialized. Here we can be called with various locks held so we
* cannot affort to initialize quotas ourselves. So just bail.
*/
if (dquot_initialize_needed(inode))
return -EAGAIN;
/* try to expand with EAs present */
error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
raw_inode, handle);
if (error) {
/*
* Inode size expansion failed; don't try again
*/
*no_expand = 1;
}
return error;
}
/*
* Expand an inode by new_extra_isize bytes.
* Returns 0 on success or negative error number on failure.
*/
static int ext4_try_to_expand_extra_isize(struct inode *inode,
unsigned int new_extra_isize,
struct ext4_iloc iloc,
handle_t *handle)
{
int no_expand;
int error;
if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
return -EOVERFLOW;
/*
* In nojournal mode, we can immediately attempt to expand
* the inode. When journaled, we first need to obtain extra
* buffer credits since we may write into the EA block
* with this same handle. If journal_extend fails, then it will
* only result in a minor loss of functionality for that inode.
* If this is felt to be critical, then e2fsck should be run to
* force a large enough s_min_extra_isize.
*/
if (ext4_journal_extend(handle,
EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
return -ENOSPC;
if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
return -EBUSY;
error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
handle, &no_expand);
ext4_write_unlock_xattr(inode, &no_expand);
return error;
}
int ext4_expand_extra_isize(struct inode *inode,
unsigned int new_extra_isize,
struct ext4_iloc *iloc)
{
handle_t *handle;
int no_expand;
int error, rc;
if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
brelse(iloc->bh);
return -EOVERFLOW;
}
handle = ext4_journal_start(inode, EXT4_HT_INODE,
EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
brelse(iloc->bh);
return error;
}
ext4_write_lock_xattr(inode, &no_expand);
BUFFER_TRACE(iloc->bh, "get_write_access");
error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
EXT4_JTR_NONE);
if (error) {
brelse(iloc->bh);
goto out_unlock;
}
error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
handle, &no_expand);
rc = ext4_mark_iloc_dirty(handle, inode, iloc);
if (!error)
error = rc;
out_unlock:
ext4_write_unlock_xattr(inode, &no_expand);
ext4_journal_stop(handle);
return error;
}
/*
* What we do here is to mark the in-core inode as clean with respect to inode
* dirtiness (it may still be data-dirty).
* This means that the in-core inode may be reaped by prune_icache
* without having to perform any I/O. This is a very good thing,
* because *any* task may call prune_icache - even ones which
* have a transaction open against a different journal.
*
* Is this cheating? Not really. Sure, we haven't written the
* inode out, but prune_icache isn't a user-visible syncing function.
* Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
* we start and wait on commits.
*/
int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
const char *func, unsigned int line)
{
struct ext4_iloc iloc;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
int err;
might_sleep();
trace_ext4_mark_inode_dirty(inode, _RET_IP_);
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out;
if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
iloc, handle);
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out:
if (unlikely(err))
ext4_error_inode_err(inode, func, line, 0, err,
"mark_inode_dirty error");
return err;
}
/*
* ext4_dirty_inode() is called from __mark_inode_dirty()
*
* We're really interested in the case where a file is being extended.
* i_size has been changed by generic_commit_write() and we thus need
* to include the updated inode in the current transaction.
*
* Also, dquot_alloc_block() will always dirty the inode when blocks
* are allocated to the file.
*
* If the inode is marked synchronous, we don't honour that here - doing
* so would cause a commit on atime updates, which we don't bother doing.
* We handle synchronous inodes at the highest possible level.
*/
void ext4_dirty_inode(struct inode *inode, int flags)
{
handle_t *handle;
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle))
return;
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
}
int ext4_change_inode_journal_flag(struct inode *inode, int val)
{
journal_t *journal;
handle_t *handle;
int err;
int alloc_ctx;
/*
* We have to be very careful here: changing a data block's
* journaling status dynamically is dangerous. If we write a
* data block to the journal, change the status and then delete
* that block, we risk forgetting to revoke the old log record
* from the journal and so a subsequent replay can corrupt data.
* So, first we make sure that the journal is empty and that
* nobody is changing anything.
*/
journal = EXT4_JOURNAL(inode);
if (!journal)
return 0;
if (is_journal_aborted(journal))
return -EROFS;
/* Wait for all existing dio workers */
inode_dio_wait(inode);
/*
* Before flushing the journal and switching inode's aops, we have
* to flush all dirty data the inode has. There can be outstanding
* delayed allocations, there can be unwritten extents created by
* fallocate or buffered writes in dioread_nolock mode covered by
* dirty data which can be converted only after flushing the dirty
* data (and journalled aops don't know how to handle these cases).
*/
if (val) {
filemap_invalidate_lock(inode->i_mapping);
err = filemap_write_and_wait(inode->i_mapping);
if (err < 0) {
filemap_invalidate_unlock(inode->i_mapping);
return err;
}
}
alloc_ctx = ext4_writepages_down_write(inode->i_sb);
jbd2_journal_lock_updates(journal);
/*
* OK, there are no updates running now, and all cached data is
* synced to disk. We are now in a completely consistent state
* which doesn't have anything in the journal, and we know that
* no filesystem updates are running, so it is safe to modify
* the inode's in-core data-journaling state flag now.
*/
if (val)
ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
else {
err = jbd2_journal_flush(journal, 0);
if (err < 0) {
jbd2_journal_unlock_updates(journal);
ext4_writepages_up_write(inode->i_sb, alloc_ctx);
return err;
}
ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
}
ext4_set_aops(inode);
jbd2_journal_unlock_updates(journal);
ext4_writepages_up_write(inode->i_sb, alloc_ctx);
if (val)
filemap_invalidate_unlock(inode->i_mapping);
/* Finally we can mark the inode as dirty. */
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
ext4_fc_mark_ineligible(inode->i_sb,
EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
err = ext4_mark_inode_dirty(handle, inode);
ext4_handle_sync(handle);
ext4_journal_stop(handle);
ext4_std_error(inode->i_sb, err);
return err;
}
static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
return !buffer_mapped(bh);
}
vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
{
struct vm_area_struct *vma = vmf->vma;
struct folio *folio = page_folio(vmf->page);
loff_t size;
unsigned long len;
int err;
vm_fault_t ret;
struct file *file = vma->vm_file;
struct inode *inode = file_inode(file);
struct address_space *mapping = inode->i_mapping;
handle_t *handle;
get_block_t *get_block;
int retries = 0;
if (unlikely(IS_IMMUTABLE(inode)))
return VM_FAULT_SIGBUS;
sb_start_pagefault(inode->i_sb);
file_update_time(vma->vm_file);
filemap_invalidate_lock_shared(mapping);
err = ext4_convert_inline_data(inode);
if (err)
goto out_ret;
/*
* On data journalling we skip straight to the transaction handle:
* there's no delalloc; page truncated will be checked later; the
* early return w/ all buffers mapped (calculates size/len) can't
* be used; and there's no dioread_nolock, so only ext4_get_block.
*/
if (ext4_should_journal_data(inode))
goto retry_alloc;
/* Delalloc case is easy... */
if (test_opt(inode->i_sb, DELALLOC) &&
!ext4_nonda_switch(inode->i_sb)) {
do {
err = block_page_mkwrite(vma, vmf,
ext4_da_get_block_prep);
} while (err == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries));
goto out_ret;
}
folio_lock(folio);
size = i_size_read(inode);
/* Page got truncated from under us? */
if (folio->mapping != mapping || folio_pos(folio) > size) {
folio_unlock(folio);
ret = VM_FAULT_NOPAGE;
goto out;
}
len = folio_size(folio);
if (folio_pos(folio) + len > size)
len = size - folio_pos(folio);
/*
* Return if we have all the buffers mapped. This avoids the need to do
* journal_start/journal_stop which can block and take a long time
*
* This cannot be done for data journalling, as we have to add the
* inode to the transaction's list to writeprotect pages on commit.
*/
if (folio_buffers(folio)) {
if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
0, len, NULL,
ext4_bh_unmapped)) {
/* Wait so that we don't change page under IO */
folio_wait_stable(folio);
ret = VM_FAULT_LOCKED;
goto out;
}
}
folio_unlock(folio);
/* OK, we need to fill the hole... */
if (ext4_should_dioread_nolock(inode))
get_block = ext4_get_block_unwritten;
else
get_block = ext4_get_block;
retry_alloc:
handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
ext4_writepage_trans_blocks(inode));
if (IS_ERR(handle)) {
ret = VM_FAULT_SIGBUS;
goto out;
}
/*
* Data journalling can't use block_page_mkwrite() because it
* will set_buffer_dirty() before do_journal_get_write_access()
* thus might hit warning messages for dirty metadata buffers.
*/
if (!ext4_should_journal_data(inode)) {
err = block_page_mkwrite(vma, vmf, get_block);
} else {
folio_lock(folio);
size = i_size_read(inode);
/* Page got truncated from under us? */
if (folio->mapping != mapping || folio_pos(folio) > size) {
ret = VM_FAULT_NOPAGE;
goto out_error;
}
len = folio_size(folio);
if (folio_pos(folio) + len > size)
len = size - folio_pos(folio);
err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
if (!err) {
ret = VM_FAULT_SIGBUS;
if (ext4_journal_folio_buffers(handle, folio, len))
goto out_error;
} else {
folio_unlock(folio);
}
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry_alloc;
out_ret:
ret = vmf_fs_error(err);
out:
filemap_invalidate_unlock_shared(mapping);
sb_end_pagefault(inode->i_sb);
return ret;
out_error:
folio_unlock(folio);
ext4_journal_stop(handle);
goto out;
}
| linux-master | fs/ext4/inode.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/ioctl.c
*
* Copyright (C) 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include <linux/fs.h>
#include <linux/capability.h>
#include <linux/time.h>
#include <linux/compat.h>
#include <linux/mount.h>
#include <linux/file.h>
#include <linux/quotaops.h>
#include <linux/random.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/iversion.h>
#include <linux/fileattr.h>
#include <linux/uuid.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include <linux/fsmap.h>
#include "fsmap.h"
#include <trace/events/ext4.h>
typedef void ext4_update_sb_callback(struct ext4_super_block *es,
const void *arg);
/*
* Superblock modification callback function for changing file system
* label
*/
static void ext4_sb_setlabel(struct ext4_super_block *es, const void *arg)
{
/* Sanity check, this should never happen */
BUILD_BUG_ON(sizeof(es->s_volume_name) < EXT4_LABEL_MAX);
memcpy(es->s_volume_name, (char *)arg, EXT4_LABEL_MAX);
}
/*
* Superblock modification callback function for changing file system
* UUID.
*/
static void ext4_sb_setuuid(struct ext4_super_block *es, const void *arg)
{
memcpy(es->s_uuid, (__u8 *)arg, UUID_SIZE);
}
static
int ext4_update_primary_sb(struct super_block *sb, handle_t *handle,
ext4_update_sb_callback func,
const void *arg)
{
int err = 0;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *bh = sbi->s_sbh;
struct ext4_super_block *es = sbi->s_es;
trace_ext4_update_sb(sb, bh->b_blocknr, 1);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb,
bh,
EXT4_JTR_NONE);
if (err)
goto out_err;
lock_buffer(bh);
func(es, arg);
ext4_superblock_csum_set(sb);
unlock_buffer(bh);
if (buffer_write_io_error(bh) || !buffer_uptodate(bh)) {
ext4_msg(sbi->s_sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(bh);
set_buffer_uptodate(bh);
}
err = ext4_handle_dirty_metadata(handle, NULL, bh);
if (err)
goto out_err;
err = sync_dirty_buffer(bh);
out_err:
ext4_std_error(sb, err);
return err;
}
/*
* Update one backup superblock in the group 'grp' using the callback
* function 'func' and argument 'arg'. If the handle is NULL the
* modification is not journalled.
*
* Returns: 0 when no modification was done (no superblock in the group)
* 1 when the modification was successful
* <0 on error
*/
static int ext4_update_backup_sb(struct super_block *sb,
handle_t *handle, ext4_group_t grp,
ext4_update_sb_callback func, const void *arg)
{
int err = 0;
ext4_fsblk_t sb_block;
struct buffer_head *bh;
unsigned long offset = 0;
struct ext4_super_block *es;
if (!ext4_bg_has_super(sb, grp))
return 0;
/*
* For the group 0 there is always 1k padding, so we have
* either adjust offset, or sb_block depending on blocksize
*/
if (grp == 0) {
sb_block = 1 * EXT4_MIN_BLOCK_SIZE;
offset = do_div(sb_block, sb->s_blocksize);
} else {
sb_block = ext4_group_first_block_no(sb, grp);
offset = 0;
}
trace_ext4_update_sb(sb, sb_block, handle ? 1 : 0);
bh = ext4_sb_bread(sb, sb_block, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (handle) {
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb,
bh,
EXT4_JTR_NONE);
if (err)
goto out_bh;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
lock_buffer(bh);
if (ext4_has_metadata_csum(sb) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "Invalid checksum for backup "
"superblock %llu", sb_block);
unlock_buffer(bh);
goto out_bh;
}
func(es, arg);
if (ext4_has_metadata_csum(sb))
es->s_checksum = ext4_superblock_csum(sb, es);
set_buffer_uptodate(bh);
unlock_buffer(bh);
if (handle) {
err = ext4_handle_dirty_metadata(handle, NULL, bh);
if (err)
goto out_bh;
} else {
BUFFER_TRACE(bh, "marking dirty");
mark_buffer_dirty(bh);
}
err = sync_dirty_buffer(bh);
out_bh:
brelse(bh);
ext4_std_error(sb, err);
return (err) ? err : 1;
}
/*
* Update primary and backup superblocks using the provided function
* func and argument arg.
*
* Only the primary superblock and at most two backup superblock
* modifications are journalled; the rest is modified without journal.
* This is safe because e2fsck will re-write them if there is a problem,
* and we're very unlikely to ever need more than two backups.
*/
static
int ext4_update_superblocks_fn(struct super_block *sb,
ext4_update_sb_callback func,
const void *arg)
{
handle_t *handle;
ext4_group_t ngroups;
unsigned int three = 1;
unsigned int five = 5;
unsigned int seven = 7;
int err = 0, ret, i;
ext4_group_t grp, primary_grp;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* We can't update superblocks while the online resize is running
*/
if (test_and_set_bit_lock(EXT4_FLAGS_RESIZING,
&sbi->s_ext4_flags)) {
ext4_msg(sb, KERN_ERR, "Can't modify superblock while"
"performing online resize");
return -EBUSY;
}
/*
* We're only going to update primary superblock and two
* backup superblocks in this transaction.
*/
handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 3);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto out;
}
/* Update primary superblock */
err = ext4_update_primary_sb(sb, handle, func, arg);
if (err) {
ext4_msg(sb, KERN_ERR, "Failed to update primary "
"superblock");
goto out_journal;
}
primary_grp = ext4_get_group_number(sb, sbi->s_sbh->b_blocknr);
ngroups = ext4_get_groups_count(sb);
/*
* Update backup superblocks. We have to start from group 0
* because it might not be where the primary superblock is
* if the fs is mounted with -o sb=<backup_sb_block>
*/
i = 0;
grp = 0;
while (grp < ngroups) {
/* Skip primary superblock */
if (grp == primary_grp)
goto next_grp;
ret = ext4_update_backup_sb(sb, handle, grp, func, arg);
if (ret < 0) {
/* Ignore bad checksum; try to update next sb */
if (ret == -EFSBADCRC)
goto next_grp;
err = ret;
goto out_journal;
}
i += ret;
if (handle && i > 1) {
/*
* We're only journalling primary superblock and
* two backup superblocks; the rest is not
* journalled.
*/
err = ext4_journal_stop(handle);
if (err)
goto out;
handle = NULL;
}
next_grp:
grp = ext4_list_backups(sb, &three, &five, &seven);
}
out_journal:
if (handle) {
ret = ext4_journal_stop(handle);
if (ret && !err)
err = ret;
}
out:
clear_bit_unlock(EXT4_FLAGS_RESIZING, &sbi->s_ext4_flags);
smp_mb__after_atomic();
return err ? err : 0;
}
/*
* Swap memory between @a and @b for @len bytes.
*
* @a: pointer to first memory area
* @b: pointer to second memory area
* @len: number of bytes to swap
*
*/
static void memswap(void *a, void *b, size_t len)
{
unsigned char *ap, *bp;
ap = (unsigned char *)a;
bp = (unsigned char *)b;
while (len-- > 0) {
swap(*ap, *bp);
ap++;
bp++;
}
}
/*
* Swap i_data and associated attributes between @inode1 and @inode2.
* This function is used for the primary swap between inode1 and inode2
* and also to revert this primary swap in case of errors.
*
* Therefore you have to make sure, that calling this method twice
* will revert all changes.
*
* @inode1: pointer to first inode
* @inode2: pointer to second inode
*/
static void swap_inode_data(struct inode *inode1, struct inode *inode2)
{
loff_t isize;
struct ext4_inode_info *ei1;
struct ext4_inode_info *ei2;
unsigned long tmp;
ei1 = EXT4_I(inode1);
ei2 = EXT4_I(inode2);
swap(inode1->i_version, inode2->i_version);
swap(inode1->i_atime, inode2->i_atime);
swap(inode1->i_mtime, inode2->i_mtime);
memswap(ei1->i_data, ei2->i_data, sizeof(ei1->i_data));
tmp = ei1->i_flags & EXT4_FL_SHOULD_SWAP;
ei1->i_flags = (ei2->i_flags & EXT4_FL_SHOULD_SWAP) |
(ei1->i_flags & ~EXT4_FL_SHOULD_SWAP);
ei2->i_flags = tmp | (ei2->i_flags & ~EXT4_FL_SHOULD_SWAP);
swap(ei1->i_disksize, ei2->i_disksize);
ext4_es_remove_extent(inode1, 0, EXT_MAX_BLOCKS);
ext4_es_remove_extent(inode2, 0, EXT_MAX_BLOCKS);
isize = i_size_read(inode1);
i_size_write(inode1, i_size_read(inode2));
i_size_write(inode2, isize);
}
void ext4_reset_inode_seed(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__le32 inum = cpu_to_le32(inode->i_ino);
__le32 gen = cpu_to_le32(inode->i_generation);
__u32 csum;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum, sizeof(inum));
ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen, sizeof(gen));
}
/*
* Swap the information from the given @inode and the inode
* EXT4_BOOT_LOADER_INO. It will basically swap i_data and all other
* important fields of the inodes.
*
* @sb: the super block of the filesystem
* @idmap: idmap of the mount the inode was found from
* @inode: the inode to swap with EXT4_BOOT_LOADER_INO
*
*/
static long swap_inode_boot_loader(struct super_block *sb,
struct mnt_idmap *idmap,
struct inode *inode)
{
handle_t *handle;
int err;
struct inode *inode_bl;
struct ext4_inode_info *ei_bl;
qsize_t size, size_bl, diff;
blkcnt_t blocks;
unsigned short bytes;
inode_bl = ext4_iget(sb, EXT4_BOOT_LOADER_INO,
EXT4_IGET_SPECIAL | EXT4_IGET_BAD);
if (IS_ERR(inode_bl))
return PTR_ERR(inode_bl);
ei_bl = EXT4_I(inode_bl);
/* Protect orig inodes against a truncate and make sure,
* that only 1 swap_inode_boot_loader is running. */
lock_two_nondirectories(inode, inode_bl);
if (inode->i_nlink != 1 || !S_ISREG(inode->i_mode) ||
IS_SWAPFILE(inode) || IS_ENCRYPTED(inode) ||
(EXT4_I(inode)->i_flags & EXT4_JOURNAL_DATA_FL) ||
ext4_has_inline_data(inode)) {
err = -EINVAL;
goto journal_err_out;
}
if (IS_RDONLY(inode) || IS_APPEND(inode) || IS_IMMUTABLE(inode) ||
!inode_owner_or_capable(idmap, inode) ||
!capable(CAP_SYS_ADMIN)) {
err = -EPERM;
goto journal_err_out;
}
filemap_invalidate_lock(inode->i_mapping);
err = filemap_write_and_wait(inode->i_mapping);
if (err)
goto err_out;
err = filemap_write_and_wait(inode_bl->i_mapping);
if (err)
goto err_out;
/* Wait for all existing dio workers */
inode_dio_wait(inode);
inode_dio_wait(inode_bl);
truncate_inode_pages(&inode->i_data, 0);
truncate_inode_pages(&inode_bl->i_data, 0);
handle = ext4_journal_start(inode_bl, EXT4_HT_MOVE_EXTENTS, 2);
if (IS_ERR(handle)) {
err = -EINVAL;
goto err_out;
}
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_SWAP_BOOT, handle);
/* Protect extent tree against block allocations via delalloc */
ext4_double_down_write_data_sem(inode, inode_bl);
if (is_bad_inode(inode_bl) || !S_ISREG(inode_bl->i_mode)) {
/* this inode has never been used as a BOOT_LOADER */
set_nlink(inode_bl, 1);
i_uid_write(inode_bl, 0);
i_gid_write(inode_bl, 0);
inode_bl->i_flags = 0;
ei_bl->i_flags = 0;
inode_set_iversion(inode_bl, 1);
i_size_write(inode_bl, 0);
EXT4_I(inode_bl)->i_disksize = inode_bl->i_size;
inode_bl->i_mode = S_IFREG;
if (ext4_has_feature_extents(sb)) {
ext4_set_inode_flag(inode_bl, EXT4_INODE_EXTENTS);
ext4_ext_tree_init(handle, inode_bl);
} else
memset(ei_bl->i_data, 0, sizeof(ei_bl->i_data));
}
err = dquot_initialize(inode);
if (err)
goto err_out1;
size = (qsize_t)(inode->i_blocks) * (1 << 9) + inode->i_bytes;
size_bl = (qsize_t)(inode_bl->i_blocks) * (1 << 9) + inode_bl->i_bytes;
diff = size - size_bl;
swap_inode_data(inode, inode_bl);
inode_set_ctime_current(inode);
inode_set_ctime_current(inode_bl);
inode_inc_iversion(inode);
inode->i_generation = get_random_u32();
inode_bl->i_generation = get_random_u32();
ext4_reset_inode_seed(inode);
ext4_reset_inode_seed(inode_bl);
ext4_discard_preallocations(inode, 0);
err = ext4_mark_inode_dirty(handle, inode);
if (err < 0) {
/* No need to update quota information. */
ext4_warning(inode->i_sb,
"couldn't mark inode #%lu dirty (err %d)",
inode->i_ino, err);
/* Revert all changes: */
swap_inode_data(inode, inode_bl);
ext4_mark_inode_dirty(handle, inode);
goto err_out1;
}
blocks = inode_bl->i_blocks;
bytes = inode_bl->i_bytes;
inode_bl->i_blocks = inode->i_blocks;
inode_bl->i_bytes = inode->i_bytes;
err = ext4_mark_inode_dirty(handle, inode_bl);
if (err < 0) {
/* No need to update quota information. */
ext4_warning(inode_bl->i_sb,
"couldn't mark inode #%lu dirty (err %d)",
inode_bl->i_ino, err);
goto revert;
}
/* Bootloader inode should not be counted into quota information. */
if (diff > 0)
dquot_free_space(inode, diff);
else
err = dquot_alloc_space(inode, -1 * diff);
if (err < 0) {
revert:
/* Revert all changes: */
inode_bl->i_blocks = blocks;
inode_bl->i_bytes = bytes;
swap_inode_data(inode, inode_bl);
ext4_mark_inode_dirty(handle, inode);
ext4_mark_inode_dirty(handle, inode_bl);
}
err_out1:
ext4_journal_stop(handle);
ext4_double_up_write_data_sem(inode, inode_bl);
err_out:
filemap_invalidate_unlock(inode->i_mapping);
journal_err_out:
unlock_two_nondirectories(inode, inode_bl);
iput(inode_bl);
return err;
}
/*
* If immutable is set and we are not clearing it, we're not allowed to change
* anything else in the inode. Don't error out if we're only trying to set
* immutable on an immutable file.
*/
static int ext4_ioctl_check_immutable(struct inode *inode, __u32 new_projid,
unsigned int flags)
{
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned int oldflags = ei->i_flags;
if (!(oldflags & EXT4_IMMUTABLE_FL) || !(flags & EXT4_IMMUTABLE_FL))
return 0;
if ((oldflags & ~EXT4_IMMUTABLE_FL) != (flags & ~EXT4_IMMUTABLE_FL))
return -EPERM;
if (ext4_has_feature_project(inode->i_sb) &&
__kprojid_val(ei->i_projid) != new_projid)
return -EPERM;
return 0;
}
static void ext4_dax_dontcache(struct inode *inode, unsigned int flags)
{
struct ext4_inode_info *ei = EXT4_I(inode);
if (S_ISDIR(inode->i_mode))
return;
if (test_opt2(inode->i_sb, DAX_NEVER) ||
test_opt(inode->i_sb, DAX_ALWAYS))
return;
if ((ei->i_flags ^ flags) & EXT4_DAX_FL)
d_mark_dontcache(inode);
}
static bool dax_compatible(struct inode *inode, unsigned int oldflags,
unsigned int flags)
{
/* Allow the DAX flag to be changed on inline directories */
if (S_ISDIR(inode->i_mode)) {
flags &= ~EXT4_INLINE_DATA_FL;
oldflags &= ~EXT4_INLINE_DATA_FL;
}
if (flags & EXT4_DAX_FL) {
if ((oldflags & EXT4_DAX_MUT_EXCL) ||
ext4_test_inode_state(inode,
EXT4_STATE_VERITY_IN_PROGRESS)) {
return false;
}
}
if ((flags & EXT4_DAX_MUT_EXCL) && (oldflags & EXT4_DAX_FL))
return false;
return true;
}
static int ext4_ioctl_setflags(struct inode *inode,
unsigned int flags)
{
struct ext4_inode_info *ei = EXT4_I(inode);
handle_t *handle = NULL;
int err = -EPERM, migrate = 0;
struct ext4_iloc iloc;
unsigned int oldflags, mask, i;
struct super_block *sb = inode->i_sb;
/* Is it quota file? Do not allow user to mess with it */
if (ext4_is_quota_file(inode))
goto flags_out;
oldflags = ei->i_flags;
/*
* The JOURNAL_DATA flag can only be changed by
* the relevant capability.
*/
if ((flags ^ oldflags) & (EXT4_JOURNAL_DATA_FL)) {
if (!capable(CAP_SYS_RESOURCE))
goto flags_out;
}
if (!dax_compatible(inode, oldflags, flags)) {
err = -EOPNOTSUPP;
goto flags_out;
}
if ((flags ^ oldflags) & EXT4_EXTENTS_FL)
migrate = 1;
if ((flags ^ oldflags) & EXT4_CASEFOLD_FL) {
if (!ext4_has_feature_casefold(sb)) {
err = -EOPNOTSUPP;
goto flags_out;
}
if (!S_ISDIR(inode->i_mode)) {
err = -ENOTDIR;
goto flags_out;
}
if (!ext4_empty_dir(inode)) {
err = -ENOTEMPTY;
goto flags_out;
}
}
/*
* Wait for all pending directio and then flush all the dirty pages
* for this file. The flush marks all the pages readonly, so any
* subsequent attempt to write to the file (particularly mmap pages)
* will come through the filesystem and fail.
*/
if (S_ISREG(inode->i_mode) && !IS_IMMUTABLE(inode) &&
(flags & EXT4_IMMUTABLE_FL)) {
inode_dio_wait(inode);
err = filemap_write_and_wait(inode->i_mapping);
if (err)
goto flags_out;
}
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto flags_out;
}
if (IS_SYNC(inode))
ext4_handle_sync(handle);
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto flags_err;
ext4_dax_dontcache(inode, flags);
for (i = 0, mask = 1; i < 32; i++, mask <<= 1) {
if (!(mask & EXT4_FL_USER_MODIFIABLE))
continue;
/* These flags get special treatment later */
if (mask == EXT4_JOURNAL_DATA_FL || mask == EXT4_EXTENTS_FL)
continue;
if (mask & flags)
ext4_set_inode_flag(inode, i);
else
ext4_clear_inode_flag(inode, i);
}
ext4_set_inode_flags(inode, false);
inode_set_ctime_current(inode);
inode_inc_iversion(inode);
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
flags_err:
ext4_journal_stop(handle);
if (err)
goto flags_out;
if ((flags ^ oldflags) & (EXT4_JOURNAL_DATA_FL)) {
/*
* Changes to the journaling mode can cause unsafe changes to
* S_DAX if the inode is DAX
*/
if (IS_DAX(inode)) {
err = -EBUSY;
goto flags_out;
}
err = ext4_change_inode_journal_flag(inode,
flags & EXT4_JOURNAL_DATA_FL);
if (err)
goto flags_out;
}
if (migrate) {
if (flags & EXT4_EXTENTS_FL)
err = ext4_ext_migrate(inode);
else
err = ext4_ind_migrate(inode);
}
flags_out:
return err;
}
#ifdef CONFIG_QUOTA
static int ext4_ioctl_setproject(struct inode *inode, __u32 projid)
{
struct super_block *sb = inode->i_sb;
struct ext4_inode_info *ei = EXT4_I(inode);
int err, rc;
handle_t *handle;
kprojid_t kprojid;
struct ext4_iloc iloc;
struct ext4_inode *raw_inode;
struct dquot *transfer_to[MAXQUOTAS] = { };
if (!ext4_has_feature_project(sb)) {
if (projid != EXT4_DEF_PROJID)
return -EOPNOTSUPP;
else
return 0;
}
if (EXT4_INODE_SIZE(sb) <= EXT4_GOOD_OLD_INODE_SIZE)
return -EOPNOTSUPP;
kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
if (projid_eq(kprojid, EXT4_I(inode)->i_projid))
return 0;
err = -EPERM;
/* Is it quota file? Do not allow user to mess with it */
if (ext4_is_quota_file(inode))
return err;
err = dquot_initialize(inode);
if (err)
return err;
err = ext4_get_inode_loc(inode, &iloc);
if (err)
return err;
raw_inode = ext4_raw_inode(&iloc);
if (!EXT4_FITS_IN_INODE(raw_inode, ei, i_projid)) {
err = ext4_expand_extra_isize(inode,
EXT4_SB(sb)->s_want_extra_isize,
&iloc);
if (err)
return err;
} else {
brelse(iloc.bh);
}
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(sb) +
EXT4_QUOTA_DEL_BLOCKS(sb) + 3);
if (IS_ERR(handle))
return PTR_ERR(handle);
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_stop;
transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
if (!IS_ERR(transfer_to[PRJQUOTA])) {
/* __dquot_transfer() calls back ext4_get_inode_usage() which
* counts xattr inode references.
*/
down_read(&EXT4_I(inode)->xattr_sem);
err = __dquot_transfer(inode, transfer_to);
up_read(&EXT4_I(inode)->xattr_sem);
dqput(transfer_to[PRJQUOTA]);
if (err)
goto out_dirty;
}
EXT4_I(inode)->i_projid = kprojid;
inode_set_ctime_current(inode);
inode_inc_iversion(inode);
out_dirty:
rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (!err)
err = rc;
out_stop:
ext4_journal_stop(handle);
return err;
}
#else
static int ext4_ioctl_setproject(struct inode *inode, __u32 projid)
{
if (projid != EXT4_DEF_PROJID)
return -EOPNOTSUPP;
return 0;
}
#endif
int ext4_force_shutdown(struct super_block *sb, u32 flags)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int ret;
if (flags > EXT4_GOING_FLAGS_NOLOGFLUSH)
return -EINVAL;
if (ext4_forced_shutdown(sb))
return 0;
ext4_msg(sb, KERN_ALERT, "shut down requested (%d)", flags);
trace_ext4_shutdown(sb, flags);
switch (flags) {
case EXT4_GOING_FLAGS_DEFAULT:
ret = freeze_bdev(sb->s_bdev);
if (ret)
return ret;
set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags);
thaw_bdev(sb->s_bdev);
break;
case EXT4_GOING_FLAGS_LOGFLUSH:
set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags);
if (sbi->s_journal && !is_journal_aborted(sbi->s_journal)) {
(void) ext4_force_commit(sb);
jbd2_journal_abort(sbi->s_journal, -ESHUTDOWN);
}
break;
case EXT4_GOING_FLAGS_NOLOGFLUSH:
set_bit(EXT4_FLAGS_SHUTDOWN, &sbi->s_ext4_flags);
if (sbi->s_journal && !is_journal_aborted(sbi->s_journal))
jbd2_journal_abort(sbi->s_journal, -ESHUTDOWN);
break;
default:
return -EINVAL;
}
clear_opt(sb, DISCARD);
return 0;
}
static int ext4_ioctl_shutdown(struct super_block *sb, unsigned long arg)
{
u32 flags;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(flags, (__u32 __user *)arg))
return -EFAULT;
return ext4_force_shutdown(sb, flags);
}
struct getfsmap_info {
struct super_block *gi_sb;
struct fsmap_head __user *gi_data;
unsigned int gi_idx;
__u32 gi_last_flags;
};
static int ext4_getfsmap_format(struct ext4_fsmap *xfm, void *priv)
{
struct getfsmap_info *info = priv;
struct fsmap fm;
trace_ext4_getfsmap_mapping(info->gi_sb, xfm);
info->gi_last_flags = xfm->fmr_flags;
ext4_fsmap_from_internal(info->gi_sb, &fm, xfm);
if (copy_to_user(&info->gi_data->fmh_recs[info->gi_idx++], &fm,
sizeof(struct fsmap)))
return -EFAULT;
return 0;
}
static int ext4_ioc_getfsmap(struct super_block *sb,
struct fsmap_head __user *arg)
{
struct getfsmap_info info = { NULL };
struct ext4_fsmap_head xhead = {0};
struct fsmap_head head;
bool aborted = false;
int error;
if (copy_from_user(&head, arg, sizeof(struct fsmap_head)))
return -EFAULT;
if (memchr_inv(head.fmh_reserved, 0, sizeof(head.fmh_reserved)) ||
memchr_inv(head.fmh_keys[0].fmr_reserved, 0,
sizeof(head.fmh_keys[0].fmr_reserved)) ||
memchr_inv(head.fmh_keys[1].fmr_reserved, 0,
sizeof(head.fmh_keys[1].fmr_reserved)))
return -EINVAL;
/*
* ext4 doesn't report file extents at all, so the only valid
* file offsets are the magic ones (all zeroes or all ones).
*/
if (head.fmh_keys[0].fmr_offset ||
(head.fmh_keys[1].fmr_offset != 0 &&
head.fmh_keys[1].fmr_offset != -1ULL))
return -EINVAL;
xhead.fmh_iflags = head.fmh_iflags;
xhead.fmh_count = head.fmh_count;
ext4_fsmap_to_internal(sb, &xhead.fmh_keys[0], &head.fmh_keys[0]);
ext4_fsmap_to_internal(sb, &xhead.fmh_keys[1], &head.fmh_keys[1]);
trace_ext4_getfsmap_low_key(sb, &xhead.fmh_keys[0]);
trace_ext4_getfsmap_high_key(sb, &xhead.fmh_keys[1]);
info.gi_sb = sb;
info.gi_data = arg;
error = ext4_getfsmap(sb, &xhead, ext4_getfsmap_format, &info);
if (error == EXT4_QUERY_RANGE_ABORT)
aborted = true;
else if (error)
return error;
/* If we didn't abort, set the "last" flag in the last fmx */
if (!aborted && info.gi_idx) {
info.gi_last_flags |= FMR_OF_LAST;
if (copy_to_user(&info.gi_data->fmh_recs[info.gi_idx - 1].fmr_flags,
&info.gi_last_flags,
sizeof(info.gi_last_flags)))
return -EFAULT;
}
/* copy back header */
head.fmh_entries = xhead.fmh_entries;
head.fmh_oflags = xhead.fmh_oflags;
if (copy_to_user(arg, &head, sizeof(struct fsmap_head)))
return -EFAULT;
return 0;
}
static long ext4_ioctl_group_add(struct file *file,
struct ext4_new_group_data *input)
{
struct super_block *sb = file_inode(file)->i_sb;
int err, err2=0;
err = ext4_resize_begin(sb);
if (err)
return err;
if (ext4_has_feature_bigalloc(sb)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not supported with bigalloc");
err = -EOPNOTSUPP;
goto group_add_out;
}
err = mnt_want_write_file(file);
if (err)
goto group_add_out;
err = ext4_group_add(sb, input);
if (EXT4_SB(sb)->s_journal) {
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal, 0);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write_file(file);
if (!err && ext4_has_group_desc_csum(sb) &&
test_opt(sb, INIT_INODE_TABLE))
err = ext4_register_li_request(sb, input->group);
group_add_out:
err2 = ext4_resize_end(sb, false);
if (err == 0)
err = err2;
return err;
}
int ext4_fileattr_get(struct dentry *dentry, struct fileattr *fa)
{
struct inode *inode = d_inode(dentry);
struct ext4_inode_info *ei = EXT4_I(inode);
u32 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
if (S_ISREG(inode->i_mode))
flags &= ~FS_PROJINHERIT_FL;
fileattr_fill_flags(fa, flags);
if (ext4_has_feature_project(inode->i_sb))
fa->fsx_projid = from_kprojid(&init_user_ns, ei->i_projid);
return 0;
}
int ext4_fileattr_set(struct mnt_idmap *idmap,
struct dentry *dentry, struct fileattr *fa)
{
struct inode *inode = d_inode(dentry);
u32 flags = fa->flags;
int err = -EOPNOTSUPP;
if (flags & ~EXT4_FL_USER_VISIBLE)
goto out;
/*
* chattr(1) grabs flags via GETFLAGS, modifies the result and
* passes that to SETFLAGS. So we cannot easily make SETFLAGS
* more restrictive than just silently masking off visible but
* not settable flags as we always did.
*/
flags &= EXT4_FL_USER_MODIFIABLE;
if (ext4_mask_flags(inode->i_mode, flags) != flags)
goto out;
err = ext4_ioctl_check_immutable(inode, fa->fsx_projid, flags);
if (err)
goto out;
err = ext4_ioctl_setflags(inode, flags);
if (err)
goto out;
err = ext4_ioctl_setproject(inode, fa->fsx_projid);
out:
return err;
}
/* So that the fiemap access checks can't overflow on 32 bit machines. */
#define FIEMAP_MAX_EXTENTS (UINT_MAX / sizeof(struct fiemap_extent))
static int ext4_ioctl_get_es_cache(struct file *filp, unsigned long arg)
{
struct fiemap fiemap;
struct fiemap __user *ufiemap = (struct fiemap __user *) arg;
struct fiemap_extent_info fieinfo = { 0, };
struct inode *inode = file_inode(filp);
int error;
if (copy_from_user(&fiemap, ufiemap, sizeof(fiemap)))
return -EFAULT;
if (fiemap.fm_extent_count > FIEMAP_MAX_EXTENTS)
return -EINVAL;
fieinfo.fi_flags = fiemap.fm_flags;
fieinfo.fi_extents_max = fiemap.fm_extent_count;
fieinfo.fi_extents_start = ufiemap->fm_extents;
error = ext4_get_es_cache(inode, &fieinfo, fiemap.fm_start,
fiemap.fm_length);
fiemap.fm_flags = fieinfo.fi_flags;
fiemap.fm_mapped_extents = fieinfo.fi_extents_mapped;
if (copy_to_user(ufiemap, &fiemap, sizeof(fiemap)))
error = -EFAULT;
return error;
}
static int ext4_ioctl_checkpoint(struct file *filp, unsigned long arg)
{
int err = 0;
__u32 flags = 0;
unsigned int flush_flags = 0;
struct super_block *sb = file_inode(filp)->i_sb;
if (copy_from_user(&flags, (__u32 __user *)arg,
sizeof(__u32)))
return -EFAULT;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
/* check for invalid bits set */
if ((flags & ~EXT4_IOC_CHECKPOINT_FLAG_VALID) ||
((flags & JBD2_JOURNAL_FLUSH_DISCARD) &&
(flags & JBD2_JOURNAL_FLUSH_ZEROOUT)))
return -EINVAL;
if (!EXT4_SB(sb)->s_journal)
return -ENODEV;
if ((flags & JBD2_JOURNAL_FLUSH_DISCARD) &&
!bdev_max_discard_sectors(EXT4_SB(sb)->s_journal->j_dev))
return -EOPNOTSUPP;
if (flags & EXT4_IOC_CHECKPOINT_FLAG_DRY_RUN)
return 0;
if (flags & EXT4_IOC_CHECKPOINT_FLAG_DISCARD)
flush_flags |= JBD2_JOURNAL_FLUSH_DISCARD;
if (flags & EXT4_IOC_CHECKPOINT_FLAG_ZEROOUT) {
flush_flags |= JBD2_JOURNAL_FLUSH_ZEROOUT;
pr_info_ratelimited("warning: checkpointing journal with EXT4_IOC_CHECKPOINT_FLAG_ZEROOUT can be slow");
}
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal, flush_flags);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
return err;
}
static int ext4_ioctl_setlabel(struct file *filp, const char __user *user_label)
{
size_t len;
int ret = 0;
char new_label[EXT4_LABEL_MAX + 1];
struct super_block *sb = file_inode(filp)->i_sb;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
/*
* Copy the maximum length allowed for ext4 label with one more to
* find the required terminating null byte in order to test the
* label length. The on disk label doesn't need to be null terminated.
*/
if (copy_from_user(new_label, user_label, EXT4_LABEL_MAX + 1))
return -EFAULT;
len = strnlen(new_label, EXT4_LABEL_MAX + 1);
if (len > EXT4_LABEL_MAX)
return -EINVAL;
/*
* Clear the buffer after the new label
*/
memset(new_label + len, 0, EXT4_LABEL_MAX - len);
ret = mnt_want_write_file(filp);
if (ret)
return ret;
ret = ext4_update_superblocks_fn(sb, ext4_sb_setlabel, new_label);
mnt_drop_write_file(filp);
return ret;
}
static int ext4_ioctl_getlabel(struct ext4_sb_info *sbi, char __user *user_label)
{
char label[EXT4_LABEL_MAX + 1];
/*
* EXT4_LABEL_MAX must always be smaller than FSLABEL_MAX because
* FSLABEL_MAX must include terminating null byte, while s_volume_name
* does not have to.
*/
BUILD_BUG_ON(EXT4_LABEL_MAX >= FSLABEL_MAX);
memset(label, 0, sizeof(label));
lock_buffer(sbi->s_sbh);
strncpy(label, sbi->s_es->s_volume_name, EXT4_LABEL_MAX);
unlock_buffer(sbi->s_sbh);
if (copy_to_user(user_label, label, sizeof(label)))
return -EFAULT;
return 0;
}
static int ext4_ioctl_getuuid(struct ext4_sb_info *sbi,
struct fsuuid __user *ufsuuid)
{
struct fsuuid fsuuid;
__u8 uuid[UUID_SIZE];
if (copy_from_user(&fsuuid, ufsuuid, sizeof(fsuuid)))
return -EFAULT;
if (fsuuid.fsu_len == 0) {
fsuuid.fsu_len = UUID_SIZE;
if (copy_to_user(&ufsuuid->fsu_len, &fsuuid.fsu_len,
sizeof(fsuuid.fsu_len)))
return -EFAULT;
return 0;
}
if (fsuuid.fsu_len < UUID_SIZE || fsuuid.fsu_flags != 0)
return -EINVAL;
lock_buffer(sbi->s_sbh);
memcpy(uuid, sbi->s_es->s_uuid, UUID_SIZE);
unlock_buffer(sbi->s_sbh);
fsuuid.fsu_len = UUID_SIZE;
if (copy_to_user(ufsuuid, &fsuuid, sizeof(fsuuid)) ||
copy_to_user(&ufsuuid->fsu_uuid[0], uuid, UUID_SIZE))
return -EFAULT;
return 0;
}
static int ext4_ioctl_setuuid(struct file *filp,
const struct fsuuid __user *ufsuuid)
{
int ret = 0;
struct super_block *sb = file_inode(filp)->i_sb;
struct fsuuid fsuuid;
__u8 uuid[UUID_SIZE];
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
/*
* If any checksums (group descriptors or metadata) are being used
* then the checksum seed feature is required to change the UUID.
*/
if (((ext4_has_feature_gdt_csum(sb) || ext4_has_metadata_csum(sb))
&& !ext4_has_feature_csum_seed(sb))
|| ext4_has_feature_stable_inodes(sb))
return -EOPNOTSUPP;
if (copy_from_user(&fsuuid, ufsuuid, sizeof(fsuuid)))
return -EFAULT;
if (fsuuid.fsu_len != UUID_SIZE || fsuuid.fsu_flags != 0)
return -EINVAL;
if (copy_from_user(uuid, &ufsuuid->fsu_uuid[0], UUID_SIZE))
return -EFAULT;
ret = mnt_want_write_file(filp);
if (ret)
return ret;
ret = ext4_update_superblocks_fn(sb, ext4_sb_setuuid, &uuid);
mnt_drop_write_file(filp);
return ret;
}
static long __ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = file_inode(filp);
struct super_block *sb = inode->i_sb;
struct mnt_idmap *idmap = file_mnt_idmap(filp);
ext4_debug("cmd = %u, arg = %lu\n", cmd, arg);
switch (cmd) {
case FS_IOC_GETFSMAP:
return ext4_ioc_getfsmap(sb, (void __user *)arg);
case EXT4_IOC_GETVERSION:
case EXT4_IOC_GETVERSION_OLD:
return put_user(inode->i_generation, (int __user *) arg);
case EXT4_IOC_SETVERSION:
case EXT4_IOC_SETVERSION_OLD: {
handle_t *handle;
struct ext4_iloc iloc;
__u32 generation;
int err;
if (!inode_owner_or_capable(idmap, inode))
return -EPERM;
if (ext4_has_metadata_csum(inode->i_sb)) {
ext4_warning(sb, "Setting inode version is not "
"supported with metadata_csum enabled.");
return -ENOTTY;
}
err = mnt_want_write_file(filp);
if (err)
return err;
if (get_user(generation, (int __user *) arg)) {
err = -EFAULT;
goto setversion_out;
}
inode_lock(inode);
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto unlock_out;
}
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err == 0) {
inode_set_ctime_current(inode);
inode_inc_iversion(inode);
inode->i_generation = generation;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
}
ext4_journal_stop(handle);
unlock_out:
inode_unlock(inode);
setversion_out:
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_GROUP_EXTEND: {
ext4_fsblk_t n_blocks_count;
int err, err2=0;
err = ext4_resize_begin(sb);
if (err)
return err;
if (get_user(n_blocks_count, (__u32 __user *)arg)) {
err = -EFAULT;
goto group_extend_out;
}
if (ext4_has_feature_bigalloc(sb)) {
ext4_msg(sb, KERN_ERR,
"Online resizing not supported with bigalloc");
err = -EOPNOTSUPP;
goto group_extend_out;
}
err = mnt_want_write_file(filp);
if (err)
goto group_extend_out;
err = ext4_group_extend(sb, EXT4_SB(sb)->s_es, n_blocks_count);
if (EXT4_SB(sb)->s_journal) {
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal, 0);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write_file(filp);
group_extend_out:
err2 = ext4_resize_end(sb, false);
if (err == 0)
err = err2;
return err;
}
case EXT4_IOC_MOVE_EXT: {
struct move_extent me;
struct fd donor;
int err;
if (!(filp->f_mode & FMODE_READ) ||
!(filp->f_mode & FMODE_WRITE))
return -EBADF;
if (copy_from_user(&me,
(struct move_extent __user *)arg, sizeof(me)))
return -EFAULT;
me.moved_len = 0;
donor = fdget(me.donor_fd);
if (!donor.file)
return -EBADF;
if (!(donor.file->f_mode & FMODE_WRITE)) {
err = -EBADF;
goto mext_out;
}
if (ext4_has_feature_bigalloc(sb)) {
ext4_msg(sb, KERN_ERR,
"Online defrag not supported with bigalloc");
err = -EOPNOTSUPP;
goto mext_out;
} else if (IS_DAX(inode)) {
ext4_msg(sb, KERN_ERR,
"Online defrag not supported with DAX");
err = -EOPNOTSUPP;
goto mext_out;
}
err = mnt_want_write_file(filp);
if (err)
goto mext_out;
err = ext4_move_extents(filp, donor.file, me.orig_start,
me.donor_start, me.len, &me.moved_len);
mnt_drop_write_file(filp);
if (copy_to_user((struct move_extent __user *)arg,
&me, sizeof(me)))
err = -EFAULT;
mext_out:
fdput(donor);
return err;
}
case EXT4_IOC_GROUP_ADD: {
struct ext4_new_group_data input;
if (copy_from_user(&input, (struct ext4_new_group_input __user *)arg,
sizeof(input)))
return -EFAULT;
return ext4_ioctl_group_add(filp, &input);
}
case EXT4_IOC_MIGRATE:
{
int err;
if (!inode_owner_or_capable(idmap, inode))
return -EACCES;
err = mnt_want_write_file(filp);
if (err)
return err;
/*
* inode_mutex prevent write and truncate on the file.
* Read still goes through. We take i_data_sem in
* ext4_ext_swap_inode_data before we switch the
* inode format to prevent read.
*/
inode_lock((inode));
err = ext4_ext_migrate(inode);
inode_unlock((inode));
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_ALLOC_DA_BLKS:
{
int err;
if (!inode_owner_or_capable(idmap, inode))
return -EACCES;
err = mnt_want_write_file(filp);
if (err)
return err;
err = ext4_alloc_da_blocks(inode);
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_SWAP_BOOT:
{
int err;
if (!(filp->f_mode & FMODE_WRITE))
return -EBADF;
err = mnt_want_write_file(filp);
if (err)
return err;
err = swap_inode_boot_loader(sb, idmap, inode);
mnt_drop_write_file(filp);
return err;
}
case EXT4_IOC_RESIZE_FS: {
ext4_fsblk_t n_blocks_count;
int err = 0, err2 = 0;
ext4_group_t o_group = EXT4_SB(sb)->s_groups_count;
if (copy_from_user(&n_blocks_count, (__u64 __user *)arg,
sizeof(__u64))) {
return -EFAULT;
}
err = ext4_resize_begin(sb);
if (err)
return err;
err = mnt_want_write_file(filp);
if (err)
goto resizefs_out;
err = ext4_resize_fs(sb, n_blocks_count);
if (EXT4_SB(sb)->s_journal) {
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_RESIZE, NULL);
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err2 = jbd2_journal_flush(EXT4_SB(sb)->s_journal, 0);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
}
if (err == 0)
err = err2;
mnt_drop_write_file(filp);
if (!err && (o_group < EXT4_SB(sb)->s_groups_count) &&
ext4_has_group_desc_csum(sb) &&
test_opt(sb, INIT_INODE_TABLE))
err = ext4_register_li_request(sb, o_group);
resizefs_out:
err2 = ext4_resize_end(sb, true);
if (err == 0)
err = err2;
return err;
}
case FITRIM:
{
struct fstrim_range range;
int ret = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!bdev_max_discard_sectors(sb->s_bdev))
return -EOPNOTSUPP;
/*
* We haven't replayed the journal, so we cannot use our
* block-bitmap-guided storage zapping commands.
*/
if (test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb))
return -EROFS;
if (copy_from_user(&range, (struct fstrim_range __user *)arg,
sizeof(range)))
return -EFAULT;
ret = ext4_trim_fs(sb, &range);
if (ret < 0)
return ret;
if (copy_to_user((struct fstrim_range __user *)arg, &range,
sizeof(range)))
return -EFAULT;
return 0;
}
case EXT4_IOC_PRECACHE_EXTENTS:
return ext4_ext_precache(inode);
case FS_IOC_SET_ENCRYPTION_POLICY:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_set_policy(filp, (const void __user *)arg);
case FS_IOC_GET_ENCRYPTION_PWSALT:
return ext4_ioctl_get_encryption_pwsalt(filp, (void __user *)arg);
case FS_IOC_GET_ENCRYPTION_POLICY:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_get_policy(filp, (void __user *)arg);
case FS_IOC_GET_ENCRYPTION_POLICY_EX:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_get_policy_ex(filp, (void __user *)arg);
case FS_IOC_ADD_ENCRYPTION_KEY:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_add_key(filp, (void __user *)arg);
case FS_IOC_REMOVE_ENCRYPTION_KEY:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_remove_key(filp, (void __user *)arg);
case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_remove_key_all_users(filp,
(void __user *)arg);
case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_get_key_status(filp, (void __user *)arg);
case FS_IOC_GET_ENCRYPTION_NONCE:
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
return fscrypt_ioctl_get_nonce(filp, (void __user *)arg);
case EXT4_IOC_CLEAR_ES_CACHE:
{
if (!inode_owner_or_capable(idmap, inode))
return -EACCES;
ext4_clear_inode_es(inode);
return 0;
}
case EXT4_IOC_GETSTATE:
{
__u32 state = 0;
if (ext4_test_inode_state(inode, EXT4_STATE_EXT_PRECACHED))
state |= EXT4_STATE_FLAG_EXT_PRECACHED;
if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
state |= EXT4_STATE_FLAG_NEW;
if (ext4_test_inode_state(inode, EXT4_STATE_NEWENTRY))
state |= EXT4_STATE_FLAG_NEWENTRY;
if (ext4_test_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE))
state |= EXT4_STATE_FLAG_DA_ALLOC_CLOSE;
return put_user(state, (__u32 __user *) arg);
}
case EXT4_IOC_GET_ES_CACHE:
return ext4_ioctl_get_es_cache(filp, arg);
case EXT4_IOC_SHUTDOWN:
return ext4_ioctl_shutdown(sb, arg);
case FS_IOC_ENABLE_VERITY:
if (!ext4_has_feature_verity(sb))
return -EOPNOTSUPP;
return fsverity_ioctl_enable(filp, (const void __user *)arg);
case FS_IOC_MEASURE_VERITY:
if (!ext4_has_feature_verity(sb))
return -EOPNOTSUPP;
return fsverity_ioctl_measure(filp, (void __user *)arg);
case FS_IOC_READ_VERITY_METADATA:
if (!ext4_has_feature_verity(sb))
return -EOPNOTSUPP;
return fsverity_ioctl_read_metadata(filp,
(const void __user *)arg);
case EXT4_IOC_CHECKPOINT:
return ext4_ioctl_checkpoint(filp, arg);
case FS_IOC_GETFSLABEL:
return ext4_ioctl_getlabel(EXT4_SB(sb), (void __user *)arg);
case FS_IOC_SETFSLABEL:
return ext4_ioctl_setlabel(filp,
(const void __user *)arg);
case EXT4_IOC_GETFSUUID:
return ext4_ioctl_getuuid(EXT4_SB(sb), (void __user *)arg);
case EXT4_IOC_SETFSUUID:
return ext4_ioctl_setuuid(filp, (const void __user *)arg);
default:
return -ENOTTY;
}
}
long ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
return __ext4_ioctl(filp, cmd, arg);
}
#ifdef CONFIG_COMPAT
long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
/* These are just misnamed, they actually get/put from/to user an int */
switch (cmd) {
case EXT4_IOC32_GETVERSION:
cmd = EXT4_IOC_GETVERSION;
break;
case EXT4_IOC32_SETVERSION:
cmd = EXT4_IOC_SETVERSION;
break;
case EXT4_IOC32_GROUP_EXTEND:
cmd = EXT4_IOC_GROUP_EXTEND;
break;
case EXT4_IOC32_GETVERSION_OLD:
cmd = EXT4_IOC_GETVERSION_OLD;
break;
case EXT4_IOC32_SETVERSION_OLD:
cmd = EXT4_IOC_SETVERSION_OLD;
break;
case EXT4_IOC32_GETRSVSZ:
cmd = EXT4_IOC_GETRSVSZ;
break;
case EXT4_IOC32_SETRSVSZ:
cmd = EXT4_IOC_SETRSVSZ;
break;
case EXT4_IOC32_GROUP_ADD: {
struct compat_ext4_new_group_input __user *uinput;
struct ext4_new_group_data input;
int err;
uinput = compat_ptr(arg);
err = get_user(input.group, &uinput->group);
err |= get_user(input.block_bitmap, &uinput->block_bitmap);
err |= get_user(input.inode_bitmap, &uinput->inode_bitmap);
err |= get_user(input.inode_table, &uinput->inode_table);
err |= get_user(input.blocks_count, &uinput->blocks_count);
err |= get_user(input.reserved_blocks,
&uinput->reserved_blocks);
if (err)
return -EFAULT;
return ext4_ioctl_group_add(file, &input);
}
case EXT4_IOC_MOVE_EXT:
case EXT4_IOC_RESIZE_FS:
case FITRIM:
case EXT4_IOC_PRECACHE_EXTENTS:
case FS_IOC_SET_ENCRYPTION_POLICY:
case FS_IOC_GET_ENCRYPTION_PWSALT:
case FS_IOC_GET_ENCRYPTION_POLICY:
case FS_IOC_GET_ENCRYPTION_POLICY_EX:
case FS_IOC_ADD_ENCRYPTION_KEY:
case FS_IOC_REMOVE_ENCRYPTION_KEY:
case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
case FS_IOC_GET_ENCRYPTION_NONCE:
case EXT4_IOC_SHUTDOWN:
case FS_IOC_GETFSMAP:
case FS_IOC_ENABLE_VERITY:
case FS_IOC_MEASURE_VERITY:
case FS_IOC_READ_VERITY_METADATA:
case EXT4_IOC_CLEAR_ES_CACHE:
case EXT4_IOC_GETSTATE:
case EXT4_IOC_GET_ES_CACHE:
case EXT4_IOC_CHECKPOINT:
case FS_IOC_GETFSLABEL:
case FS_IOC_SETFSLABEL:
case EXT4_IOC_GETFSUUID:
case EXT4_IOC_SETFSUUID:
break;
default:
return -ENOIOCTLCMD;
}
return ext4_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
}
#endif
static void set_overhead(struct ext4_super_block *es, const void *arg)
{
es->s_overhead_clusters = cpu_to_le32(*((unsigned long *) arg));
}
int ext4_update_overhead(struct super_block *sb, bool force)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_rdonly(sb))
return 0;
if (!force &&
(sbi->s_overhead == 0 ||
sbi->s_overhead == le32_to_cpu(sbi->s_es->s_overhead_clusters)))
return 0;
return ext4_update_superblocks_fn(sb, set_overhead, &sbi->s_overhead);
}
| linux-master | fs/ext4/ioctl.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/xattr_security.c
* Handler for storing security labels as extended attributes.
*/
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/security.h>
#include <linux/slab.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
static int
ext4_xattr_security_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_SECURITY,
name, buffer, size);
}
static int
ext4_xattr_security_set(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)
{
return ext4_xattr_set(inode, EXT4_XATTR_INDEX_SECURITY,
name, value, size, flags);
}
static int
ext4_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *fs_info)
{
const struct xattr *xattr;
handle_t *handle = fs_info;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
err = ext4_xattr_set_handle(handle, inode,
EXT4_XATTR_INDEX_SECURITY,
xattr->name, xattr->value,
xattr->value_len, XATTR_CREATE);
if (err < 0)
break;
}
return err;
}
int
ext4_init_security(handle_t *handle, struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
return security_inode_init_security(inode, dir, qstr,
&ext4_initxattrs, handle);
}
const struct xattr_handler ext4_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.get = ext4_xattr_security_get,
.set = ext4_xattr_security_set,
};
| linux-master | fs/ext4/xattr_security.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/namei.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
* Directory entry file type support and forward compatibility hooks
* for B-tree directories by Theodore Ts'o ([email protected]), 1998
* Hash Tree Directory indexing (c)
* Daniel Phillips, 2001
* Hash Tree Directory indexing porting
* Christopher Li, 2002
* Hash Tree Directory indexing cleanup
* Theodore Ts'o, 2002
*/
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/time.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/bio.h>
#include <linux/iversion.h>
#include <linux/unicode.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include <trace/events/ext4.h>
/*
* define how far ahead to read directories while searching them.
*/
#define NAMEI_RA_CHUNKS 2
#define NAMEI_RA_BLOCKS 4
#define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
static struct buffer_head *ext4_append(handle_t *handle,
struct inode *inode,
ext4_lblk_t *block)
{
struct ext4_map_blocks map;
struct buffer_head *bh;
int err;
if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
((inode->i_size >> 10) >=
EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
return ERR_PTR(-ENOSPC);
*block = inode->i_size >> inode->i_sb->s_blocksize_bits;
map.m_lblk = *block;
map.m_len = 1;
/*
* We're appending new directory block. Make sure the block is not
* allocated yet, otherwise we will end up corrupting the
* directory.
*/
err = ext4_map_blocks(NULL, inode, &map, 0);
if (err < 0)
return ERR_PTR(err);
if (err) {
EXT4_ERROR_INODE(inode, "Logical block already allocated");
return ERR_PTR(-EFSCORRUPTED);
}
bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
if (IS_ERR(bh))
return bh;
inode->i_size += inode->i_sb->s_blocksize;
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_mark_inode_dirty(handle, inode);
if (err)
goto out;
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
EXT4_JTR_NONE);
if (err)
goto out;
return bh;
out:
brelse(bh);
ext4_std_error(inode->i_sb, err);
return ERR_PTR(err);
}
static int ext4_dx_csum_verify(struct inode *inode,
struct ext4_dir_entry *dirent);
/*
* Hints to ext4_read_dirblock regarding whether we expect a directory
* block being read to be an index block, or a block containing
* directory entries (and if the latter, whether it was found via a
* logical block in an htree index block). This is used to control
* what sort of sanity checkinig ext4_read_dirblock() will do on the
* directory block read from the storage device. EITHER will means
* the caller doesn't know what kind of directory block will be read,
* so no specific verification will be done.
*/
typedef enum {
EITHER, INDEX, DIRENT, DIRENT_HTREE
} dirblock_type_t;
#define ext4_read_dirblock(inode, block, type) \
__ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
ext4_lblk_t block,
dirblock_type_t type,
const char *func,
unsigned int line)
{
struct buffer_head *bh;
struct ext4_dir_entry *dirent;
int is_dx_block = 0;
if (block >= inode->i_size >> inode->i_blkbits) {
ext4_error_inode(inode, func, line, block,
"Attempting to read directory block (%u) that is past i_size (%llu)",
block, inode->i_size);
return ERR_PTR(-EFSCORRUPTED);
}
if (ext4_simulate_fail(inode->i_sb, EXT4_SIM_DIRBLOCK_EIO))
bh = ERR_PTR(-EIO);
else
bh = ext4_bread(NULL, inode, block, 0);
if (IS_ERR(bh)) {
__ext4_warning(inode->i_sb, func, line,
"inode #%lu: lblock %lu: comm %s: "
"error %ld reading directory block",
inode->i_ino, (unsigned long)block,
current->comm, PTR_ERR(bh));
return bh;
}
if (!bh && (type == INDEX || type == DIRENT_HTREE)) {
ext4_error_inode(inode, func, line, block,
"Directory hole found for htree %s block",
(type == INDEX) ? "index" : "leaf");
return ERR_PTR(-EFSCORRUPTED);
}
if (!bh)
return NULL;
dirent = (struct ext4_dir_entry *) bh->b_data;
/* Determine whether or not we have an index block */
if (is_dx(inode)) {
if (block == 0)
is_dx_block = 1;
else if (ext4_rec_len_from_disk(dirent->rec_len,
inode->i_sb->s_blocksize) ==
inode->i_sb->s_blocksize)
is_dx_block = 1;
}
if (!is_dx_block && type == INDEX) {
ext4_error_inode(inode, func, line, block,
"directory leaf block found instead of index block");
brelse(bh);
return ERR_PTR(-EFSCORRUPTED);
}
if (!ext4_has_metadata_csum(inode->i_sb) ||
buffer_verified(bh))
return bh;
/*
* An empty leaf block can get mistaken for a index block; for
* this reason, we can only check the index checksum when the
* caller is sure it should be an index block.
*/
if (is_dx_block && type == INDEX) {
if (ext4_dx_csum_verify(inode, dirent) &&
!ext4_simulate_fail(inode->i_sb, EXT4_SIM_DIRBLOCK_CRC))
set_buffer_verified(bh);
else {
ext4_error_inode_err(inode, func, line, block,
EFSBADCRC,
"Directory index failed checksum");
brelse(bh);
return ERR_PTR(-EFSBADCRC);
}
}
if (!is_dx_block) {
if (ext4_dirblock_csum_verify(inode, bh) &&
!ext4_simulate_fail(inode->i_sb, EXT4_SIM_DIRBLOCK_CRC))
set_buffer_verified(bh);
else {
ext4_error_inode_err(inode, func, line, block,
EFSBADCRC,
"Directory block failed checksum");
brelse(bh);
return ERR_PTR(-EFSBADCRC);
}
}
return bh;
}
#ifdef DX_DEBUG
#define dxtrace(command) command
#else
#define dxtrace(command)
#endif
struct fake_dirent
{
__le32 inode;
__le16 rec_len;
u8 name_len;
u8 file_type;
};
struct dx_countlimit
{
__le16 limit;
__le16 count;
};
struct dx_entry
{
__le32 hash;
__le32 block;
};
/*
* dx_root_info is laid out so that if it should somehow get overlaid by a
* dirent the two low bits of the hash version will be zero. Therefore, the
* hash version mod 4 should never be 0. Sincerely, the paranoia department.
*/
struct dx_root
{
struct fake_dirent dot;
char dot_name[4];
struct fake_dirent dotdot;
char dotdot_name[4];
struct dx_root_info
{
__le32 reserved_zero;
u8 hash_version;
u8 info_length; /* 8 */
u8 indirect_levels;
u8 unused_flags;
}
info;
struct dx_entry entries[];
};
struct dx_node
{
struct fake_dirent fake;
struct dx_entry entries[];
};
struct dx_frame
{
struct buffer_head *bh;
struct dx_entry *entries;
struct dx_entry *at;
};
struct dx_map_entry
{
u32 hash;
u16 offs;
u16 size;
};
/*
* This goes at the end of each htree block.
*/
struct dx_tail {
u32 dt_reserved;
__le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */
};
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
static inline unsigned dx_get_hash(struct dx_entry *entry);
static void dx_set_hash(struct dx_entry *entry, unsigned value);
static unsigned dx_get_count(struct dx_entry *entries);
static unsigned dx_get_limit(struct dx_entry *entries);
static void dx_set_count(struct dx_entry *entries, unsigned value);
static void dx_set_limit(struct dx_entry *entries, unsigned value);
static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
static unsigned dx_node_limit(struct inode *dir);
static struct dx_frame *dx_probe(struct ext4_filename *fname,
struct inode *dir,
struct dx_hash_info *hinfo,
struct dx_frame *frame);
static void dx_release(struct dx_frame *frames);
static int dx_make_map(struct inode *dir, struct buffer_head *bh,
struct dx_hash_info *hinfo,
struct dx_map_entry *map_tail);
static void dx_sort_map(struct dx_map_entry *map, unsigned count);
static struct ext4_dir_entry_2 *dx_move_dirents(struct inode *dir, char *from,
char *to, struct dx_map_entry *offsets,
int count, unsigned int blocksize);
static struct ext4_dir_entry_2 *dx_pack_dirents(struct inode *dir, char *base,
unsigned int blocksize);
static void dx_insert_block(struct dx_frame *frame,
u32 hash, ext4_lblk_t block);
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash);
static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir);
static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
struct inode *dir, struct inode *inode);
/* checksumming functions */
void ext4_initialize_dirent_tail(struct buffer_head *bh,
unsigned int blocksize)
{
struct ext4_dir_entry_tail *t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
memset(t, 0, sizeof(struct ext4_dir_entry_tail));
t->det_rec_len = ext4_rec_len_to_disk(
sizeof(struct ext4_dir_entry_tail), blocksize);
t->det_reserved_ft = EXT4_FT_DIR_CSUM;
}
/* Walk through a dirent block to find a checksum "dirent" at the tail */
static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
struct buffer_head *bh)
{
struct ext4_dir_entry_tail *t;
int blocksize = EXT4_BLOCK_SIZE(inode->i_sb);
#ifdef PARANOID
struct ext4_dir_entry *d, *top;
d = (struct ext4_dir_entry *)bh->b_data;
top = (struct ext4_dir_entry *)(bh->b_data +
(blocksize - sizeof(struct ext4_dir_entry_tail)));
while (d < top && ext4_rec_len_from_disk(d->rec_len, blocksize))
d = (struct ext4_dir_entry *)(((void *)d) +
ext4_rec_len_from_disk(d->rec_len, blocksize));
if (d != top)
return NULL;
t = (struct ext4_dir_entry_tail *)d;
#else
t = EXT4_DIRENT_TAIL(bh->b_data, EXT4_BLOCK_SIZE(inode->i_sb));
#endif
if (t->det_reserved_zero1 ||
(ext4_rec_len_from_disk(t->det_rec_len, blocksize) !=
sizeof(struct ext4_dir_entry_tail)) ||
t->det_reserved_zero2 ||
t->det_reserved_ft != EXT4_FT_DIR_CSUM)
return NULL;
return t;
}
static __le32 ext4_dirblock_csum(struct inode *inode, void *dirent, int size)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum;
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
return cpu_to_le32(csum);
}
#define warn_no_space_for_csum(inode) \
__warn_no_space_for_csum((inode), __func__, __LINE__)
static void __warn_no_space_for_csum(struct inode *inode, const char *func,
unsigned int line)
{
__ext4_warning_inode(inode, func, line,
"No space for directory leaf checksum. Please run e2fsck -D.");
}
int ext4_dirblock_csum_verify(struct inode *inode, struct buffer_head *bh)
{
struct ext4_dir_entry_tail *t;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
t = get_dirent_tail(inode, bh);
if (!t) {
warn_no_space_for_csum(inode);
return 0;
}
if (t->det_checksum != ext4_dirblock_csum(inode, bh->b_data,
(char *)t - bh->b_data))
return 0;
return 1;
}
static void ext4_dirblock_csum_set(struct inode *inode,
struct buffer_head *bh)
{
struct ext4_dir_entry_tail *t;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
t = get_dirent_tail(inode, bh);
if (!t) {
warn_no_space_for_csum(inode);
return;
}
t->det_checksum = ext4_dirblock_csum(inode, bh->b_data,
(char *)t - bh->b_data);
}
int ext4_handle_dirty_dirblock(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dirblock_csum_set(inode, bh);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
struct ext4_dir_entry *dirent,
int *offset)
{
struct ext4_dir_entry *dp;
struct dx_root_info *root;
int count_offset;
int blocksize = EXT4_BLOCK_SIZE(inode->i_sb);
unsigned int rlen = ext4_rec_len_from_disk(dirent->rec_len, blocksize);
if (rlen == blocksize)
count_offset = 8;
else if (rlen == 12) {
dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
if (ext4_rec_len_from_disk(dp->rec_len, blocksize) != blocksize - 12)
return NULL;
root = (struct dx_root_info *)(((void *)dp + 12));
if (root->reserved_zero ||
root->info_length != sizeof(struct dx_root_info))
return NULL;
count_offset = 32;
} else
return NULL;
if (offset)
*offset = count_offset;
return (struct dx_countlimit *)(((void *)dirent) + count_offset);
}
static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
int count_offset, int count, struct dx_tail *t)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_inode_info *ei = EXT4_I(inode);
__u32 csum;
int size;
__u32 dummy_csum = 0;
int offset = offsetof(struct dx_tail, dt_checksum);
size = count_offset + (count * sizeof(struct dx_entry));
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
return cpu_to_le32(csum);
}
static int ext4_dx_csum_verify(struct inode *inode,
struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!ext4_has_metadata_csum(inode->i_sb))
return 1;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return 0;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
warn_no_space_for_csum(inode);
return 0;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
count, t))
return 0;
return 1;
}
static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
{
struct dx_countlimit *c;
struct dx_tail *t;
int count_offset, limit, count;
if (!ext4_has_metadata_csum(inode->i_sb))
return;
c = get_dx_countlimit(inode, dirent, &count_offset);
if (!c) {
EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D.");
return;
}
limit = le16_to_cpu(c->limit);
count = le16_to_cpu(c->count);
if (count_offset + (limit * sizeof(struct dx_entry)) >
EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
warn_no_space_for_csum(inode);
return;
}
t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
}
static inline int ext4_handle_dirty_dx_node(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
return ext4_handle_dirty_metadata(handle, inode, bh);
}
/*
* p is at least 6 bytes before the end of page
*/
static inline struct ext4_dir_entry_2 *
ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
{
return (struct ext4_dir_entry_2 *)((char *)p +
ext4_rec_len_from_disk(p->rec_len, blocksize));
}
/*
* Future: use high four bits of block for coalesce-on-delete flags
* Mask them off for now.
*/
static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
{
return le32_to_cpu(entry->block) & 0x0fffffff;
}
static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
{
entry->block = cpu_to_le32(value);
}
static inline unsigned dx_get_hash(struct dx_entry *entry)
{
return le32_to_cpu(entry->hash);
}
static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
{
entry->hash = cpu_to_le32(value);
}
static inline unsigned dx_get_count(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->count);
}
static inline unsigned dx_get_limit(struct dx_entry *entries)
{
return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
}
static inline void dx_set_count(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
}
static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
{
((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
}
static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
{
unsigned int entry_space = dir->i_sb->s_blocksize -
ext4_dir_rec_len(1, NULL) -
ext4_dir_rec_len(2, NULL) - infosize;
if (ext4_has_metadata_csum(dir->i_sb))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
static inline unsigned dx_node_limit(struct inode *dir)
{
unsigned int entry_space = dir->i_sb->s_blocksize -
ext4_dir_rec_len(0, dir);
if (ext4_has_metadata_csum(dir->i_sb))
entry_space -= sizeof(struct dx_tail);
return entry_space / sizeof(struct dx_entry);
}
/*
* Debug
*/
#ifdef DX_DEBUG
static void dx_show_index(char * label, struct dx_entry *entries)
{
int i, n = dx_get_count (entries);
printk(KERN_DEBUG "%s index", label);
for (i = 0; i < n; i++) {
printk(KERN_CONT " %x->%lu",
i ? dx_get_hash(entries + i) : 0,
(unsigned long)dx_get_block(entries + i));
}
printk(KERN_CONT "\n");
}
struct stats
{
unsigned names;
unsigned space;
unsigned bcount;
};
static struct stats dx_show_leaf(struct inode *dir,
struct dx_hash_info *hinfo,
struct ext4_dir_entry_2 *de,
int size, int show_names)
{
unsigned names = 0, space = 0;
char *base = (char *) de;
struct dx_hash_info h = *hinfo;
printk("names: ");
while ((char *) de < base + size)
{
if (de->inode)
{
if (show_names)
{
#ifdef CONFIG_FS_ENCRYPTION
int len;
char *name;
struct fscrypt_str fname_crypto_str =
FSTR_INIT(NULL, 0);
int res = 0;
name = de->name;
len = de->name_len;
if (!IS_ENCRYPTED(dir)) {
/* Directory is not encrypted */
(void) ext4fs_dirhash(dir, de->name,
de->name_len, &h);
printk("%*.s:(U)%x.%u ", len,
name, h.hash,
(unsigned) ((char *) de
- base));
} else {
struct fscrypt_str de_name =
FSTR_INIT(name, len);
/* Directory is encrypted */
res = fscrypt_fname_alloc_buffer(
len, &fname_crypto_str);
if (res)
printk(KERN_WARNING "Error "
"allocating crypto "
"buffer--skipping "
"crypto\n");
res = fscrypt_fname_disk_to_usr(dir,
0, 0, &de_name,
&fname_crypto_str);
if (res) {
printk(KERN_WARNING "Error "
"converting filename "
"from disk to usr"
"\n");
name = "??";
len = 2;
} else {
name = fname_crypto_str.name;
len = fname_crypto_str.len;
}
if (IS_CASEFOLDED(dir))
h.hash = EXT4_DIRENT_HASH(de);
else
(void) ext4fs_dirhash(dir,
de->name,
de->name_len, &h);
printk("%*.s:(E)%x.%u ", len, name,
h.hash, (unsigned) ((char *) de
- base));
fscrypt_fname_free_buffer(
&fname_crypto_str);
}
#else
int len = de->name_len;
char *name = de->name;
(void) ext4fs_dirhash(dir, de->name,
de->name_len, &h);
printk("%*.s:%x.%u ", len, name, h.hash,
(unsigned) ((char *) de - base));
#endif
}
space += ext4_dir_rec_len(de->name_len, dir);
names++;
}
de = ext4_next_entry(de, size);
}
printk(KERN_CONT "(%i)\n", names);
return (struct stats) { names, space, 1 };
}
struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
struct dx_entry *entries, int levels)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned count = dx_get_count(entries), names = 0, space = 0, i;
unsigned bcount = 0;
struct buffer_head *bh;
printk("%i indexed blocks...\n", count);
for (i = 0; i < count; i++, entries++)
{
ext4_lblk_t block = dx_get_block(entries);
ext4_lblk_t hash = i ? dx_get_hash(entries): 0;
u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
struct stats stats;
printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range);
bh = ext4_bread(NULL,dir, block, 0);
if (!bh || IS_ERR(bh))
continue;
stats = levels?
dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
bh->b_data, blocksize, 0);
names += stats.names;
space += stats.space;
bcount += stats.bcount;
brelse(bh);
}
if (bcount)
printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
levels ? "" : " ", names, space/bcount,
(space/bcount)*100/blocksize);
return (struct stats) { names, space, bcount};
}
/*
* Linear search cross check
*/
static inline void htree_rep_invariant_check(struct dx_entry *at,
struct dx_entry *target,
u32 hash, unsigned int n)
{
while (n--) {
dxtrace(printk(KERN_CONT ","));
if (dx_get_hash(++at) > hash) {
at--;
break;
}
}
ASSERT(at == target - 1);
}
#else /* DX_DEBUG */
static inline void htree_rep_invariant_check(struct dx_entry *at,
struct dx_entry *target,
u32 hash, unsigned int n)
{
}
#endif /* DX_DEBUG */
/*
* Probe for a directory leaf block to search.
*
* dx_probe can return ERR_BAD_DX_DIR, which means there was a format
* error in the directory index, and the caller should fall back to
* searching the directory normally. The callers of dx_probe **MUST**
* check for this error code, and make sure it never gets reflected
* back to userspace.
*/
static struct dx_frame *
dx_probe(struct ext4_filename *fname, struct inode *dir,
struct dx_hash_info *hinfo, struct dx_frame *frame_in)
{
unsigned count, indirect, level, i;
struct dx_entry *at, *entries, *p, *q, *m;
struct dx_root *root;
struct dx_frame *frame = frame_in;
struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
u32 hash;
ext4_lblk_t block;
ext4_lblk_t blocks[EXT4_HTREE_LEVEL];
memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
frame->bh = ext4_read_dirblock(dir, 0, INDEX);
if (IS_ERR(frame->bh))
return (struct dx_frame *) frame->bh;
root = (struct dx_root *) frame->bh->b_data;
if (root->info.hash_version != DX_HASH_TEA &&
root->info.hash_version != DX_HASH_HALF_MD4 &&
root->info.hash_version != DX_HASH_LEGACY &&
root->info.hash_version != DX_HASH_SIPHASH) {
ext4_warning_inode(dir, "Unrecognised inode hash code %u",
root->info.hash_version);
goto fail;
}
if (ext4_hash_in_dirent(dir)) {
if (root->info.hash_version != DX_HASH_SIPHASH) {
ext4_warning_inode(dir,
"Hash in dirent, but hash is not SIPHASH");
goto fail;
}
} else {
if (root->info.hash_version == DX_HASH_SIPHASH) {
ext4_warning_inode(dir,
"Hash code is SIPHASH, but hash not in dirent");
goto fail;
}
}
if (fname)
hinfo = &fname->hinfo;
hinfo->hash_version = root->info.hash_version;
if (hinfo->hash_version <= DX_HASH_TEA)
hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
/* hash is already computed for encrypted casefolded directory */
if (fname && fname_name(fname) &&
!(IS_ENCRYPTED(dir) && IS_CASEFOLDED(dir))) {
int ret = ext4fs_dirhash(dir, fname_name(fname),
fname_len(fname), hinfo);
if (ret < 0) {
ret_err = ERR_PTR(ret);
goto fail;
}
}
hash = hinfo->hash;
if (root->info.unused_flags & 1) {
ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
root->info.unused_flags);
goto fail;
}
indirect = root->info.indirect_levels;
if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
ext4_warning(dir->i_sb,
"Directory (ino: %lu) htree depth %#06x exceed"
"supported value", dir->i_ino,
ext4_dir_htree_level(dir->i_sb));
if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
ext4_warning(dir->i_sb, "Enable large directory "
"feature to access it");
}
goto fail;
}
entries = (struct dx_entry *)(((char *)&root->info) +
root->info.info_length);
if (dx_get_limit(entries) != dx_root_limit(dir,
root->info.info_length)) {
ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
dx_get_limit(entries),
dx_root_limit(dir, root->info.info_length));
goto fail;
}
dxtrace(printk("Look up %x", hash));
level = 0;
blocks[0] = 0;
while (1) {
count = dx_get_count(entries);
if (!count || count > dx_get_limit(entries)) {
ext4_warning_inode(dir,
"dx entry: count %u beyond limit %u",
count, dx_get_limit(entries));
goto fail;
}
p = entries + 1;
q = entries + count - 1;
while (p <= q) {
m = p + (q - p) / 2;
dxtrace(printk(KERN_CONT "."));
if (dx_get_hash(m) > hash)
q = m - 1;
else
p = m + 1;
}
htree_rep_invariant_check(entries, p, hash, count - 1);
at = p - 1;
dxtrace(printk(KERN_CONT " %x->%u\n",
at == entries ? 0 : dx_get_hash(at),
dx_get_block(at)));
frame->entries = entries;
frame->at = at;
block = dx_get_block(at);
for (i = 0; i <= level; i++) {
if (blocks[i] == block) {
ext4_warning_inode(dir,
"dx entry: tree cycle block %u points back to block %u",
blocks[level], block);
goto fail;
}
}
if (++level > indirect)
return frame;
blocks[level] = block;
frame++;
frame->bh = ext4_read_dirblock(dir, block, INDEX);
if (IS_ERR(frame->bh)) {
ret_err = (struct dx_frame *) frame->bh;
frame->bh = NULL;
goto fail;
}
entries = ((struct dx_node *) frame->bh->b_data)->entries;
if (dx_get_limit(entries) != dx_node_limit(dir)) {
ext4_warning_inode(dir,
"dx entry: limit %u != node limit %u",
dx_get_limit(entries), dx_node_limit(dir));
goto fail;
}
}
fail:
while (frame >= frame_in) {
brelse(frame->bh);
frame--;
}
if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
ext4_warning_inode(dir,
"Corrupt directory, running e2fsck is recommended");
return ret_err;
}
static void dx_release(struct dx_frame *frames)
{
struct dx_root_info *info;
int i;
unsigned int indirect_levels;
if (frames[0].bh == NULL)
return;
info = &((struct dx_root *)frames[0].bh->b_data)->info;
/* save local copy, "info" may be freed after brelse() */
indirect_levels = info->indirect_levels;
for (i = 0; i <= indirect_levels; i++) {
if (frames[i].bh == NULL)
break;
brelse(frames[i].bh);
frames[i].bh = NULL;
}
}
/*
* This function increments the frame pointer to search the next leaf
* block, and reads in the necessary intervening nodes if the search
* should be necessary. Whether or not the search is necessary is
* controlled by the hash parameter. If the hash value is even, then
* the search is only continued if the next block starts with that
* hash value. This is used if we are searching for a specific file.
*
* If the hash value is HASH_NB_ALWAYS, then always go to the next block.
*
* This function returns 1 if the caller should continue to search,
* or 0 if it should not. If there is an error reading one of the
* index blocks, it will a negative error code.
*
* If start_hash is non-null, it will be filled in with the starting
* hash of the next page.
*/
static int ext4_htree_next_block(struct inode *dir, __u32 hash,
struct dx_frame *frame,
struct dx_frame *frames,
__u32 *start_hash)
{
struct dx_frame *p;
struct buffer_head *bh;
int num_frames = 0;
__u32 bhash;
p = frame;
/*
* Find the next leaf page by incrementing the frame pointer.
* If we run out of entries in the interior node, loop around and
* increment pointer in the parent node. When we break out of
* this loop, num_frames indicates the number of interior
* nodes need to be read.
*/
while (1) {
if (++(p->at) < p->entries + dx_get_count(p->entries))
break;
if (p == frames)
return 0;
num_frames++;
p--;
}
/*
* If the hash is 1, then continue only if the next page has a
* continuation hash of any value. This is used for readdir
* handling. Otherwise, check to see if the hash matches the
* desired continuation hash. If it doesn't, return since
* there's no point to read in the successive index pages.
*/
bhash = dx_get_hash(p->at);
if (start_hash)
*start_hash = bhash;
if ((hash & 1) == 0) {
if ((bhash & ~1) != hash)
return 0;
}
/*
* If the hash is HASH_NB_ALWAYS, we always go to the next
* block so no check is necessary
*/
while (num_frames--) {
bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
if (IS_ERR(bh))
return PTR_ERR(bh);
p++;
brelse(p->bh);
p->bh = bh;
p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
}
return 1;
}
/*
* This function fills a red-black tree with information from a
* directory block. It returns the number directory entries loaded
* into the tree. If there is an error it is returned in err.
*/
static int htree_dirblock_to_tree(struct file *dir_file,
struct inode *dir, ext4_lblk_t block,
struct dx_hash_info *hinfo,
__u32 start_hash, __u32 start_minor_hash)
{
struct buffer_head *bh;
struct ext4_dir_entry_2 *de, *top;
int err = 0, count = 0;
struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
int csum = ext4_has_metadata_csum(dir->i_sb);
dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
(unsigned long)block));
bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
if (IS_ERR(bh))
return PTR_ERR(bh);
de = (struct ext4_dir_entry_2 *) bh->b_data;
/* csum entries are not larger in the casefolded encrypted case */
top = (struct ext4_dir_entry_2 *) ((char *) de +
dir->i_sb->s_blocksize -
ext4_dir_rec_len(0,
csum ? NULL : dir));
/* Check if the directory is encrypted */
if (IS_ENCRYPTED(dir)) {
err = fscrypt_prepare_readdir(dir);
if (err < 0) {
brelse(bh);
return err;
}
err = fscrypt_fname_alloc_buffer(EXT4_NAME_LEN,
&fname_crypto_str);
if (err < 0) {
brelse(bh);
return err;
}
}
for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
bh->b_data, bh->b_size,
(block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
+ ((char *)de - bh->b_data))) {
/* silently ignore the rest of the block */
break;
}
if (ext4_hash_in_dirent(dir)) {
if (de->name_len && de->inode) {
hinfo->hash = EXT4_DIRENT_HASH(de);
hinfo->minor_hash = EXT4_DIRENT_MINOR_HASH(de);
} else {
hinfo->hash = 0;
hinfo->minor_hash = 0;
}
} else {
err = ext4fs_dirhash(dir, de->name,
de->name_len, hinfo);
if (err < 0) {
count = err;
goto errout;
}
}
if ((hinfo->hash < start_hash) ||
((hinfo->hash == start_hash) &&
(hinfo->minor_hash < start_minor_hash)))
continue;
if (de->inode == 0)
continue;
if (!IS_ENCRYPTED(dir)) {
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file,
hinfo->hash, hinfo->minor_hash, de,
&tmp_str);
} else {
int save_len = fname_crypto_str.len;
struct fscrypt_str de_name = FSTR_INIT(de->name,
de->name_len);
/* Directory is encrypted */
err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
hinfo->minor_hash, &de_name,
&fname_crypto_str);
if (err) {
count = err;
goto errout;
}
err = ext4_htree_store_dirent(dir_file,
hinfo->hash, hinfo->minor_hash, de,
&fname_crypto_str);
fname_crypto_str.len = save_len;
}
if (err != 0) {
count = err;
goto errout;
}
count++;
}
errout:
brelse(bh);
fscrypt_fname_free_buffer(&fname_crypto_str);
return count;
}
/*
* This function fills a red-black tree with information from a
* directory. We start scanning the directory in hash order, starting
* at start_hash and start_minor_hash.
*
* This function returns the number of entries inserted into the tree,
* or a negative error code.
*/
int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
__u32 start_minor_hash, __u32 *next_hash)
{
struct dx_hash_info hinfo;
struct ext4_dir_entry_2 *de;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct inode *dir;
ext4_lblk_t block;
int count = 0;
int ret, err;
__u32 hashval;
struct fscrypt_str tmp_str;
dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
start_hash, start_minor_hash));
dir = file_inode(dir_file);
if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
if (ext4_hash_in_dirent(dir))
hinfo.hash_version = DX_HASH_SIPHASH;
else
hinfo.hash_version =
EXT4_SB(dir->i_sb)->s_def_hash_version;
if (hinfo.hash_version <= DX_HASH_TEA)
hinfo.hash_version +=
EXT4_SB(dir->i_sb)->s_hash_unsigned;
hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
count = ext4_inlinedir_to_tree(dir_file, dir, 0,
&hinfo, start_hash,
start_minor_hash,
&has_inline_data);
if (has_inline_data) {
*next_hash = ~0;
return count;
}
}
count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
start_hash, start_minor_hash);
*next_hash = ~0;
return count;
}
hinfo.hash = start_hash;
hinfo.minor_hash = 0;
frame = dx_probe(NULL, dir, &hinfo, frames);
if (IS_ERR(frame))
return PTR_ERR(frame);
/* Add '.' and '..' from the htree header */
if (!start_hash && !start_minor_hash) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file, 0, 0,
de, &tmp_str);
if (err != 0)
goto errout;
count++;
}
if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
de = ext4_next_entry(de, dir->i_sb->s_blocksize);
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file, 2, 0,
de, &tmp_str);
if (err != 0)
goto errout;
count++;
}
while (1) {
if (fatal_signal_pending(current)) {
err = -ERESTARTSYS;
goto errout;
}
cond_resched();
block = dx_get_block(frame->at);
ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
start_hash, start_minor_hash);
if (ret < 0) {
err = ret;
goto errout;
}
count += ret;
hashval = ~0;
ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
frame, frames, &hashval);
*next_hash = hashval;
if (ret < 0) {
err = ret;
goto errout;
}
/*
* Stop if: (a) there are no more entries, or
* (b) we have inserted at least one entry and the
* next hash value is not a continuation
*/
if ((ret == 0) ||
(count && ((hashval & 1) == 0)))
break;
}
dx_release(frames);
dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
"next hash: %x\n", count, *next_hash));
return count;
errout:
dx_release(frames);
return (err);
}
static inline int search_dirblock(struct buffer_head *bh,
struct inode *dir,
struct ext4_filename *fname,
unsigned int offset,
struct ext4_dir_entry_2 **res_dir)
{
return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
fname, offset, res_dir);
}
/*
* Directory block splitting, compacting
*/
/*
* Create map of hash values, offsets, and sizes, stored at end of block.
* Returns number of entries mapped.
*/
static int dx_make_map(struct inode *dir, struct buffer_head *bh,
struct dx_hash_info *hinfo,
struct dx_map_entry *map_tail)
{
int count = 0;
struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)bh->b_data;
unsigned int buflen = bh->b_size;
char *base = bh->b_data;
struct dx_hash_info h = *hinfo;
int blocksize = EXT4_BLOCK_SIZE(dir->i_sb);
if (ext4_has_metadata_csum(dir->i_sb))
buflen -= sizeof(struct ext4_dir_entry_tail);
while ((char *) de < base + buflen) {
if (ext4_check_dir_entry(dir, NULL, de, bh, base, buflen,
((char *)de) - base))
return -EFSCORRUPTED;
if (de->name_len && de->inode) {
if (ext4_hash_in_dirent(dir))
h.hash = EXT4_DIRENT_HASH(de);
else {
int err = ext4fs_dirhash(dir, de->name,
de->name_len, &h);
if (err < 0)
return err;
}
map_tail--;
map_tail->hash = h.hash;
map_tail->offs = ((char *) de - base)>>2;
map_tail->size = ext4_rec_len_from_disk(de->rec_len,
blocksize);
count++;
cond_resched();
}
de = ext4_next_entry(de, blocksize);
}
return count;
}
/* Sort map by hash value */
static void dx_sort_map (struct dx_map_entry *map, unsigned count)
{
struct dx_map_entry *p, *q, *top = map + count - 1;
int more;
/* Combsort until bubble sort doesn't suck */
while (count > 2) {
count = count*10/13;
if (count - 9 < 2) /* 9, 10 -> 11 */
count = 11;
for (p = top, q = p - count; q >= map; p--, q--)
if (p->hash < q->hash)
swap(*p, *q);
}
/* Garden variety bubble sort */
do {
more = 0;
q = top;
while (q-- > map) {
if (q[1].hash >= q[0].hash)
continue;
swap(*(q+1), *q);
more = 1;
}
} while(more);
}
static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
{
struct dx_entry *entries = frame->entries;
struct dx_entry *old = frame->at, *new = old + 1;
int count = dx_get_count(entries);
ASSERT(count < dx_get_limit(entries));
ASSERT(old < entries + count);
memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
dx_set_hash(new, hash);
dx_set_block(new, block);
dx_set_count(entries, count + 1);
}
#if IS_ENABLED(CONFIG_UNICODE)
/*
* Test whether a case-insensitive directory entry matches the filename
* being searched for. If quick is set, assume the name being looked up
* is already in the casefolded form.
*
* Returns: 0 if the directory entry matches, more than 0 if it
* doesn't match or less than zero on error.
*/
static int ext4_ci_compare(const struct inode *parent, const struct qstr *name,
u8 *de_name, size_t de_name_len, bool quick)
{
const struct super_block *sb = parent->i_sb;
const struct unicode_map *um = sb->s_encoding;
struct fscrypt_str decrypted_name = FSTR_INIT(NULL, de_name_len);
struct qstr entry = QSTR_INIT(de_name, de_name_len);
int ret;
if (IS_ENCRYPTED(parent)) {
const struct fscrypt_str encrypted_name =
FSTR_INIT(de_name, de_name_len);
decrypted_name.name = kmalloc(de_name_len, GFP_KERNEL);
if (!decrypted_name.name)
return -ENOMEM;
ret = fscrypt_fname_disk_to_usr(parent, 0, 0, &encrypted_name,
&decrypted_name);
if (ret < 0)
goto out;
entry.name = decrypted_name.name;
entry.len = decrypted_name.len;
}
if (quick)
ret = utf8_strncasecmp_folded(um, name, &entry);
else
ret = utf8_strncasecmp(um, name, &entry);
if (ret < 0) {
/* Handle invalid character sequence as either an error
* or as an opaque byte sequence.
*/
if (sb_has_strict_encoding(sb))
ret = -EINVAL;
else if (name->len != entry.len)
ret = 1;
else
ret = !!memcmp(name->name, entry.name, entry.len);
}
out:
kfree(decrypted_name.name);
return ret;
}
int ext4_fname_setup_ci_filename(struct inode *dir, const struct qstr *iname,
struct ext4_filename *name)
{
struct fscrypt_str *cf_name = &name->cf_name;
struct dx_hash_info *hinfo = &name->hinfo;
int len;
if (!IS_CASEFOLDED(dir) ||
(IS_ENCRYPTED(dir) && !fscrypt_has_encryption_key(dir))) {
cf_name->name = NULL;
return 0;
}
cf_name->name = kmalloc(EXT4_NAME_LEN, GFP_NOFS);
if (!cf_name->name)
return -ENOMEM;
len = utf8_casefold(dir->i_sb->s_encoding,
iname, cf_name->name,
EXT4_NAME_LEN);
if (len <= 0) {
kfree(cf_name->name);
cf_name->name = NULL;
}
cf_name->len = (unsigned) len;
if (!IS_ENCRYPTED(dir))
return 0;
hinfo->hash_version = DX_HASH_SIPHASH;
hinfo->seed = NULL;
if (cf_name->name)
return ext4fs_dirhash(dir, cf_name->name, cf_name->len, hinfo);
else
return ext4fs_dirhash(dir, iname->name, iname->len, hinfo);
}
#endif
/*
* Test whether a directory entry matches the filename being searched for.
*
* Return: %true if the directory entry matches, otherwise %false.
*/
static bool ext4_match(struct inode *parent,
const struct ext4_filename *fname,
struct ext4_dir_entry_2 *de)
{
struct fscrypt_name f;
if (!de->inode)
return false;
f.usr_fname = fname->usr_fname;
f.disk_name = fname->disk_name;
#ifdef CONFIG_FS_ENCRYPTION
f.crypto_buf = fname->crypto_buf;
#endif
#if IS_ENABLED(CONFIG_UNICODE)
if (IS_CASEFOLDED(parent) &&
(!IS_ENCRYPTED(parent) || fscrypt_has_encryption_key(parent))) {
if (fname->cf_name.name) {
struct qstr cf = {.name = fname->cf_name.name,
.len = fname->cf_name.len};
if (IS_ENCRYPTED(parent)) {
if (fname->hinfo.hash != EXT4_DIRENT_HASH(de) ||
fname->hinfo.minor_hash !=
EXT4_DIRENT_MINOR_HASH(de)) {
return false;
}
}
return !ext4_ci_compare(parent, &cf, de->name,
de->name_len, true);
}
return !ext4_ci_compare(parent, fname->usr_fname, de->name,
de->name_len, false);
}
#endif
return fscrypt_match_name(&f, de->name, de->name_len);
}
/*
* Returns 0 if not found, -1 on failure, and 1 on success
*/
int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
struct inode *dir, struct ext4_filename *fname,
unsigned int offset, struct ext4_dir_entry_2 **res_dir)
{
struct ext4_dir_entry_2 * de;
char * dlimit;
int de_len;
de = (struct ext4_dir_entry_2 *)search_buf;
dlimit = search_buf + buf_size;
while ((char *) de < dlimit - EXT4_BASE_DIR_LEN) {
/* this code is executed quadratically often */
/* do minimal checking `by hand' */
if (de->name + de->name_len <= dlimit &&
ext4_match(dir, fname, de)) {
/* found a match - just to be sure, do
* a full check */
if (ext4_check_dir_entry(dir, NULL, de, bh, search_buf,
buf_size, offset))
return -1;
*res_dir = de;
return 1;
}
/* prevent looping on a bad block */
de_len = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
if (de_len <= 0)
return -1;
offset += de_len;
de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
}
return 0;
}
static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
struct ext4_dir_entry *de)
{
struct super_block *sb = dir->i_sb;
if (!is_dx(dir))
return 0;
if (block == 0)
return 1;
if (de->inode == 0 &&
ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
sb->s_blocksize)
return 1;
return 0;
}
/*
* __ext4_find_entry()
*
* finds an entry in the specified directory with the wanted name. It
* returns the cache buffer in which the entry was found, and the entry
* itself (as a parameter - res_dir). It does NOT read the inode of the
* entry - you'll have to do that yourself if you want to.
*
* The returned buffer_head has ->b_count elevated. The caller is expected
* to brelse() it when appropriate.
*/
static struct buffer_head *__ext4_find_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir,
int *inlined)
{
struct super_block *sb;
struct buffer_head *bh_use[NAMEI_RA_SIZE];
struct buffer_head *bh, *ret = NULL;
ext4_lblk_t start, block;
const u8 *name = fname->usr_fname->name;
size_t ra_max = 0; /* Number of bh's in the readahead
buffer, bh_use[] */
size_t ra_ptr = 0; /* Current index into readahead
buffer */
ext4_lblk_t nblocks;
int i, namelen, retval;
*res_dir = NULL;
sb = dir->i_sb;
namelen = fname->usr_fname->len;
if (namelen > EXT4_NAME_LEN)
return NULL;
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
ret = ext4_find_inline_entry(dir, fname, res_dir,
&has_inline_data);
if (inlined)
*inlined = has_inline_data;
if (has_inline_data)
goto cleanup_and_exit;
}
if ((namelen <= 2) && (name[0] == '.') &&
(name[1] == '.' || name[1] == '\0')) {
/*
* "." or ".." will only be in the first block
* NFS may look up ".."; "." should be handled by the VFS
*/
block = start = 0;
nblocks = 1;
goto restart;
}
if (is_dx(dir)) {
ret = ext4_dx_find_entry(dir, fname, res_dir);
/*
* On success, or if the error was file not found,
* return. Otherwise, fall back to doing a search the
* old fashioned way.
*/
if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
goto cleanup_and_exit;
dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
"falling back\n"));
ret = NULL;
}
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
if (!nblocks) {
ret = NULL;
goto cleanup_and_exit;
}
start = EXT4_I(dir)->i_dir_start_lookup;
if (start >= nblocks)
start = 0;
block = start;
restart:
do {
/*
* We deal with the read-ahead logic here.
*/
cond_resched();
if (ra_ptr >= ra_max) {
/* Refill the readahead buffer */
ra_ptr = 0;
if (block < start)
ra_max = start - block;
else
ra_max = nblocks - block;
ra_max = min(ra_max, ARRAY_SIZE(bh_use));
retval = ext4_bread_batch(dir, block, ra_max,
false /* wait */, bh_use);
if (retval) {
ret = ERR_PTR(retval);
ra_max = 0;
goto cleanup_and_exit;
}
}
if ((bh = bh_use[ra_ptr++]) == NULL)
goto next;
wait_on_buffer(bh);
if (!buffer_uptodate(bh)) {
EXT4_ERROR_INODE_ERR(dir, EIO,
"reading directory lblock %lu",
(unsigned long) block);
brelse(bh);
ret = ERR_PTR(-EIO);
goto cleanup_and_exit;
}
if (!buffer_verified(bh) &&
!is_dx_internal_node(dir, block,
(struct ext4_dir_entry *)bh->b_data) &&
!ext4_dirblock_csum_verify(dir, bh)) {
EXT4_ERROR_INODE_ERR(dir, EFSBADCRC,
"checksumming directory "
"block %lu", (unsigned long)block);
brelse(bh);
ret = ERR_PTR(-EFSBADCRC);
goto cleanup_and_exit;
}
set_buffer_verified(bh);
i = search_dirblock(bh, dir, fname,
block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
if (i == 1) {
EXT4_I(dir)->i_dir_start_lookup = block;
ret = bh;
goto cleanup_and_exit;
} else {
brelse(bh);
if (i < 0)
goto cleanup_and_exit;
}
next:
if (++block >= nblocks)
block = 0;
} while (block != start);
/*
* If the directory has grown while we were searching, then
* search the last part of the directory before giving up.
*/
block = nblocks;
nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
if (block < nblocks) {
start = 0;
goto restart;
}
cleanup_and_exit:
/* Clean up the read-ahead blocks */
for (; ra_ptr < ra_max; ra_ptr++)
brelse(bh_use[ra_ptr]);
return ret;
}
static struct buffer_head *ext4_find_entry(struct inode *dir,
const struct qstr *d_name,
struct ext4_dir_entry_2 **res_dir,
int *inlined)
{
int err;
struct ext4_filename fname;
struct buffer_head *bh;
err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
if (err == -ENOENT)
return NULL;
if (err)
return ERR_PTR(err);
bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
ext4_fname_free_filename(&fname);
return bh;
}
static struct buffer_head *ext4_lookup_entry(struct inode *dir,
struct dentry *dentry,
struct ext4_dir_entry_2 **res_dir)
{
int err;
struct ext4_filename fname;
struct buffer_head *bh;
err = ext4_fname_prepare_lookup(dir, dentry, &fname);
generic_set_encrypted_ci_d_ops(dentry);
if (err == -ENOENT)
return NULL;
if (err)
return ERR_PTR(err);
bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
ext4_fname_free_filename(&fname);
return bh;
}
static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir)
{
struct super_block * sb = dir->i_sb;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct buffer_head *bh;
ext4_lblk_t block;
int retval;
#ifdef CONFIG_FS_ENCRYPTION
*res_dir = NULL;
#endif
frame = dx_probe(fname, dir, NULL, frames);
if (IS_ERR(frame))
return (struct buffer_head *) frame;
do {
block = dx_get_block(frame->at);
bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
if (IS_ERR(bh))
goto errout;
retval = search_dirblock(bh, dir, fname,
block << EXT4_BLOCK_SIZE_BITS(sb),
res_dir);
if (retval == 1)
goto success;
brelse(bh);
if (retval == -1) {
bh = ERR_PTR(ERR_BAD_DX_DIR);
goto errout;
}
/* Check to see if we should continue to search */
retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
frames, NULL);
if (retval < 0) {
ext4_warning_inode(dir,
"error %d reading directory index block",
retval);
bh = ERR_PTR(retval);
goto errout;
}
} while (retval == 1);
bh = NULL;
errout:
dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
success:
dx_release(frames);
return bh;
}
static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
struct inode *inode;
struct ext4_dir_entry_2 *de;
struct buffer_head *bh;
if (dentry->d_name.len > EXT4_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
bh = ext4_lookup_entry(dir, dentry, &de);
if (IS_ERR(bh))
return ERR_CAST(bh);
inode = NULL;
if (bh) {
__u32 ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(dir->i_sb, ino)) {
EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
return ERR_PTR(-EFSCORRUPTED);
}
if (unlikely(ino == dir->i_ino)) {
EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
dentry);
return ERR_PTR(-EFSCORRUPTED);
}
inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
if (inode == ERR_PTR(-ESTALE)) {
EXT4_ERROR_INODE(dir,
"deleted inode referenced: %u",
ino);
return ERR_PTR(-EFSCORRUPTED);
}
if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
(S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
!fscrypt_has_permitted_context(dir, inode)) {
ext4_warning(inode->i_sb,
"Inconsistent encryption contexts: %lu/%lu",
dir->i_ino, inode->i_ino);
iput(inode);
return ERR_PTR(-EPERM);
}
}
#if IS_ENABLED(CONFIG_UNICODE)
if (!inode && IS_CASEFOLDED(dir)) {
/* Eventually we want to call d_add_ci(dentry, NULL)
* for negative dentries in the encoding case as
* well. For now, prevent the negative dentry
* from being cached.
*/
return NULL;
}
#endif
return d_splice_alias(inode, dentry);
}
struct dentry *ext4_get_parent(struct dentry *child)
{
__u32 ino;
struct ext4_dir_entry_2 * de;
struct buffer_head *bh;
bh = ext4_find_entry(d_inode(child), &dotdot_name, &de, NULL);
if (IS_ERR(bh))
return ERR_CAST(bh);
if (!bh)
return ERR_PTR(-ENOENT);
ino = le32_to_cpu(de->inode);
brelse(bh);
if (!ext4_valid_inum(child->d_sb, ino)) {
EXT4_ERROR_INODE(d_inode(child),
"bad parent inode number: %u", ino);
return ERR_PTR(-EFSCORRUPTED);
}
return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
}
/*
* Move count entries from end of map between two memory locations.
* Returns pointer to last entry moved.
*/
static struct ext4_dir_entry_2 *
dx_move_dirents(struct inode *dir, char *from, char *to,
struct dx_map_entry *map, int count,
unsigned blocksize)
{
unsigned rec_len = 0;
while (count--) {
struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
(from + (map->offs<<2));
rec_len = ext4_dir_rec_len(de->name_len, dir);
memcpy (to, de, rec_len);
((struct ext4_dir_entry_2 *) to)->rec_len =
ext4_rec_len_to_disk(rec_len, blocksize);
/* wipe dir_entry excluding the rec_len field */
de->inode = 0;
memset(&de->name_len, 0, ext4_rec_len_from_disk(de->rec_len,
blocksize) -
offsetof(struct ext4_dir_entry_2,
name_len));
map++;
to += rec_len;
}
return (struct ext4_dir_entry_2 *) (to - rec_len);
}
/*
* Compact each dir entry in the range to the minimal rec_len.
* Returns pointer to last entry in range.
*/
static struct ext4_dir_entry_2 *dx_pack_dirents(struct inode *dir, char *base,
unsigned int blocksize)
{
struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
unsigned rec_len = 0;
prev = to = de;
while ((char*)de < base + blocksize) {
next = ext4_next_entry(de, blocksize);
if (de->inode && de->name_len) {
rec_len = ext4_dir_rec_len(de->name_len, dir);
if (de > to)
memmove(to, de, rec_len);
to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
prev = to;
to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
}
de = next;
}
return prev;
}
/*
* Split a full leaf block to make room for a new dir entry.
* Allocate a new block, and move entries so that they are approx. equally full.
* Returns pointer to de in block into which the new entry will be inserted.
*/
static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
struct buffer_head **bh,struct dx_frame *frame,
struct dx_hash_info *hinfo)
{
unsigned blocksize = dir->i_sb->s_blocksize;
unsigned continued;
int count;
struct buffer_head *bh2;
ext4_lblk_t newblock;
u32 hash2;
struct dx_map_entry *map;
char *data1 = (*bh)->b_data, *data2;
unsigned split, move, size;
struct ext4_dir_entry_2 *de = NULL, *de2;
int csum_size = 0;
int err = 0, i;
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
bh2 = ext4_append(handle, dir, &newblock);
if (IS_ERR(bh2)) {
brelse(*bh);
*bh = NULL;
return (struct ext4_dir_entry_2 *) bh2;
}
BUFFER_TRACE(*bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, *bh,
EXT4_JTR_NONE);
if (err)
goto journal_error;
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, frame->bh,
EXT4_JTR_NONE);
if (err)
goto journal_error;
data2 = bh2->b_data;
/* create map in the end of data2 block */
map = (struct dx_map_entry *) (data2 + blocksize);
count = dx_make_map(dir, *bh, hinfo, map);
if (count < 0) {
err = count;
goto journal_error;
}
map -= count;
dx_sort_map(map, count);
/* Ensure that neither split block is over half full */
size = 0;
move = 0;
for (i = count-1; i >= 0; i--) {
/* is more than half of this entry in 2nd half of the block? */
if (size + map[i].size/2 > blocksize/2)
break;
size += map[i].size;
move++;
}
/*
* map index at which we will split
*
* If the sum of active entries didn't exceed half the block size, just
* split it in half by count; each resulting block will have at least
* half the space free.
*/
if (i > 0)
split = count - move;
else
split = count/2;
hash2 = map[split].hash;
continued = hash2 == map[split - 1].hash;
dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
(unsigned long)dx_get_block(frame->at),
hash2, split, count-split));
/* Fancy dance to stay within two buffers */
de2 = dx_move_dirents(dir, data1, data2, map + split, count - split,
blocksize);
de = dx_pack_dirents(dir, data1, blocksize);
de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
(char *) de,
blocksize);
de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
(char *) de2,
blocksize);
if (csum_size) {
ext4_initialize_dirent_tail(*bh, blocksize);
ext4_initialize_dirent_tail(bh2, blocksize);
}
dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
blocksize, 1));
dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
blocksize, 1));
/* Which block gets the new entry? */
if (hinfo->hash >= hash2) {
swap(*bh, bh2);
de = de2;
}
dx_insert_block(frame, hash2 + continued, newblock);
err = ext4_handle_dirty_dirblock(handle, dir, bh2);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (err)
goto journal_error;
brelse(bh2);
dxtrace(dx_show_index("frame", frame->entries));
return de;
journal_error:
brelse(*bh);
brelse(bh2);
*bh = NULL;
ext4_std_error(dir->i_sb, err);
return ERR_PTR(err);
}
int ext4_find_dest_de(struct inode *dir, struct inode *inode,
struct buffer_head *bh,
void *buf, int buf_size,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **dest_de)
{
struct ext4_dir_entry_2 *de;
unsigned short reclen = ext4_dir_rec_len(fname_len(fname), dir);
int nlen, rlen;
unsigned int offset = 0;
char *top;
de = buf;
top = buf + buf_size - reclen;
while ((char *) de <= top) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
buf, buf_size, offset))
return -EFSCORRUPTED;
if (ext4_match(dir, fname, de))
return -EEXIST;
nlen = ext4_dir_rec_len(de->name_len, dir);
rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
if ((de->inode ? rlen - nlen : rlen) >= reclen)
break;
de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
offset += rlen;
}
if ((char *) de > top)
return -ENOSPC;
*dest_de = de;
return 0;
}
void ext4_insert_dentry(struct inode *dir,
struct inode *inode,
struct ext4_dir_entry_2 *de,
int buf_size,
struct ext4_filename *fname)
{
int nlen, rlen;
nlen = ext4_dir_rec_len(de->name_len, dir);
rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
if (de->inode) {
struct ext4_dir_entry_2 *de1 =
(struct ext4_dir_entry_2 *)((char *)de + nlen);
de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
de = de1;
}
de->file_type = EXT4_FT_UNKNOWN;
de->inode = cpu_to_le32(inode->i_ino);
ext4_set_de_type(inode->i_sb, de, inode->i_mode);
de->name_len = fname_len(fname);
memcpy(de->name, fname_name(fname), fname_len(fname));
if (ext4_hash_in_dirent(dir)) {
struct dx_hash_info *hinfo = &fname->hinfo;
EXT4_DIRENT_HASHES(de)->hash = cpu_to_le32(hinfo->hash);
EXT4_DIRENT_HASHES(de)->minor_hash =
cpu_to_le32(hinfo->minor_hash);
}
}
/*
* Add a new entry into a directory (leaf) block. If de is non-NULL,
* it points to a directory entry which is guaranteed to be large
* enough for new directory entry. If de is NULL, then
* add_dirent_to_buf will attempt search the directory block for
* space. It will return -ENOSPC if no space is available, and -EIO
* and -EEXIST if directory entry already exists.
*/
static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
struct inode *dir,
struct inode *inode, struct ext4_dir_entry_2 *de,
struct buffer_head *bh)
{
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int err, err2;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
if (!de) {
err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
blocksize - csum_size, fname, &de);
if (err)
return err;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, bh,
EXT4_JTR_NONE);
if (err) {
ext4_std_error(dir->i_sb, err);
return err;
}
/* By now the buffer is marked for journaling */
ext4_insert_dentry(dir, inode, de, blocksize, fname);
/*
* XXX shouldn't update any times until successful
* completion of syscall, but too many callers depend
* on this.
*
* XXX similarly, too many callers depend on
* ext4_new_inode() setting the times, but error
* recovery deletes the inode, so the worst that can
* happen is that the times are slightly out of date
* and/or different from the directory change time.
*/
dir->i_mtime = inode_set_ctime_current(dir);
ext4_update_dx_flag(dir);
inode_inc_iversion(dir);
err2 = ext4_mark_inode_dirty(handle, dir);
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirblock(handle, dir, bh);
if (err)
ext4_std_error(dir->i_sb, err);
return err ? err : err2;
}
/*
* This converts a one block unindexed directory to a 3 block indexed
* directory, and adds the dentry to the indexed directory.
*/
static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
struct inode *dir,
struct inode *inode, struct buffer_head *bh)
{
struct buffer_head *bh2;
struct dx_root *root;
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct dx_entry *entries;
struct ext4_dir_entry_2 *de, *de2;
char *data2, *top;
unsigned len;
int retval;
unsigned blocksize;
ext4_lblk_t block;
struct fake_dirent *fde;
int csum_size = 0;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
blocksize = dir->i_sb->s_blocksize;
dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
BUFFER_TRACE(bh, "get_write_access");
retval = ext4_journal_get_write_access(handle, dir->i_sb, bh,
EXT4_JTR_NONE);
if (retval) {
ext4_std_error(dir->i_sb, retval);
brelse(bh);
return retval;
}
root = (struct dx_root *) bh->b_data;
/* The 0th block becomes the root, move the dirents out */
fde = &root->dotdot;
de = (struct ext4_dir_entry_2 *)((char *)fde +
ext4_rec_len_from_disk(fde->rec_len, blocksize));
if ((char *) de >= (((char *) root) + blocksize)) {
EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
brelse(bh);
return -EFSCORRUPTED;
}
len = ((char *) root) + (blocksize - csum_size) - (char *) de;
/* Allocate new block for the 0th block's dirents */
bh2 = ext4_append(handle, dir, &block);
if (IS_ERR(bh2)) {
brelse(bh);
return PTR_ERR(bh2);
}
ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
data2 = bh2->b_data;
memcpy(data2, de, len);
memset(de, 0, len); /* wipe old data */
de = (struct ext4_dir_entry_2 *) data2;
top = data2 + len;
while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top) {
if (ext4_check_dir_entry(dir, NULL, de, bh2, data2, len,
(data2 + (blocksize - csum_size) -
(char *) de))) {
brelse(bh2);
brelse(bh);
return -EFSCORRUPTED;
}
de = de2;
}
de->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
(char *) de, blocksize);
if (csum_size)
ext4_initialize_dirent_tail(bh2, blocksize);
/* Initialize the root; the dot dirents already exist */
de = (struct ext4_dir_entry_2 *) (&root->dotdot);
de->rec_len = ext4_rec_len_to_disk(
blocksize - ext4_dir_rec_len(2, NULL), blocksize);
memset (&root->info, 0, sizeof(root->info));
root->info.info_length = sizeof(root->info);
if (ext4_hash_in_dirent(dir))
root->info.hash_version = DX_HASH_SIPHASH;
else
root->info.hash_version =
EXT4_SB(dir->i_sb)->s_def_hash_version;
entries = root->entries;
dx_set_block(entries, 1);
dx_set_count(entries, 1);
dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
/* Initialize as for dx_probe */
fname->hinfo.hash_version = root->info.hash_version;
if (fname->hinfo.hash_version <= DX_HASH_TEA)
fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
/* casefolded encrypted hashes are computed on fname setup */
if (!ext4_hash_in_dirent(dir)) {
int err = ext4fs_dirhash(dir, fname_name(fname),
fname_len(fname), &fname->hinfo);
if (err < 0) {
brelse(bh2);
brelse(bh);
return err;
}
}
memset(frames, 0, sizeof(frames));
frame = frames;
frame->entries = entries;
frame->at = entries;
frame->bh = bh;
retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (retval)
goto out_frames;
retval = ext4_handle_dirty_dirblock(handle, dir, bh2);
if (retval)
goto out_frames;
de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
if (IS_ERR(de)) {
retval = PTR_ERR(de);
goto out_frames;
}
retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
out_frames:
/*
* Even if the block split failed, we have to properly write
* out all the changes we did so far. Otherwise we can end up
* with corrupted filesystem.
*/
if (retval)
ext4_mark_inode_dirty(handle, dir);
dx_release(frames);
brelse(bh2);
return retval;
}
/*
* ext4_add_entry()
*
* adds a file entry to the specified directory, using the same
* semantics as ext4_find_entry(). It returns NULL if it failed.
*
* NOTE!! The inode part of 'de' is left at 0 - which means you
* may not sleep between calling this and putting something into
* the entry, as someone else might have used it while you slept.
*/
static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode)
{
struct inode *dir = d_inode(dentry->d_parent);
struct buffer_head *bh = NULL;
struct ext4_dir_entry_2 *de;
struct super_block *sb;
struct ext4_filename fname;
int retval;
int dx_fallback=0;
unsigned blocksize;
ext4_lblk_t block, blocks;
int csum_size = 0;
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
sb = dir->i_sb;
blocksize = sb->s_blocksize;
if (!dentry->d_name.len)
return -EINVAL;
if (fscrypt_is_nokey_name(dentry))
return -ENOKEY;
#if IS_ENABLED(CONFIG_UNICODE)
if (sb_has_strict_encoding(sb) && IS_CASEFOLDED(dir) &&
utf8_validate(sb->s_encoding, &dentry->d_name))
return -EINVAL;
#endif
retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
if (retval)
return retval;
if (ext4_has_inline_data(dir)) {
retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
if (retval < 0)
goto out;
if (retval == 1) {
retval = 0;
goto out;
}
}
if (is_dx(dir)) {
retval = ext4_dx_add_entry(handle, &fname, dir, inode);
if (!retval || (retval != ERR_BAD_DX_DIR))
goto out;
/* Can we just ignore htree data? */
if (ext4_has_metadata_csum(sb)) {
EXT4_ERROR_INODE(dir,
"Directory has corrupted htree index.");
retval = -EFSCORRUPTED;
goto out;
}
ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
dx_fallback++;
retval = ext4_mark_inode_dirty(handle, dir);
if (unlikely(retval))
goto out;
}
blocks = dir->i_size >> sb->s_blocksize_bits;
for (block = 0; block < blocks; block++) {
bh = ext4_read_dirblock(dir, block, DIRENT);
if (bh == NULL) {
bh = ext4_bread(handle, dir, block,
EXT4_GET_BLOCKS_CREATE);
goto add_to_new_block;
}
if (IS_ERR(bh)) {
retval = PTR_ERR(bh);
bh = NULL;
goto out;
}
retval = add_dirent_to_buf(handle, &fname, dir, inode,
NULL, bh);
if (retval != -ENOSPC)
goto out;
if (blocks == 1 && !dx_fallback &&
ext4_has_feature_dir_index(sb)) {
retval = make_indexed_dir(handle, &fname, dir,
inode, bh);
bh = NULL; /* make_indexed_dir releases bh */
goto out;
}
brelse(bh);
}
bh = ext4_append(handle, dir, &block);
add_to_new_block:
if (IS_ERR(bh)) {
retval = PTR_ERR(bh);
bh = NULL;
goto out;
}
de = (struct ext4_dir_entry_2 *) bh->b_data;
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
if (csum_size)
ext4_initialize_dirent_tail(bh, blocksize);
retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
out:
ext4_fname_free_filename(&fname);
brelse(bh);
if (retval == 0)
ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
return retval;
}
/*
* Returns 0 for success, or a negative error value
*/
static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
struct inode *dir, struct inode *inode)
{
struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
struct dx_entry *entries, *at;
struct buffer_head *bh;
struct super_block *sb = dir->i_sb;
struct ext4_dir_entry_2 *de;
int restart;
int err;
again:
restart = 0;
frame = dx_probe(fname, dir, NULL, frames);
if (IS_ERR(frame))
return PTR_ERR(frame);
entries = frame->entries;
at = frame->at;
bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
if (IS_ERR(bh)) {
err = PTR_ERR(bh);
bh = NULL;
goto cleanup;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, bh, EXT4_JTR_NONE);
if (err)
goto journal_error;
err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
if (err != -ENOSPC)
goto cleanup;
err = 0;
/* Block full, should compress but for now just split */
dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
dx_get_count(entries), dx_get_limit(entries)));
/* Need to split index? */
if (dx_get_count(entries) == dx_get_limit(entries)) {
ext4_lblk_t newblock;
int levels = frame - frames + 1;
unsigned int icount;
int add_level = 1;
struct dx_entry *entries2;
struct dx_node *node2;
struct buffer_head *bh2;
while (frame > frames) {
if (dx_get_count((frame - 1)->entries) <
dx_get_limit((frame - 1)->entries)) {
add_level = 0;
break;
}
frame--; /* split higher index block */
at = frame->at;
entries = frame->entries;
restart = 1;
}
if (add_level && levels == ext4_dir_htree_level(sb)) {
ext4_warning(sb, "Directory (ino: %lu) index full, "
"reach max htree level :%d",
dir->i_ino, levels);
if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
ext4_warning(sb, "Large directory feature is "
"not enabled on this "
"filesystem");
}
err = -ENOSPC;
goto cleanup;
}
icount = dx_get_count(entries);
bh2 = ext4_append(handle, dir, &newblock);
if (IS_ERR(bh2)) {
err = PTR_ERR(bh2);
goto cleanup;
}
node2 = (struct dx_node *)(bh2->b_data);
entries2 = node2->entries;
memset(&node2->fake, 0, sizeof(struct fake_dirent));
node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
sb->s_blocksize);
BUFFER_TRACE(frame->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, frame->bh,
EXT4_JTR_NONE);
if (err)
goto journal_error;
if (!add_level) {
unsigned icount1 = icount/2, icount2 = icount - icount1;
unsigned hash2 = dx_get_hash(entries + icount1);
dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
icount1, icount2));
BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
err = ext4_journal_get_write_access(handle, sb,
(frame - 1)->bh,
EXT4_JTR_NONE);
if (err)
goto journal_error;
memcpy((char *) entries2, (char *) (entries + icount1),
icount2 * sizeof(struct dx_entry));
dx_set_count(entries, icount1);
dx_set_count(entries2, icount2);
dx_set_limit(entries2, dx_node_limit(dir));
/* Which index block gets the new entry? */
if (at - entries >= icount1) {
frame->at = at - entries - icount1 + entries2;
frame->entries = entries = entries2;
swap(frame->bh, bh2);
}
dx_insert_block((frame - 1), hash2, newblock);
dxtrace(dx_show_index("node", frame->entries));
dxtrace(dx_show_index("node",
((struct dx_node *) bh2->b_data)->entries));
err = ext4_handle_dirty_dx_node(handle, dir, bh2);
if (err)
goto journal_error;
brelse (bh2);
err = ext4_handle_dirty_dx_node(handle, dir,
(frame - 1)->bh);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir,
frame->bh);
if (restart || err)
goto journal_error;
} else {
struct dx_root *dxroot;
memcpy((char *) entries2, (char *) entries,
icount * sizeof(struct dx_entry));
dx_set_limit(entries2, dx_node_limit(dir));
/* Set up root */
dx_set_count(entries, 1);
dx_set_block(entries + 0, newblock);
dxroot = (struct dx_root *)frames[0].bh->b_data;
dxroot->info.indirect_levels += 1;
dxtrace(printk(KERN_DEBUG
"Creating %d level index...\n",
dxroot->info.indirect_levels));
err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
if (err)
goto journal_error;
err = ext4_handle_dirty_dx_node(handle, dir, bh2);
brelse(bh2);
restart = 1;
goto journal_error;
}
}
de = do_split(handle, dir, &bh, frame, &fname->hinfo);
if (IS_ERR(de)) {
err = PTR_ERR(de);
goto cleanup;
}
err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
goto cleanup;
journal_error:
ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
cleanup:
brelse(bh);
dx_release(frames);
/* @restart is true means htree-path has been changed, we need to
* repeat dx_probe() to find out valid htree-path
*/
if (restart && err == 0)
goto again;
return err;
}
/*
* ext4_generic_delete_entry deletes a directory entry by merging it
* with the previous entry
*/
int ext4_generic_delete_entry(struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh,
void *entry_buf,
int buf_size,
int csum_size)
{
struct ext4_dir_entry_2 *de, *pde;
unsigned int blocksize = dir->i_sb->s_blocksize;
int i;
i = 0;
pde = NULL;
de = entry_buf;
while (i < buf_size - csum_size) {
if (ext4_check_dir_entry(dir, NULL, de, bh,
entry_buf, buf_size, i))
return -EFSCORRUPTED;
if (de == de_del) {
if (pde) {
pde->rec_len = ext4_rec_len_to_disk(
ext4_rec_len_from_disk(pde->rec_len,
blocksize) +
ext4_rec_len_from_disk(de->rec_len,
blocksize),
blocksize);
/* wipe entire dir_entry */
memset(de, 0, ext4_rec_len_from_disk(de->rec_len,
blocksize));
} else {
/* wipe dir_entry excluding the rec_len field */
de->inode = 0;
memset(&de->name_len, 0,
ext4_rec_len_from_disk(de->rec_len,
blocksize) -
offsetof(struct ext4_dir_entry_2,
name_len));
}
inode_inc_iversion(dir);
return 0;
}
i += ext4_rec_len_from_disk(de->rec_len, blocksize);
pde = de;
de = ext4_next_entry(de, blocksize);
}
return -ENOENT;
}
static int ext4_delete_entry(handle_t *handle,
struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh)
{
int err, csum_size = 0;
if (ext4_has_inline_data(dir)) {
int has_inline_data = 1;
err = ext4_delete_inline_entry(handle, dir, de_del, bh,
&has_inline_data);
if (has_inline_data)
return err;
}
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, bh,
EXT4_JTR_NONE);
if (unlikely(err))
goto out;
err = ext4_generic_delete_entry(dir, de_del, bh, bh->b_data,
dir->i_sb->s_blocksize, csum_size);
if (err)
goto out;
BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirblock(handle, dir, bh);
if (unlikely(err))
goto out;
return 0;
out:
if (err != -ENOENT)
ext4_std_error(dir->i_sb, err);
return err;
}
/*
* Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
* since this indicates that nlinks count was previously 1 to avoid overflowing
* the 16-bit i_links_count field on disk. Directories with i_nlink == 1 mean
* that subdirectory link counts are not being maintained accurately.
*
* The caller has already checked for i_nlink overflow in case the DIR_LINK
* feature is not enabled and returned -EMLINK. The is_dx() check is a proxy
* for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
* on regular files) and to avoid creating huge/slow non-HTREE directories.
*/
static void ext4_inc_count(struct inode *inode)
{
inc_nlink(inode);
if (is_dx(inode) &&
(inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
set_nlink(inode, 1);
}
/*
* If a directory had nlink == 1, then we should let it be 1. This indicates
* directory has >EXT4_LINK_MAX subdirs.
*/
static void ext4_dec_count(struct inode *inode)
{
if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
drop_nlink(inode);
}
/*
* Add non-directory inode to a directory. On success, the inode reference is
* consumed by dentry is instantiation. This is also indicated by clearing of
* *inodep pointer. On failure, the caller is responsible for dropping the
* inode reference in the safe context.
*/
static int ext4_add_nondir(handle_t *handle,
struct dentry *dentry, struct inode **inodep)
{
struct inode *dir = d_inode(dentry->d_parent);
struct inode *inode = *inodep;
int err = ext4_add_entry(handle, dentry, inode);
if (!err) {
err = ext4_mark_inode_dirty(handle, inode);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
d_instantiate_new(dentry, inode);
*inodep = NULL;
return err;
}
drop_nlink(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_orphan_add(handle, inode);
unlock_new_inode(inode);
return err;
}
/*
* By the time this is called, we already have created
* the directory cache entry for the new file, but it
* is so far negative - it has no inode.
*
* If the create succeeds, we fill in the inode information
* with d_instantiate().
*/
static int ext4_create(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, bool excl)
{
handle_t *handle;
struct inode *inode;
int err, credits, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(idmap, dir, mode, &dentry->d_name,
0, NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
err = ext4_add_nondir(handle, dentry, &inode);
if (!err)
ext4_fc_track_create(handle, dentry);
}
if (handle)
ext4_journal_stop(handle);
if (!IS_ERR_OR_NULL(inode))
iput(inode);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_mknod(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, dev_t rdev)
{
handle_t *handle;
struct inode *inode;
int err, credits, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(idmap, dir, mode, &dentry->d_name,
0, NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
init_special_inode(inode, inode->i_mode, rdev);
inode->i_op = &ext4_special_inode_operations;
err = ext4_add_nondir(handle, dentry, &inode);
if (!err)
ext4_fc_track_create(handle, dentry);
}
if (handle)
ext4_journal_stop(handle);
if (!IS_ERR_OR_NULL(inode))
iput(inode);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
struct file *file, umode_t mode)
{
handle_t *handle;
struct inode *inode;
int err, retries = 0;
err = dquot_initialize(dir);
if (err)
return err;
retry:
inode = ext4_new_inode_start_handle(idmap, dir, mode,
NULL, 0, NULL,
EXT4_HT_DIR,
EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
4 + EXT4_XATTR_TRANS_BLOCKS);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
inode->i_op = &ext4_file_inode_operations;
inode->i_fop = &ext4_file_operations;
ext4_set_aops(inode);
d_tmpfile(file, inode);
err = ext4_orphan_add(handle, inode);
if (err)
goto err_unlock_inode;
mark_inode_dirty(inode);
unlock_new_inode(inode);
}
if (handle)
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return finish_open_simple(file, err);
err_unlock_inode:
ext4_journal_stop(handle);
unlock_new_inode(inode);
return err;
}
struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
struct ext4_dir_entry_2 *de,
int blocksize, int csum_size,
unsigned int parent_ino, int dotdot_real_len)
{
de->inode = cpu_to_le32(inode->i_ino);
de->name_len = 1;
de->rec_len = ext4_rec_len_to_disk(ext4_dir_rec_len(de->name_len, NULL),
blocksize);
strcpy(de->name, ".");
ext4_set_de_type(inode->i_sb, de, S_IFDIR);
de = ext4_next_entry(de, blocksize);
de->inode = cpu_to_le32(parent_ino);
de->name_len = 2;
if (!dotdot_real_len)
de->rec_len = ext4_rec_len_to_disk(blocksize -
(csum_size + ext4_dir_rec_len(1, NULL)),
blocksize);
else
de->rec_len = ext4_rec_len_to_disk(
ext4_dir_rec_len(de->name_len, NULL),
blocksize);
strcpy(de->name, "..");
ext4_set_de_type(inode->i_sb, de, S_IFDIR);
return ext4_next_entry(de, blocksize);
}
int ext4_init_new_dir(handle_t *handle, struct inode *dir,
struct inode *inode)
{
struct buffer_head *dir_block = NULL;
struct ext4_dir_entry_2 *de;
ext4_lblk_t block = 0;
unsigned int blocksize = dir->i_sb->s_blocksize;
int csum_size = 0;
int err;
if (ext4_has_metadata_csum(dir->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
err = ext4_try_create_inline_dir(handle, dir, inode);
if (err < 0 && err != -ENOSPC)
goto out;
if (!err)
goto out;
}
inode->i_size = 0;
dir_block = ext4_append(handle, inode, &block);
if (IS_ERR(dir_block))
return PTR_ERR(dir_block);
de = (struct ext4_dir_entry_2 *)dir_block->b_data;
ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
set_nlink(inode, 2);
if (csum_size)
ext4_initialize_dirent_tail(dir_block, blocksize);
BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_dirblock(handle, inode, dir_block);
if (err)
goto out;
set_buffer_verified(dir_block);
out:
brelse(dir_block);
return err;
}
static int ext4_mkdir(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode)
{
handle_t *handle;
struct inode *inode;
int err, err2 = 0, credits, retries = 0;
if (EXT4_DIR_LINK_MAX(dir))
return -EMLINK;
err = dquot_initialize(dir);
if (err)
return err;
credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
retry:
inode = ext4_new_inode_start_handle(idmap, dir, S_IFDIR | mode,
&dentry->d_name,
0, NULL, EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_stop;
inode->i_op = &ext4_dir_inode_operations;
inode->i_fop = &ext4_dir_operations;
err = ext4_init_new_dir(handle, dir, inode);
if (err)
goto out_clear_inode;
err = ext4_mark_inode_dirty(handle, inode);
if (!err)
err = ext4_add_entry(handle, dentry, inode);
if (err) {
out_clear_inode:
clear_nlink(inode);
ext4_orphan_add(handle, inode);
unlock_new_inode(inode);
err2 = ext4_mark_inode_dirty(handle, inode);
if (unlikely(err2))
err = err2;
ext4_journal_stop(handle);
iput(inode);
goto out_retry;
}
ext4_inc_count(dir);
ext4_update_dx_flag(dir);
err = ext4_mark_inode_dirty(handle, dir);
if (err)
goto out_clear_inode;
d_instantiate_new(dentry, inode);
ext4_fc_track_create(handle, dentry);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
out_stop:
if (handle)
ext4_journal_stop(handle);
out_retry:
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
/*
* routine to check that the specified directory is empty (for rmdir)
*/
bool ext4_empty_dir(struct inode *inode)
{
unsigned int offset;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
struct super_block *sb;
if (ext4_has_inline_data(inode)) {
int has_inline_data = 1;
int ret;
ret = empty_inline_dir(inode, &has_inline_data);
if (has_inline_data)
return ret;
}
sb = inode->i_sb;
if (inode->i_size < ext4_dir_rec_len(1, NULL) +
ext4_dir_rec_len(2, NULL)) {
EXT4_ERROR_INODE(inode, "invalid size");
return false;
}
/* The first directory block must not be a hole,
* so treat it as DIRENT_HTREE
*/
bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
if (IS_ERR(bh))
return false;
de = (struct ext4_dir_entry_2 *) bh->b_data;
if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
0) ||
le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
ext4_warning_inode(inode, "directory missing '.'");
brelse(bh);
return false;
}
offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
de = ext4_next_entry(de, sb->s_blocksize);
if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
offset) ||
le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
ext4_warning_inode(inode, "directory missing '..'");
brelse(bh);
return false;
}
offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
while (offset < inode->i_size) {
if (!(offset & (sb->s_blocksize - 1))) {
unsigned int lblock;
brelse(bh);
lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
bh = ext4_read_dirblock(inode, lblock, EITHER);
if (bh == NULL) {
offset += sb->s_blocksize;
continue;
}
if (IS_ERR(bh))
return false;
}
de = (struct ext4_dir_entry_2 *) (bh->b_data +
(offset & (sb->s_blocksize - 1)));
if (ext4_check_dir_entry(inode, NULL, de, bh,
bh->b_data, bh->b_size, offset) ||
le32_to_cpu(de->inode)) {
brelse(bh);
return false;
}
offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
}
brelse(bh);
return true;
}
static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
{
int retval;
struct inode *inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle = NULL;
if (unlikely(ext4_forced_shutdown(dir->i_sb)))
return -EIO;
/* Initialize quotas before so that eventual writes go in
* separate transaction */
retval = dquot_initialize(dir);
if (retval)
return retval;
retval = dquot_initialize(d_inode(dentry));
if (retval)
return retval;
retval = -ENOENT;
bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto end_rmdir;
inode = d_inode(dentry);
retval = -EFSCORRUPTED;
if (le32_to_cpu(de->inode) != inode->i_ino)
goto end_rmdir;
retval = -ENOTEMPTY;
if (!ext4_empty_dir(inode))
goto end_rmdir;
handle = ext4_journal_start(dir, EXT4_HT_DIR,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_rmdir;
}
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto end_rmdir;
if (!EXT4_DIR_LINK_EMPTY(inode))
ext4_warning_inode(inode,
"empty directory '%.*s' has too many links (%u)",
dentry->d_name.len, dentry->d_name.name,
inode->i_nlink);
inode_inc_iversion(inode);
clear_nlink(inode);
/* There's no need to set i_disksize: the fact that i_nlink is
* zero will ensure that the right thing happens during any
* recovery. */
inode->i_size = 0;
ext4_orphan_add(handle, inode);
dir->i_mtime = inode_set_ctime_current(dir);
inode_set_ctime_current(inode);
retval = ext4_mark_inode_dirty(handle, inode);
if (retval)
goto end_rmdir;
ext4_dec_count(dir);
ext4_update_dx_flag(dir);
ext4_fc_track_unlink(handle, dentry);
retval = ext4_mark_inode_dirty(handle, dir);
#if IS_ENABLED(CONFIG_UNICODE)
/* VFS negative dentries are incompatible with Encoding and
* Case-insensitiveness. Eventually we'll want avoid
* invalidating the dentries here, alongside with returning the
* negative dentries at ext4_lookup(), when it is better
* supported by the VFS for the CI case.
*/
if (IS_CASEFOLDED(dir))
d_invalidate(dentry);
#endif
end_rmdir:
brelse(bh);
if (handle)
ext4_journal_stop(handle);
return retval;
}
int __ext4_unlink(struct inode *dir, const struct qstr *d_name,
struct inode *inode,
struct dentry *dentry /* NULL during fast_commit recovery */)
{
int retval = -ENOENT;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
handle_t *handle;
int skip_remove_dentry = 0;
/*
* Keep this outside the transaction; it may have to set up the
* directory's encryption key, which isn't GFP_NOFS-safe.
*/
bh = ext4_find_entry(dir, d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
return -ENOENT;
if (le32_to_cpu(de->inode) != inode->i_ino) {
/*
* It's okay if we find dont find dentry which matches
* the inode. That's because it might have gotten
* renamed to a different inode number
*/
if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
skip_remove_dentry = 1;
else
goto out_bh;
}
handle = ext4_journal_start(dir, EXT4_HT_DIR,
EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
goto out_bh;
}
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
if (!skip_remove_dentry) {
retval = ext4_delete_entry(handle, dir, de, bh);
if (retval)
goto out_handle;
dir->i_mtime = inode_set_ctime_current(dir);
ext4_update_dx_flag(dir);
retval = ext4_mark_inode_dirty(handle, dir);
if (retval)
goto out_handle;
} else {
retval = 0;
}
if (inode->i_nlink == 0)
ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
d_name->len, d_name->name);
else
drop_nlink(inode);
if (!inode->i_nlink)
ext4_orphan_add(handle, inode);
inode_set_ctime_current(inode);
retval = ext4_mark_inode_dirty(handle, inode);
if (dentry && !retval)
ext4_fc_track_unlink(handle, dentry);
out_handle:
ext4_journal_stop(handle);
out_bh:
brelse(bh);
return retval;
}
static int ext4_unlink(struct inode *dir, struct dentry *dentry)
{
int retval;
if (unlikely(ext4_forced_shutdown(dir->i_sb)))
return -EIO;
trace_ext4_unlink_enter(dir, dentry);
/*
* Initialize quotas before so that eventual writes go
* in separate transaction
*/
retval = dquot_initialize(dir);
if (retval)
goto out_trace;
retval = dquot_initialize(d_inode(dentry));
if (retval)
goto out_trace;
retval = __ext4_unlink(dir, &dentry->d_name, d_inode(dentry), dentry);
#if IS_ENABLED(CONFIG_UNICODE)
/* VFS negative dentries are incompatible with Encoding and
* Case-insensitiveness. Eventually we'll want avoid
* invalidating the dentries here, alongside with returning the
* negative dentries at ext4_lookup(), when it is better
* supported by the VFS for the CI case.
*/
if (IS_CASEFOLDED(dir))
d_invalidate(dentry);
#endif
out_trace:
trace_ext4_unlink_exit(dentry, retval);
return retval;
}
static int ext4_init_symlink_block(handle_t *handle, struct inode *inode,
struct fscrypt_str *disk_link)
{
struct buffer_head *bh;
char *kaddr;
int err = 0;
bh = ext4_bread(handle, inode, 0, EXT4_GET_BLOCKS_CREATE);
if (IS_ERR(bh))
return PTR_ERR(bh);
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb, bh, EXT4_JTR_NONE);
if (err)
goto out;
kaddr = (char *)bh->b_data;
memcpy(kaddr, disk_link->name, disk_link->len);
inode->i_size = disk_link->len - 1;
EXT4_I(inode)->i_disksize = inode->i_size;
err = ext4_handle_dirty_metadata(handle, inode, bh);
out:
brelse(bh);
return err;
}
static int ext4_symlink(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, const char *symname)
{
handle_t *handle;
struct inode *inode;
int err, len = strlen(symname);
int credits;
struct fscrypt_str disk_link;
int retries = 0;
if (unlikely(ext4_forced_shutdown(dir->i_sb)))
return -EIO;
err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
&disk_link);
if (err)
return err;
err = dquot_initialize(dir);
if (err)
return err;
/*
* EXT4_INDEX_EXTRA_TRANS_BLOCKS for addition of entry into the
* directory. +3 for inode, inode bitmap, group descriptor allocation.
* EXT4_DATA_TRANS_BLOCKS for the data block allocation and
* modification.
*/
credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
retry:
inode = ext4_new_inode_start_handle(idmap, dir, S_IFLNK|S_IRWXUGO,
&dentry->d_name, 0, NULL,
EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
if (IS_ERR(inode)) {
if (handle)
ext4_journal_stop(handle);
err = PTR_ERR(inode);
goto out_retry;
}
if (IS_ENCRYPTED(inode)) {
err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
if (err)
goto err_drop_inode;
inode->i_op = &ext4_encrypted_symlink_inode_operations;
} else {
if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
inode->i_op = &ext4_symlink_inode_operations;
} else {
inode->i_op = &ext4_fast_symlink_inode_operations;
inode->i_link = (char *)&EXT4_I(inode)->i_data;
}
}
if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
/* alloc symlink block and fill it */
err = ext4_init_symlink_block(handle, inode, &disk_link);
if (err)
goto err_drop_inode;
} else {
/* clear the extent format for fast symlink */
ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
disk_link.len);
inode->i_size = disk_link.len - 1;
EXT4_I(inode)->i_disksize = inode->i_size;
}
err = ext4_add_nondir(handle, dentry, &inode);
if (handle)
ext4_journal_stop(handle);
iput(inode);
goto out_retry;
err_drop_inode:
clear_nlink(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_orphan_add(handle, inode);
unlock_new_inode(inode);
if (handle)
ext4_journal_stop(handle);
iput(inode);
out_retry:
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
if (disk_link.name != (unsigned char *)symname)
kfree(disk_link.name);
return err;
}
int __ext4_link(struct inode *dir, struct inode *inode, struct dentry *dentry)
{
handle_t *handle;
int err, retries = 0;
retry:
handle = ext4_journal_start(dir, EXT4_HT_DIR,
(EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
if (IS_DIRSYNC(dir))
ext4_handle_sync(handle);
inode_set_ctime_current(inode);
ext4_inc_count(inode);
ihold(inode);
err = ext4_add_entry(handle, dentry, inode);
if (!err) {
err = ext4_mark_inode_dirty(handle, inode);
/* this can happen only for tmpfile being
* linked the first time
*/
if (inode->i_nlink == 1)
ext4_orphan_del(handle, inode);
d_instantiate(dentry, inode);
ext4_fc_track_link(handle, dentry);
} else {
drop_nlink(inode);
iput(inode);
}
ext4_journal_stop(handle);
if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
goto retry;
return err;
}
static int ext4_link(struct dentry *old_dentry,
struct inode *dir, struct dentry *dentry)
{
struct inode *inode = d_inode(old_dentry);
int err;
if (inode->i_nlink >= EXT4_LINK_MAX)
return -EMLINK;
err = fscrypt_prepare_link(old_dentry, dir, dentry);
if (err)
return err;
if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
(!projid_eq(EXT4_I(dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)))
return -EXDEV;
err = dquot_initialize(dir);
if (err)
return err;
return __ext4_link(dir, inode, dentry);
}
/*
* Try to find buffer head where contains the parent block.
* It should be the inode block if it is inlined or the 1st block
* if it is a normal dir.
*/
static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
struct inode *inode,
int *retval,
struct ext4_dir_entry_2 **parent_de,
int *inlined)
{
struct buffer_head *bh;
if (!ext4_has_inline_data(inode)) {
struct ext4_dir_entry_2 *de;
unsigned int offset;
/* The first directory block must not be a hole, so
* treat it as DIRENT_HTREE
*/
bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
if (IS_ERR(bh)) {
*retval = PTR_ERR(bh);
return NULL;
}
de = (struct ext4_dir_entry_2 *) bh->b_data;
if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
bh->b_size, 0) ||
le32_to_cpu(de->inode) != inode->i_ino ||
strcmp(".", de->name)) {
EXT4_ERROR_INODE(inode, "directory missing '.'");
brelse(bh);
*retval = -EFSCORRUPTED;
return NULL;
}
offset = ext4_rec_len_from_disk(de->rec_len,
inode->i_sb->s_blocksize);
de = ext4_next_entry(de, inode->i_sb->s_blocksize);
if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
bh->b_size, offset) ||
le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
EXT4_ERROR_INODE(inode, "directory missing '..'");
brelse(bh);
*retval = -EFSCORRUPTED;
return NULL;
}
*parent_de = de;
return bh;
}
*inlined = 1;
return ext4_get_first_inline_block(inode, parent_de, retval);
}
struct ext4_renament {
struct inode *dir;
struct dentry *dentry;
struct inode *inode;
bool is_dir;
int dir_nlink_delta;
/* entry for "dentry" */
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
int inlined;
/* entry for ".." in inode if it's a directory */
struct buffer_head *dir_bh;
struct ext4_dir_entry_2 *parent_de;
int dir_inlined;
};
static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
{
int retval;
ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
&retval, &ent->parent_de,
&ent->dir_inlined);
if (!ent->dir_bh)
return retval;
if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
return -EFSCORRUPTED;
BUFFER_TRACE(ent->dir_bh, "get_write_access");
return ext4_journal_get_write_access(handle, ent->dir->i_sb,
ent->dir_bh, EXT4_JTR_NONE);
}
static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
unsigned dir_ino)
{
int retval;
ent->parent_de->inode = cpu_to_le32(dir_ino);
BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
if (!ent->dir_inlined) {
if (is_dx(ent->inode)) {
retval = ext4_handle_dirty_dx_node(handle,
ent->inode,
ent->dir_bh);
} else {
retval = ext4_handle_dirty_dirblock(handle, ent->inode,
ent->dir_bh);
}
} else {
retval = ext4_mark_inode_dirty(handle, ent->inode);
}
if (retval) {
ext4_std_error(ent->dir->i_sb, retval);
return retval;
}
return 0;
}
static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
unsigned ino, unsigned file_type)
{
int retval, retval2;
BUFFER_TRACE(ent->bh, "get write access");
retval = ext4_journal_get_write_access(handle, ent->dir->i_sb, ent->bh,
EXT4_JTR_NONE);
if (retval)
return retval;
ent->de->inode = cpu_to_le32(ino);
if (ext4_has_feature_filetype(ent->dir->i_sb))
ent->de->file_type = file_type;
inode_inc_iversion(ent->dir);
ent->dir->i_mtime = inode_set_ctime_current(ent->dir);
retval = ext4_mark_inode_dirty(handle, ent->dir);
BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
if (!ent->inlined) {
retval2 = ext4_handle_dirty_dirblock(handle, ent->dir, ent->bh);
if (unlikely(retval2)) {
ext4_std_error(ent->dir->i_sb, retval2);
return retval2;
}
}
return retval;
}
static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
unsigned ino, unsigned file_type)
{
struct ext4_renament old = *ent;
int retval = 0;
/*
* old->de could have moved from under us during make indexed dir,
* so the old->de may no longer valid and need to find it again
* before reset old inode info.
*/
old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
&old.inlined);
if (IS_ERR(old.bh))
retval = PTR_ERR(old.bh);
if (!old.bh)
retval = -ENOENT;
if (retval) {
ext4_std_error(old.dir->i_sb, retval);
return;
}
ext4_setent(handle, &old, ino, file_type);
brelse(old.bh);
}
static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
const struct qstr *d_name)
{
int retval = -ENOENT;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
bh = ext4_find_entry(dir, d_name, &de, NULL);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (bh) {
retval = ext4_delete_entry(handle, dir, de, bh);
brelse(bh);
}
return retval;
}
static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
int force_reread)
{
int retval;
/*
* ent->de could have moved from under us during htree split, so make
* sure that we are deleting the right entry. We might also be pointing
* to a stale entry in the unused part of ent->bh so just checking inum
* and the name isn't enough.
*/
if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
ent->de->name_len != ent->dentry->d_name.len ||
strncmp(ent->de->name, ent->dentry->d_name.name,
ent->de->name_len) ||
force_reread) {
retval = ext4_find_delete_entry(handle, ent->dir,
&ent->dentry->d_name);
} else {
retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
if (retval == -ENOENT) {
retval = ext4_find_delete_entry(handle, ent->dir,
&ent->dentry->d_name);
}
}
if (retval) {
ext4_warning_inode(ent->dir,
"Deleting old file: nlink %d, error=%d",
ent->dir->i_nlink, retval);
}
}
static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
{
if (ent->dir_nlink_delta) {
if (ent->dir_nlink_delta == -1)
ext4_dec_count(ent->dir);
else
ext4_inc_count(ent->dir);
ext4_mark_inode_dirty(handle, ent->dir);
}
}
static struct inode *ext4_whiteout_for_rename(struct mnt_idmap *idmap,
struct ext4_renament *ent,
int credits, handle_t **h)
{
struct inode *wh;
handle_t *handle;
int retries = 0;
/*
* for inode block, sb block, group summaries,
* and inode bitmap
*/
credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
EXT4_XATTR_TRANS_BLOCKS + 4);
retry:
wh = ext4_new_inode_start_handle(idmap, ent->dir,
S_IFCHR | WHITEOUT_MODE,
&ent->dentry->d_name, 0, NULL,
EXT4_HT_DIR, credits);
handle = ext4_journal_current_handle();
if (IS_ERR(wh)) {
if (handle)
ext4_journal_stop(handle);
if (PTR_ERR(wh) == -ENOSPC &&
ext4_should_retry_alloc(ent->dir->i_sb, &retries))
goto retry;
} else {
*h = handle;
init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
wh->i_op = &ext4_special_inode_operations;
}
return wh;
}
/*
* Anybody can rename anything with this: the permission checks are left to the
* higher-level routines.
*
* n.b. old_{dentry,inode) refers to the source dentry/inode
* while new_{dentry,inode) refers to the destination dentry/inode
* This comes from rename(const char *oldpath, const char *newpath)
*/
static int ext4_rename(struct mnt_idmap *idmap, struct inode *old_dir,
struct dentry *old_dentry, struct inode *new_dir,
struct dentry *new_dentry, unsigned int flags)
{
handle_t *handle = NULL;
struct ext4_renament old = {
.dir = old_dir,
.dentry = old_dentry,
.inode = d_inode(old_dentry),
};
struct ext4_renament new = {
.dir = new_dir,
.dentry = new_dentry,
.inode = d_inode(new_dentry),
};
int force_reread;
int retval;
struct inode *whiteout = NULL;
int credits;
u8 old_file_type;
if (new.inode && new.inode->i_nlink == 0) {
EXT4_ERROR_INODE(new.inode,
"target of rename is already freed");
return -EFSCORRUPTED;
}
if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
(!projid_eq(EXT4_I(new_dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)))
return -EXDEV;
retval = dquot_initialize(old.dir);
if (retval)
return retval;
retval = dquot_initialize(old.inode);
if (retval)
return retval;
retval = dquot_initialize(new.dir);
if (retval)
return retval;
/* Initialize quotas before so that eventual writes go
* in separate transaction */
if (new.inode) {
retval = dquot_initialize(new.inode);
if (retval)
return retval;
}
old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de,
&old.inlined);
if (IS_ERR(old.bh))
return PTR_ERR(old.bh);
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
retval = -ENOENT;
if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
goto release_bh;
new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
&new.de, &new.inlined);
if (IS_ERR(new.bh)) {
retval = PTR_ERR(new.bh);
new.bh = NULL;
goto release_bh;
}
if (new.bh) {
if (!new.inode) {
brelse(new.bh);
new.bh = NULL;
}
}
if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
ext4_alloc_da_blocks(old.inode);
credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
if (!(flags & RENAME_WHITEOUT)) {
handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
goto release_bh;
}
} else {
whiteout = ext4_whiteout_for_rename(idmap, &old, credits, &handle);
if (IS_ERR(whiteout)) {
retval = PTR_ERR(whiteout);
goto release_bh;
}
}
old_file_type = old.de->file_type;
if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
ext4_handle_sync(handle);
if (S_ISDIR(old.inode->i_mode)) {
if (new.inode) {
retval = -ENOTEMPTY;
if (!ext4_empty_dir(new.inode))
goto end_rename;
} else {
retval = -EMLINK;
if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
goto end_rename;
}
retval = ext4_rename_dir_prepare(handle, &old);
if (retval)
goto end_rename;
}
/*
* If we're renaming a file within an inline_data dir and adding or
* setting the new dirent causes a conversion from inline_data to
* extents/blockmap, we need to force the dirent delete code to
* re-read the directory, or else we end up trying to delete a dirent
* from what is now the extent tree root (or a block map).
*/
force_reread = (new.dir->i_ino == old.dir->i_ino &&
ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
if (whiteout) {
/*
* Do this before adding a new entry, so the old entry is sure
* to be still pointing to the valid old entry.
*/
retval = ext4_setent(handle, &old, whiteout->i_ino,
EXT4_FT_CHRDEV);
if (retval)
goto end_rename;
retval = ext4_mark_inode_dirty(handle, whiteout);
if (unlikely(retval))
goto end_rename;
}
if (!new.bh) {
retval = ext4_add_entry(handle, new.dentry, old.inode);
if (retval)
goto end_rename;
} else {
retval = ext4_setent(handle, &new,
old.inode->i_ino, old_file_type);
if (retval)
goto end_rename;
}
if (force_reread)
force_reread = !ext4_test_inode_flag(new.dir,
EXT4_INODE_INLINE_DATA);
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
inode_set_ctime_current(old.inode);
retval = ext4_mark_inode_dirty(handle, old.inode);
if (unlikely(retval))
goto end_rename;
if (!whiteout) {
/*
* ok, that's it
*/
ext4_rename_delete(handle, &old, force_reread);
}
if (new.inode) {
ext4_dec_count(new.inode);
inode_set_ctime_current(new.inode);
}
old.dir->i_mtime = inode_set_ctime_current(old.dir);
ext4_update_dx_flag(old.dir);
if (old.dir_bh) {
retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
if (retval)
goto end_rename;
ext4_dec_count(old.dir);
if (new.inode) {
/* checked ext4_empty_dir above, can't have another
* parent, ext4_dec_count() won't work for many-linked
* dirs */
clear_nlink(new.inode);
} else {
ext4_inc_count(new.dir);
ext4_update_dx_flag(new.dir);
retval = ext4_mark_inode_dirty(handle, new.dir);
if (unlikely(retval))
goto end_rename;
}
}
retval = ext4_mark_inode_dirty(handle, old.dir);
if (unlikely(retval))
goto end_rename;
if (S_ISDIR(old.inode->i_mode)) {
/*
* We disable fast commits here that's because the
* replay code is not yet capable of changing dot dot
* dirents in directories.
*/
ext4_fc_mark_ineligible(old.inode->i_sb,
EXT4_FC_REASON_RENAME_DIR, handle);
} else {
struct super_block *sb = old.inode->i_sb;
if (new.inode)
ext4_fc_track_unlink(handle, new.dentry);
if (test_opt2(sb, JOURNAL_FAST_COMMIT) &&
!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
!(ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE))) {
__ext4_fc_track_link(handle, old.inode, new.dentry);
__ext4_fc_track_unlink(handle, old.inode, old.dentry);
if (whiteout)
__ext4_fc_track_create(handle, whiteout,
old.dentry);
}
}
if (new.inode) {
retval = ext4_mark_inode_dirty(handle, new.inode);
if (unlikely(retval))
goto end_rename;
if (!new.inode->i_nlink)
ext4_orphan_add(handle, new.inode);
}
retval = 0;
end_rename:
if (whiteout) {
if (retval) {
ext4_resetent(handle, &old,
old.inode->i_ino, old_file_type);
drop_nlink(whiteout);
ext4_mark_inode_dirty(handle, whiteout);
ext4_orphan_add(handle, whiteout);
}
unlock_new_inode(whiteout);
ext4_journal_stop(handle);
iput(whiteout);
} else {
ext4_journal_stop(handle);
}
release_bh:
brelse(old.dir_bh);
brelse(old.bh);
brelse(new.bh);
return retval;
}
static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
handle_t *handle = NULL;
struct ext4_renament old = {
.dir = old_dir,
.dentry = old_dentry,
.inode = d_inode(old_dentry),
};
struct ext4_renament new = {
.dir = new_dir,
.dentry = new_dentry,
.inode = d_inode(new_dentry),
};
u8 new_file_type;
int retval;
if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
!projid_eq(EXT4_I(new_dir)->i_projid,
EXT4_I(old_dentry->d_inode)->i_projid)) ||
(ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
!projid_eq(EXT4_I(old_dir)->i_projid,
EXT4_I(new_dentry->d_inode)->i_projid)))
return -EXDEV;
retval = dquot_initialize(old.dir);
if (retval)
return retval;
retval = dquot_initialize(new.dir);
if (retval)
return retval;
old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
&old.de, &old.inlined);
if (IS_ERR(old.bh))
return PTR_ERR(old.bh);
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
retval = -ENOENT;
if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
goto end_rename;
new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
&new.de, &new.inlined);
if (IS_ERR(new.bh)) {
retval = PTR_ERR(new.bh);
new.bh = NULL;
goto end_rename;
}
/* RENAME_EXCHANGE case: old *and* new must both exist */
if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
goto end_rename;
handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
(2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
if (IS_ERR(handle)) {
retval = PTR_ERR(handle);
handle = NULL;
goto end_rename;
}
if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
ext4_handle_sync(handle);
if (S_ISDIR(old.inode->i_mode)) {
old.is_dir = true;
retval = ext4_rename_dir_prepare(handle, &old);
if (retval)
goto end_rename;
}
if (S_ISDIR(new.inode->i_mode)) {
new.is_dir = true;
retval = ext4_rename_dir_prepare(handle, &new);
if (retval)
goto end_rename;
}
/*
* Other than the special case of overwriting a directory, parents'
* nlink only needs to be modified if this is a cross directory rename.
*/
if (old.dir != new.dir && old.is_dir != new.is_dir) {
old.dir_nlink_delta = old.is_dir ? -1 : 1;
new.dir_nlink_delta = -old.dir_nlink_delta;
retval = -EMLINK;
if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
(new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
goto end_rename;
}
new_file_type = new.de->file_type;
retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
if (retval)
goto end_rename;
retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
if (retval)
goto end_rename;
/*
* Like most other Unix systems, set the ctime for inodes on a
* rename.
*/
inode_set_ctime_current(old.inode);
inode_set_ctime_current(new.inode);
retval = ext4_mark_inode_dirty(handle, old.inode);
if (unlikely(retval))
goto end_rename;
retval = ext4_mark_inode_dirty(handle, new.inode);
if (unlikely(retval))
goto end_rename;
ext4_fc_mark_ineligible(new.inode->i_sb,
EXT4_FC_REASON_CROSS_RENAME, handle);
if (old.dir_bh) {
retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
if (retval)
goto end_rename;
}
if (new.dir_bh) {
retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
if (retval)
goto end_rename;
}
ext4_update_dir_count(handle, &old);
ext4_update_dir_count(handle, &new);
retval = 0;
end_rename:
brelse(old.dir_bh);
brelse(new.dir_bh);
brelse(old.bh);
brelse(new.bh);
if (handle)
ext4_journal_stop(handle);
return retval;
}
static int ext4_rename2(struct mnt_idmap *idmap,
struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
unsigned int flags)
{
int err;
if (unlikely(ext4_forced_shutdown(old_dir->i_sb)))
return -EIO;
if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
return -EINVAL;
err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (err)
return err;
if (flags & RENAME_EXCHANGE) {
return ext4_cross_rename(old_dir, old_dentry,
new_dir, new_dentry);
}
return ext4_rename(idmap, old_dir, old_dentry, new_dir, new_dentry, flags);
}
/*
* directories can handle most operations...
*/
const struct inode_operations ext4_dir_inode_operations = {
.create = ext4_create,
.lookup = ext4_lookup,
.link = ext4_link,
.unlink = ext4_unlink,
.symlink = ext4_symlink,
.mkdir = ext4_mkdir,
.rmdir = ext4_rmdir,
.mknod = ext4_mknod,
.tmpfile = ext4_tmpfile,
.rename = ext4_rename2,
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
.get_inode_acl = ext4_get_acl,
.set_acl = ext4_set_acl,
.fiemap = ext4_fiemap,
.fileattr_get = ext4_fileattr_get,
.fileattr_set = ext4_fileattr_set,
};
const struct inode_operations ext4_special_inode_operations = {
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
.get_inode_acl = ext4_get_acl,
.set_acl = ext4_set_acl,
};
| linux-master | fs/ext4/namei.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/xattr_hurd.c
* Handler for extended gnu attributes for the Hurd.
*
* Copyright (C) 2001 by Andreas Gruenbacher, <[email protected]>
* Copyright (C) 2020 by Jan (janneke) Nieuwenhuizen, <[email protected]>
*/
#include <linux/init.h>
#include <linux/string.h>
#include "ext4.h"
#include "xattr.h"
static bool
ext4_xattr_hurd_list(struct dentry *dentry)
{
return test_opt(dentry->d_sb, XATTR_USER);
}
static int
ext4_xattr_hurd_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *buffer, size_t size)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_HURD,
name, buffer, size);
}
static int
ext4_xattr_hurd_set(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)
{
if (!test_opt(inode->i_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_set(inode, EXT4_XATTR_INDEX_HURD,
name, value, size, flags);
}
const struct xattr_handler ext4_xattr_hurd_handler = {
.prefix = XATTR_HURD_PREFIX,
.list = ext4_xattr_hurd_list,
.get = ext4_xattr_hurd_get,
.set = ext4_xattr_hurd_set,
};
| linux-master | fs/ext4/xattr_hurd.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <[email protected]>
*/
#include <linux/quotaops.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext4_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext4_acl_header))
return ERR_PTR(-EINVAL);
if (((ext4_acl_header *)value)->a_version !=
cpu_to_le32(EXT4_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext4_acl_header);
count = ext4_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
ext4_acl_entry *entry =
(ext4_acl_entry *)value;
if ((char *)value + sizeof(ext4_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext4_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext4_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext4_acl_header *ext_acl;
char *e;
size_t n;
*size = ext4_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext4_acl_header) + acl->a_count *
sizeof(ext4_acl_entry), GFP_NOFS);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT4_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext4_acl_header);
for (n = 0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext4_acl_entry *entry = (ext4_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch (acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext4_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext4_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext4_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* Inode operation get_posix_acl().
*
* inode->i_rwsem: don't care
*/
struct posix_acl *
ext4_get_acl(struct inode *inode, int type, bool rcu)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
if (rcu)
return ERR_PTR(-ECHILD);
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext4_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext4_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext4_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* Set the access or default ACL of an inode.
*
* inode->i_rwsem: down unless called from ext4_new_inode
*/
static int
__ext4_set_acl(handle_t *handle, struct inode *inode, int type,
struct posix_acl *acl, int xattr_flags)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext4_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext4_xattr_set_handle(handle, inode, name_index, "",
value, size, xattr_flags);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
int
ext4_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
struct posix_acl *acl, int type)
{
handle_t *handle;
int error, credits, retries = 0;
size_t acl_size = acl ? ext4_acl_size(acl->a_count) : 0;
struct inode *inode = d_inode(dentry);
umode_t mode = inode->i_mode;
int update_mode = 0;
error = dquot_initialize(inode);
if (error)
return error;
retry:
error = ext4_xattr_set_credits(inode, acl_size, false /* is_create */,
&credits);
if (error)
return error;
handle = ext4_journal_start(inode, EXT4_HT_XATTR, credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
if ((type == ACL_TYPE_ACCESS) && acl) {
error = posix_acl_update_mode(idmap, inode, &mode, &acl);
if (error)
goto out_stop;
if (mode != inode->i_mode)
update_mode = 1;
}
error = __ext4_set_acl(handle, inode, type, acl, 0 /* xattr_flags */);
if (!error && update_mode) {
inode->i_mode = mode;
inode_set_ctime_current(inode);
error = ext4_mark_inode_dirty(handle, inode);
}
out_stop:
ext4_journal_stop(handle);
if (error == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext4_new_inode.
*
* dir->i_rwsem: down
* inode->i_rwsem: up (access to inode is still exclusive)
*/
int
ext4_init_acl(handle_t *handle, struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = __ext4_set_acl(handle, inode, ACL_TYPE_DEFAULT,
default_acl, XATTR_CREATE);
posix_acl_release(default_acl);
} else {
inode->i_default_acl = NULL;
}
if (acl) {
if (!error)
error = __ext4_set_acl(handle, inode, ACL_TYPE_ACCESS,
acl, XATTR_CREATE);
posix_acl_release(acl);
} else {
inode->i_acl = NULL;
}
return error;
}
| linux-master | fs/ext4/acl.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/symlink.c
*
* Only fast symlinks left here - the rest is done by generic code. AV, 1999
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/symlink.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4 symlink handling code
*/
#include <linux/fs.h>
#include <linux/namei.h>
#include "ext4.h"
#include "xattr.h"
static const char *ext4_encrypted_get_link(struct dentry *dentry,
struct inode *inode,
struct delayed_call *done)
{
struct buffer_head *bh = NULL;
const void *caddr;
unsigned int max_size;
const char *paddr;
if (!dentry)
return ERR_PTR(-ECHILD);
if (ext4_inode_is_fast_symlink(inode)) {
caddr = EXT4_I(inode)->i_data;
max_size = sizeof(EXT4_I(inode)->i_data);
} else {
bh = ext4_bread(NULL, inode, 0, 0);
if (IS_ERR(bh))
return ERR_CAST(bh);
if (!bh) {
EXT4_ERROR_INODE(inode, "bad symlink.");
return ERR_PTR(-EFSCORRUPTED);
}
caddr = bh->b_data;
max_size = inode->i_sb->s_blocksize;
}
paddr = fscrypt_get_symlink(inode, caddr, max_size, done);
brelse(bh);
return paddr;
}
static int ext4_encrypted_symlink_getattr(struct mnt_idmap *idmap,
const struct path *path,
struct kstat *stat, u32 request_mask,
unsigned int query_flags)
{
ext4_getattr(idmap, path, stat, request_mask, query_flags);
return fscrypt_symlink_getattr(path, stat);
}
static void ext4_free_link(void *bh)
{
brelse(bh);
}
static const char *ext4_get_link(struct dentry *dentry, struct inode *inode,
struct delayed_call *callback)
{
struct buffer_head *bh;
char *inline_link;
/*
* Create a new inlined symlink is not supported, just provide a
* method to read the leftovers.
*/
if (ext4_has_inline_data(inode)) {
if (!dentry)
return ERR_PTR(-ECHILD);
inline_link = ext4_read_inline_link(inode);
if (!IS_ERR(inline_link))
set_delayed_call(callback, kfree_link, inline_link);
return inline_link;
}
if (!dentry) {
bh = ext4_getblk(NULL, inode, 0, EXT4_GET_BLOCKS_CACHED_NOWAIT);
if (IS_ERR(bh))
return ERR_CAST(bh);
if (!bh || !ext4_buffer_uptodate(bh))
return ERR_PTR(-ECHILD);
} else {
bh = ext4_bread(NULL, inode, 0, 0);
if (IS_ERR(bh))
return ERR_CAST(bh);
if (!bh) {
EXT4_ERROR_INODE(inode, "bad symlink.");
return ERR_PTR(-EFSCORRUPTED);
}
}
set_delayed_call(callback, ext4_free_link, bh);
nd_terminate_link(bh->b_data, inode->i_size,
inode->i_sb->s_blocksize - 1);
return bh->b_data;
}
const struct inode_operations ext4_encrypted_symlink_inode_operations = {
.get_link = ext4_encrypted_get_link,
.setattr = ext4_setattr,
.getattr = ext4_encrypted_symlink_getattr,
.listxattr = ext4_listxattr,
};
const struct inode_operations ext4_symlink_inode_operations = {
.get_link = ext4_get_link,
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
};
const struct inode_operations ext4_fast_symlink_inode_operations = {
.get_link = simple_get_link,
.setattr = ext4_setattr,
.getattr = ext4_getattr,
.listxattr = ext4_listxattr,
};
| linux-master | fs/ext4/symlink.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/file.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/file.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4 fs regular file handling primitives
*
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* ([email protected])
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/iomap.h>
#include <linux/mount.h>
#include <linux/path.h>
#include <linux/dax.h>
#include <linux/quotaops.h>
#include <linux/pagevec.h>
#include <linux/uio.h>
#include <linux/mman.h>
#include <linux/backing-dev.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "truncate.h"
/*
* Returns %true if the given DIO request should be attempted with DIO, or
* %false if it should fall back to buffered I/O.
*
* DIO isn't well specified; when it's unsupported (either due to the request
* being misaligned, or due to the file not supporting DIO at all), filesystems
* either fall back to buffered I/O or return EINVAL. For files that don't use
* any special features like encryption or verity, ext4 has traditionally
* returned EINVAL for misaligned DIO. iomap_dio_rw() uses this convention too.
* In this case, we should attempt the DIO, *not* fall back to buffered I/O.
*
* In contrast, in cases where DIO is unsupported due to ext4 features, ext4
* traditionally falls back to buffered I/O.
*
* This function implements the traditional ext4 behavior in all these cases.
*/
static bool ext4_should_use_dio(struct kiocb *iocb, struct iov_iter *iter)
{
struct inode *inode = file_inode(iocb->ki_filp);
u32 dio_align = ext4_dio_alignment(inode);
if (dio_align == 0)
return false;
if (dio_align == 1)
return true;
return IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(iter), dio_align);
}
static ssize_t ext4_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
ssize_t ret;
struct inode *inode = file_inode(iocb->ki_filp);
if (iocb->ki_flags & IOCB_NOWAIT) {
if (!inode_trylock_shared(inode))
return -EAGAIN;
} else {
inode_lock_shared(inode);
}
if (!ext4_should_use_dio(iocb, to)) {
inode_unlock_shared(inode);
/*
* Fallback to buffered I/O if the operation being performed on
* the inode is not supported by direct I/O. The IOCB_DIRECT
* flag needs to be cleared here in order to ensure that the
* direct I/O path within generic_file_read_iter() is not
* taken.
*/
iocb->ki_flags &= ~IOCB_DIRECT;
return generic_file_read_iter(iocb, to);
}
ret = iomap_dio_rw(iocb, to, &ext4_iomap_ops, NULL, 0, NULL, 0);
inode_unlock_shared(inode);
file_accessed(iocb->ki_filp);
return ret;
}
#ifdef CONFIG_FS_DAX
static ssize_t ext4_dax_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct inode *inode = file_inode(iocb->ki_filp);
ssize_t ret;
if (iocb->ki_flags & IOCB_NOWAIT) {
if (!inode_trylock_shared(inode))
return -EAGAIN;
} else {
inode_lock_shared(inode);
}
/*
* Recheck under inode lock - at this point we are sure it cannot
* change anymore
*/
if (!IS_DAX(inode)) {
inode_unlock_shared(inode);
/* Fallback to buffered IO in case we cannot support DAX */
return generic_file_read_iter(iocb, to);
}
ret = dax_iomap_rw(iocb, to, &ext4_iomap_ops);
inode_unlock_shared(inode);
file_accessed(iocb->ki_filp);
return ret;
}
#endif
static ssize_t ext4_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct inode *inode = file_inode(iocb->ki_filp);
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
if (!iov_iter_count(to))
return 0; /* skip atime */
#ifdef CONFIG_FS_DAX
if (IS_DAX(inode))
return ext4_dax_read_iter(iocb, to);
#endif
if (iocb->ki_flags & IOCB_DIRECT)
return ext4_dio_read_iter(iocb, to);
return generic_file_read_iter(iocb, to);
}
static ssize_t ext4_file_splice_read(struct file *in, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len, unsigned int flags)
{
struct inode *inode = file_inode(in);
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
return filemap_splice_read(in, ppos, pipe, len, flags);
}
/*
* Called when an inode is released. Note that this is different
* from ext4_file_open: open gets called at every open, but release
* gets called only when /all/ the files are closed.
*/
static int ext4_release_file(struct inode *inode, struct file *filp)
{
if (ext4_test_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE)) {
ext4_alloc_da_blocks(inode);
ext4_clear_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
}
/* if we are the last writer on the inode, drop the block reservation */
if ((filp->f_mode & FMODE_WRITE) &&
(atomic_read(&inode->i_writecount) == 1) &&
!EXT4_I(inode)->i_reserved_data_blocks) {
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode, 0);
up_write(&EXT4_I(inode)->i_data_sem);
}
if (is_dx(inode) && filp->private_data)
ext4_htree_free_dir_info(filp->private_data);
return 0;
}
/*
* This tests whether the IO in question is block-aligned or not.
* Ext4 utilizes unwritten extents when hole-filling during direct IO, and they
* are converted to written only after the IO is complete. Until they are
* mapped, these blocks appear as holes, so dio_zero_block() will assume that
* it needs to zero out portions of the start and/or end block. If 2 AIO
* threads are at work on the same unwritten block, they must be synchronized
* or one thread will zero the other's data, causing corruption.
*/
static bool
ext4_unaligned_io(struct inode *inode, struct iov_iter *from, loff_t pos)
{
struct super_block *sb = inode->i_sb;
unsigned long blockmask = sb->s_blocksize - 1;
if ((pos | iov_iter_alignment(from)) & blockmask)
return true;
return false;
}
static bool
ext4_extending_io(struct inode *inode, loff_t offset, size_t len)
{
if (offset + len > i_size_read(inode) ||
offset + len > EXT4_I(inode)->i_disksize)
return true;
return false;
}
/* Is IO overwriting allocated or initialized blocks? */
static bool ext4_overwrite_io(struct inode *inode,
loff_t pos, loff_t len, bool *unwritten)
{
struct ext4_map_blocks map;
unsigned int blkbits = inode->i_blkbits;
int err, blklen;
if (pos + len > i_size_read(inode))
return false;
map.m_lblk = pos >> blkbits;
map.m_len = EXT4_MAX_BLOCKS(len, pos, blkbits);
blklen = map.m_len;
err = ext4_map_blocks(NULL, inode, &map, 0);
if (err != blklen)
return false;
/*
* 'err==len' means that all of the blocks have been preallocated,
* regardless of whether they have been initialized or not. We need to
* check m_flags to distinguish the unwritten extents.
*/
*unwritten = !(map.m_flags & EXT4_MAP_MAPPED);
return true;
}
static ssize_t ext4_generic_write_checks(struct kiocb *iocb,
struct iov_iter *from)
{
struct inode *inode = file_inode(iocb->ki_filp);
ssize_t ret;
if (unlikely(IS_IMMUTABLE(inode)))
return -EPERM;
ret = generic_write_checks(iocb, from);
if (ret <= 0)
return ret;
/*
* If we have encountered a bitmap-format file, the size limit
* is smaller than s_maxbytes, which is for extent-mapped files.
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
if (iocb->ki_pos >= sbi->s_bitmap_maxbytes)
return -EFBIG;
iov_iter_truncate(from, sbi->s_bitmap_maxbytes - iocb->ki_pos);
}
return iov_iter_count(from);
}
static ssize_t ext4_write_checks(struct kiocb *iocb, struct iov_iter *from)
{
ssize_t ret, count;
count = ext4_generic_write_checks(iocb, from);
if (count <= 0)
return count;
ret = file_modified(iocb->ki_filp);
if (ret)
return ret;
return count;
}
static ssize_t ext4_buffered_write_iter(struct kiocb *iocb,
struct iov_iter *from)
{
ssize_t ret;
struct inode *inode = file_inode(iocb->ki_filp);
if (iocb->ki_flags & IOCB_NOWAIT)
return -EOPNOTSUPP;
inode_lock(inode);
ret = ext4_write_checks(iocb, from);
if (ret <= 0)
goto out;
ret = generic_perform_write(iocb, from);
out:
inode_unlock(inode);
if (unlikely(ret <= 0))
return ret;
return generic_write_sync(iocb, ret);
}
static ssize_t ext4_handle_inode_extension(struct inode *inode, loff_t offset,
ssize_t written, size_t count)
{
handle_t *handle;
bool truncate = false;
u8 blkbits = inode->i_blkbits;
ext4_lblk_t written_blk, end_blk;
int ret;
/*
* Note that EXT4_I(inode)->i_disksize can get extended up to
* inode->i_size while the I/O was running due to writeback of delalloc
* blocks. But, the code in ext4_iomap_alloc() is careful to use
* zeroed/unwritten extents if this is possible; thus we won't leave
* uninitialized blocks in a file even if we didn't succeed in writing
* as much as we intended.
*/
WARN_ON_ONCE(i_size_read(inode) < EXT4_I(inode)->i_disksize);
if (offset + count <= EXT4_I(inode)->i_disksize) {
/*
* We need to ensure that the inode is removed from the orphan
* list if it has been added prematurely, due to writeback of
* delalloc blocks.
*/
if (!list_empty(&EXT4_I(inode)->i_orphan) && inode->i_nlink) {
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle)) {
ext4_orphan_del(NULL, inode);
return PTR_ERR(handle);
}
ext4_orphan_del(handle, inode);
ext4_journal_stop(handle);
}
return written;
}
if (written < 0)
goto truncate;
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle)) {
written = PTR_ERR(handle);
goto truncate;
}
if (ext4_update_inode_size(inode, offset + written)) {
ret = ext4_mark_inode_dirty(handle, inode);
if (unlikely(ret)) {
written = ret;
ext4_journal_stop(handle);
goto truncate;
}
}
/*
* We may need to truncate allocated but not written blocks beyond EOF.
*/
written_blk = ALIGN(offset + written, 1 << blkbits);
end_blk = ALIGN(offset + count, 1 << blkbits);
if (written_blk < end_blk && ext4_can_truncate(inode))
truncate = true;
/*
* Remove the inode from the orphan list if it has been extended and
* everything went OK.
*/
if (!truncate && inode->i_nlink)
ext4_orphan_del(handle, inode);
ext4_journal_stop(handle);
if (truncate) {
truncate:
ext4_truncate_failed_write(inode);
/*
* If the truncate operation failed early, then the inode may
* still be on the orphan list. In that case, we need to try
* remove the inode from the in-memory linked list.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
return written;
}
static int ext4_dio_write_end_io(struct kiocb *iocb, ssize_t size,
int error, unsigned int flags)
{
loff_t pos = iocb->ki_pos;
struct inode *inode = file_inode(iocb->ki_filp);
if (error)
return error;
if (size && flags & IOMAP_DIO_UNWRITTEN) {
error = ext4_convert_unwritten_extents(NULL, inode, pos, size);
if (error < 0)
return error;
}
/*
* If we are extending the file, we have to update i_size here before
* page cache gets invalidated in iomap_dio_rw(). Otherwise racing
* buffered reads could zero out too much from page cache pages. Update
* of on-disk size will happen later in ext4_dio_write_iter() where
* we have enough information to also perform orphan list handling etc.
* Note that we perform all extending writes synchronously under
* i_rwsem held exclusively so i_size update is safe here in that case.
* If the write was not extending, we cannot see pos > i_size here
* because operations reducing i_size like truncate wait for all
* outstanding DIO before updating i_size.
*/
pos += size;
if (pos > i_size_read(inode))
i_size_write(inode, pos);
return 0;
}
static const struct iomap_dio_ops ext4_dio_write_ops = {
.end_io = ext4_dio_write_end_io,
};
/*
* The intention here is to start with shared lock acquired then see if any
* condition requires an exclusive inode lock. If yes, then we restart the
* whole operation by releasing the shared lock and acquiring exclusive lock.
*
* - For unaligned_io we never take shared lock as it may cause data corruption
* when two unaligned IO tries to modify the same block e.g. while zeroing.
*
* - For extending writes case we don't take the shared lock, since it requires
* updating inode i_disksize and/or orphan handling with exclusive lock.
*
* - shared locking will only be true mostly with overwrites, including
* initialized blocks and unwritten blocks. For overwrite unwritten blocks
* we protect splitting extents by i_data_sem in ext4_inode_info, so we can
* also release exclusive i_rwsem lock.
*
* - Otherwise we will switch to exclusive i_rwsem lock.
*/
static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,
bool *ilock_shared, bool *extend,
bool *unwritten, int *dio_flags)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file_inode(file);
loff_t offset;
size_t count;
ssize_t ret;
bool overwrite, unaligned_io;
restart:
ret = ext4_generic_write_checks(iocb, from);
if (ret <= 0)
goto out;
offset = iocb->ki_pos;
count = ret;
unaligned_io = ext4_unaligned_io(inode, from, offset);
*extend = ext4_extending_io(inode, offset, count);
overwrite = ext4_overwrite_io(inode, offset, count, unwritten);
/*
* Determine whether we need to upgrade to an exclusive lock. This is
* required to change security info in file_modified(), for extending
* I/O, any form of non-overwrite I/O, and unaligned I/O to unwritten
* extents (as partial block zeroing may be required).
*
* Note that unaligned writes are allowed under shared lock so long as
* they are pure overwrites. Otherwise, concurrent unaligned writes risk
* data corruption due to partial block zeroing in the dio layer, and so
* the I/O must occur exclusively.
*/
if (*ilock_shared &&
((!IS_NOSEC(inode) || *extend || !overwrite ||
(unaligned_io && *unwritten)))) {
if (iocb->ki_flags & IOCB_NOWAIT) {
ret = -EAGAIN;
goto out;
}
inode_unlock_shared(inode);
*ilock_shared = false;
inode_lock(inode);
goto restart;
}
/*
* Now that locking is settled, determine dio flags and exclusivity
* requirements. We don't use DIO_OVERWRITE_ONLY because we enforce
* behavior already. The inode lock is already held exclusive if the
* write is non-overwrite or extending, so drain all outstanding dio and
* set the force wait dio flag.
*/
if (!*ilock_shared && (unaligned_io || *extend)) {
if (iocb->ki_flags & IOCB_NOWAIT) {
ret = -EAGAIN;
goto out;
}
if (unaligned_io && (!overwrite || *unwritten))
inode_dio_wait(inode);
*dio_flags = IOMAP_DIO_FORCE_WAIT;
}
ret = file_modified(file);
if (ret < 0)
goto out;
return count;
out:
if (*ilock_shared)
inode_unlock_shared(inode);
else
inode_unlock(inode);
return ret;
}
static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
ssize_t ret;
handle_t *handle;
struct inode *inode = file_inode(iocb->ki_filp);
loff_t offset = iocb->ki_pos;
size_t count = iov_iter_count(from);
const struct iomap_ops *iomap_ops = &ext4_iomap_ops;
bool extend = false, unwritten = false;
bool ilock_shared = true;
int dio_flags = 0;
/*
* Quick check here without any i_rwsem lock to see if it is extending
* IO. A more reliable check is done in ext4_dio_write_checks() with
* proper locking in place.
*/
if (offset + count > i_size_read(inode))
ilock_shared = false;
if (iocb->ki_flags & IOCB_NOWAIT) {
if (ilock_shared) {
if (!inode_trylock_shared(inode))
return -EAGAIN;
} else {
if (!inode_trylock(inode))
return -EAGAIN;
}
} else {
if (ilock_shared)
inode_lock_shared(inode);
else
inode_lock(inode);
}
/* Fallback to buffered I/O if the inode does not support direct I/O. */
if (!ext4_should_use_dio(iocb, from)) {
if (ilock_shared)
inode_unlock_shared(inode);
else
inode_unlock(inode);
return ext4_buffered_write_iter(iocb, from);
}
ret = ext4_dio_write_checks(iocb, from, &ilock_shared, &extend,
&unwritten, &dio_flags);
if (ret <= 0)
return ret;
/*
* Make sure inline data cannot be created anymore since we are going
* to allocate blocks for DIO. We know the inode does not have any
* inline data now because ext4_dio_supported() checked for that.
*/
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
offset = iocb->ki_pos;
count = ret;
if (extend) {
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext4_orphan_add(handle, inode);
if (ret) {
ext4_journal_stop(handle);
goto out;
}
ext4_journal_stop(handle);
}
if (ilock_shared && !unwritten)
iomap_ops = &ext4_iomap_overwrite_ops;
ret = iomap_dio_rw(iocb, from, iomap_ops, &ext4_dio_write_ops,
dio_flags, NULL, 0);
if (ret == -ENOTBLK)
ret = 0;
if (extend)
ret = ext4_handle_inode_extension(inode, offset, ret, count);
out:
if (ilock_shared)
inode_unlock_shared(inode);
else
inode_unlock(inode);
if (ret >= 0 && iov_iter_count(from)) {
ssize_t err;
loff_t endbyte;
offset = iocb->ki_pos;
err = ext4_buffered_write_iter(iocb, from);
if (err < 0)
return err;
/*
* We need to ensure that the pages within the page cache for
* the range covered by this I/O are written to disk and
* invalidated. This is in attempt to preserve the expected
* direct I/O semantics in the case we fallback to buffered I/O
* to complete off the I/O request.
*/
ret += err;
endbyte = offset + err - 1;
err = filemap_write_and_wait_range(iocb->ki_filp->f_mapping,
offset, endbyte);
if (!err)
invalidate_mapping_pages(iocb->ki_filp->f_mapping,
offset >> PAGE_SHIFT,
endbyte >> PAGE_SHIFT);
}
return ret;
}
#ifdef CONFIG_FS_DAX
static ssize_t
ext4_dax_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
ssize_t ret;
size_t count;
loff_t offset;
handle_t *handle;
bool extend = false;
struct inode *inode = file_inode(iocb->ki_filp);
if (iocb->ki_flags & IOCB_NOWAIT) {
if (!inode_trylock(inode))
return -EAGAIN;
} else {
inode_lock(inode);
}
ret = ext4_write_checks(iocb, from);
if (ret <= 0)
goto out;
offset = iocb->ki_pos;
count = iov_iter_count(from);
if (offset + count > EXT4_I(inode)->i_disksize) {
handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext4_orphan_add(handle, inode);
if (ret) {
ext4_journal_stop(handle);
goto out;
}
extend = true;
ext4_journal_stop(handle);
}
ret = dax_iomap_rw(iocb, from, &ext4_iomap_ops);
if (extend)
ret = ext4_handle_inode_extension(inode, offset, ret, count);
out:
inode_unlock(inode);
if (ret > 0)
ret = generic_write_sync(iocb, ret);
return ret;
}
#endif
static ssize_t
ext4_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct inode *inode = file_inode(iocb->ki_filp);
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
#ifdef CONFIG_FS_DAX
if (IS_DAX(inode))
return ext4_dax_write_iter(iocb, from);
#endif
if (iocb->ki_flags & IOCB_DIRECT)
return ext4_dio_write_iter(iocb, from);
else
return ext4_buffered_write_iter(iocb, from);
}
#ifdef CONFIG_FS_DAX
static vm_fault_t ext4_dax_huge_fault(struct vm_fault *vmf, unsigned int order)
{
int error = 0;
vm_fault_t result;
int retries = 0;
handle_t *handle = NULL;
struct inode *inode = file_inode(vmf->vma->vm_file);
struct super_block *sb = inode->i_sb;
/*
* We have to distinguish real writes from writes which will result in a
* COW page; COW writes should *not* poke the journal (the file will not
* be changed). Doing so would cause unintended failures when mounted
* read-only.
*
* We check for VM_SHARED rather than vmf->cow_page since the latter is
* unset for order != 0 (i.e. only in do_cow_fault); for
* other sizes, dax_iomap_fault will handle splitting / fallback so that
* we eventually come back with a COW page.
*/
bool write = (vmf->flags & FAULT_FLAG_WRITE) &&
(vmf->vma->vm_flags & VM_SHARED);
struct address_space *mapping = vmf->vma->vm_file->f_mapping;
pfn_t pfn;
if (write) {
sb_start_pagefault(sb);
file_update_time(vmf->vma->vm_file);
filemap_invalidate_lock_shared(mapping);
retry:
handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
EXT4_DATA_TRANS_BLOCKS(sb));
if (IS_ERR(handle)) {
filemap_invalidate_unlock_shared(mapping);
sb_end_pagefault(sb);
return VM_FAULT_SIGBUS;
}
} else {
filemap_invalidate_lock_shared(mapping);
}
result = dax_iomap_fault(vmf, order, &pfn, &error, &ext4_iomap_ops);
if (write) {
ext4_journal_stop(handle);
if ((result & VM_FAULT_ERROR) && error == -ENOSPC &&
ext4_should_retry_alloc(sb, &retries))
goto retry;
/* Handling synchronous page fault? */
if (result & VM_FAULT_NEEDDSYNC)
result = dax_finish_sync_fault(vmf, order, pfn);
filemap_invalidate_unlock_shared(mapping);
sb_end_pagefault(sb);
} else {
filemap_invalidate_unlock_shared(mapping);
}
return result;
}
static vm_fault_t ext4_dax_fault(struct vm_fault *vmf)
{
return ext4_dax_huge_fault(vmf, 0);
}
static const struct vm_operations_struct ext4_dax_vm_ops = {
.fault = ext4_dax_fault,
.huge_fault = ext4_dax_huge_fault,
.page_mkwrite = ext4_dax_fault,
.pfn_mkwrite = ext4_dax_fault,
};
#else
#define ext4_dax_vm_ops ext4_file_vm_ops
#endif
static const struct vm_operations_struct ext4_file_vm_ops = {
.fault = filemap_fault,
.map_pages = filemap_map_pages,
.page_mkwrite = ext4_page_mkwrite,
};
static int ext4_file_mmap(struct file *file, struct vm_area_struct *vma)
{
struct inode *inode = file->f_mapping->host;
struct dax_device *dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
/*
* We don't support synchronous mappings for non-DAX files and
* for DAX files if underneath dax_device is not synchronous.
*/
if (!daxdev_mapping_supported(vma, dax_dev))
return -EOPNOTSUPP;
file_accessed(file);
if (IS_DAX(file_inode(file))) {
vma->vm_ops = &ext4_dax_vm_ops;
vm_flags_set(vma, VM_HUGEPAGE);
} else {
vma->vm_ops = &ext4_file_vm_ops;
}
return 0;
}
static int ext4_sample_last_mounted(struct super_block *sb,
struct vfsmount *mnt)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct path path;
char buf[64], *cp;
handle_t *handle;
int err;
if (likely(ext4_test_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED)))
return 0;
if (sb_rdonly(sb) || !sb_start_intwrite_trylock(sb))
return 0;
ext4_set_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED);
/*
* Sample where the filesystem has been mounted and
* store it in the superblock for sysadmin convenience
* when trying to sort through large numbers of block
* devices or filesystem images.
*/
memset(buf, 0, sizeof(buf));
path.mnt = mnt;
path.dentry = mnt->mnt_root;
cp = d_path(&path, buf, sizeof(buf));
err = 0;
if (IS_ERR(cp))
goto out;
handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
err = PTR_ERR(handle);
if (IS_ERR(handle))
goto out;
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
EXT4_JTR_NONE);
if (err)
goto out_journal;
lock_buffer(sbi->s_sbh);
strncpy(sbi->s_es->s_last_mounted, cp,
sizeof(sbi->s_es->s_last_mounted));
ext4_superblock_csum_set(sb);
unlock_buffer(sbi->s_sbh);
ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
out_journal:
ext4_journal_stop(handle);
out:
sb_end_intwrite(sb);
return err;
}
static int ext4_file_open(struct inode *inode, struct file *filp)
{
int ret;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return -EIO;
ret = ext4_sample_last_mounted(inode->i_sb, filp->f_path.mnt);
if (ret)
return ret;
ret = fscrypt_file_open(inode, filp);
if (ret)
return ret;
ret = fsverity_file_open(inode, filp);
if (ret)
return ret;
/*
* Set up the jbd2_inode if we are opening the inode for
* writing and the journal is present
*/
if (filp->f_mode & FMODE_WRITE) {
ret = ext4_inode_attach_jinode(inode);
if (ret < 0)
return ret;
}
filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC |
FMODE_DIO_PARALLEL_WRITE;
return dquot_file_open(inode, filp);
}
/*
* ext4_llseek() handles both block-mapped and extent-mapped maxbytes values
* by calling generic_file_llseek_size() with the appropriate maxbytes
* value for each.
*/
loff_t ext4_llseek(struct file *file, loff_t offset, int whence)
{
struct inode *inode = file->f_mapping->host;
loff_t maxbytes;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
else
maxbytes = inode->i_sb->s_maxbytes;
switch (whence) {
default:
return generic_file_llseek_size(file, offset, whence,
maxbytes, i_size_read(inode));
case SEEK_HOLE:
inode_lock_shared(inode);
offset = iomap_seek_hole(inode, offset,
&ext4_iomap_report_ops);
inode_unlock_shared(inode);
break;
case SEEK_DATA:
inode_lock_shared(inode);
offset = iomap_seek_data(inode, offset,
&ext4_iomap_report_ops);
inode_unlock_shared(inode);
break;
}
if (offset < 0)
return offset;
return vfs_setpos(file, offset, maxbytes);
}
const struct file_operations ext4_file_operations = {
.llseek = ext4_llseek,
.read_iter = ext4_file_read_iter,
.write_iter = ext4_file_write_iter,
.iopoll = iocb_bio_iopoll,
.unlocked_ioctl = ext4_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ext4_compat_ioctl,
#endif
.mmap = ext4_file_mmap,
.mmap_supported_flags = MAP_SYNC,
.open = ext4_file_open,
.release = ext4_release_file,
.fsync = ext4_sync_file,
.get_unmapped_area = thp_get_unmapped_area,
.splice_read = ext4_file_splice_read,
.splice_write = iter_file_splice_write,
.fallocate = ext4_fallocate,
};
const struct inode_operations ext4_file_inode_operations = {
.setattr = ext4_setattr,
.getattr = ext4_file_getattr,
.listxattr = ext4_listxattr,
.get_inode_acl = ext4_get_acl,
.set_acl = ext4_set_acl,
.fiemap = ext4_fiemap,
.fileattr_get = ext4_fileattr_get,
.fileattr_set = ext4_fileattr_set,
};
| linux-master | fs/ext4/file.c |
/*
* Ext4 orphan inode handling
*/
#include <linux/fs.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include "ext4.h"
#include "ext4_jbd2.h"
static int ext4_orphan_file_add(handle_t *handle, struct inode *inode)
{
int i, j, start;
struct ext4_orphan_info *oi = &EXT4_SB(inode->i_sb)->s_orphan_info;
int ret = 0;
bool found = false;
__le32 *bdata;
int inodes_per_ob = ext4_inodes_per_orphan_block(inode->i_sb);
int looped = 0;
/*
* Find block with free orphan entry. Use CPU number for a naive hash
* for a search start in the orphan file
*/
start = raw_smp_processor_id()*13 % oi->of_blocks;
i = start;
do {
if (atomic_dec_if_positive(&oi->of_binfo[i].ob_free_entries)
>= 0) {
found = true;
break;
}
if (++i >= oi->of_blocks)
i = 0;
} while (i != start);
if (!found) {
/*
* For now we don't grow or shrink orphan file. We just use
* whatever was allocated at mke2fs time. The additional
* credits we would have to reserve for each orphan inode
* operation just don't seem worth it.
*/
return -ENOSPC;
}
ret = ext4_journal_get_write_access(handle, inode->i_sb,
oi->of_binfo[i].ob_bh, EXT4_JTR_ORPHAN_FILE);
if (ret) {
atomic_inc(&oi->of_binfo[i].ob_free_entries);
return ret;
}
bdata = (__le32 *)(oi->of_binfo[i].ob_bh->b_data);
/* Find empty slot in a block */
j = 0;
do {
if (looped) {
/*
* Did we walk through the block several times without
* finding free entry? It is theoretically possible
* if entries get constantly allocated and freed or
* if the block is corrupted. Avoid indefinite looping
* and bail. We'll use orphan list instead.
*/
if (looped > 3) {
atomic_inc(&oi->of_binfo[i].ob_free_entries);
return -ENOSPC;
}
cond_resched();
}
while (bdata[j]) {
if (++j >= inodes_per_ob) {
j = 0;
looped++;
}
}
} while (cmpxchg(&bdata[j], (__le32)0, cpu_to_le32(inode->i_ino)) !=
(__le32)0);
EXT4_I(inode)->i_orphan_idx = i * inodes_per_ob + j;
ext4_set_inode_state(inode, EXT4_STATE_ORPHAN_FILE);
return ext4_handle_dirty_metadata(handle, NULL, oi->of_binfo[i].ob_bh);
}
/*
* ext4_orphan_add() links an unlinked or truncated inode into a list of
* such inodes, starting at the superblock, in case we crash before the
* file is closed/deleted, or in case the inode truncate spans multiple
* transactions and the last transaction is not recovered after a crash.
*
* At filesystem recovery time, we walk this list deleting unlinked
* inodes and truncating linked inodes in ext4_orphan_cleanup().
*
* Orphan list manipulation functions must be called under i_rwsem unless
* we are just creating the inode or deleting it.
*/
int ext4_orphan_add(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_iloc iloc;
int err = 0, rc;
bool dirty = false;
if (!sbi->s_journal || is_bad_inode(inode))
return 0;
WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
!inode_is_locked(inode));
/*
* Inode orphaned in orphan file or in orphan list?
*/
if (ext4_test_inode_state(inode, EXT4_STATE_ORPHAN_FILE) ||
!list_empty(&EXT4_I(inode)->i_orphan))
return 0;
/*
* Orphan handling is only valid for files with data blocks
* being truncated, or files being unlinked. Note that we either
* hold i_rwsem, or the inode can not be referenced from outside,
* so i_nlink should not be bumped due to race
*/
ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
if (sbi->s_orphan_info.of_blocks) {
err = ext4_orphan_file_add(handle, inode);
/*
* Fallback to normal orphan list of orphan file is
* out of space
*/
if (err != -ENOSPC)
return err;
}
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
EXT4_JTR_NONE);
if (err)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out;
mutex_lock(&sbi->s_orphan_lock);
/*
* Due to previous errors inode may be already a part of on-disk
* orphan list. If so skip on-disk list modification.
*/
if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
(le32_to_cpu(sbi->s_es->s_inodes_count))) {
/* Insert this inode at the head of the on-disk orphan list */
NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
lock_buffer(sbi->s_sbh);
sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
ext4_superblock_csum_set(sb);
unlock_buffer(sbi->s_sbh);
dirty = true;
}
list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
mutex_unlock(&sbi->s_orphan_lock);
if (dirty) {
err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (!err)
err = rc;
if (err) {
/*
* We have to remove inode from in-memory list if
* addition to on disk orphan list failed. Stray orphan
* list entries can cause panics at unmount time.
*/
mutex_lock(&sbi->s_orphan_lock);
list_del_init(&EXT4_I(inode)->i_orphan);
mutex_unlock(&sbi->s_orphan_lock);
}
} else
brelse(iloc.bh);
ext4_debug("superblock will point to %lu\n", inode->i_ino);
ext4_debug("orphan inode %lu will point to %d\n",
inode->i_ino, NEXT_ORPHAN(inode));
out:
ext4_std_error(sb, err);
return err;
}
static int ext4_orphan_file_del(handle_t *handle, struct inode *inode)
{
struct ext4_orphan_info *oi = &EXT4_SB(inode->i_sb)->s_orphan_info;
__le32 *bdata;
int blk, off;
int inodes_per_ob = ext4_inodes_per_orphan_block(inode->i_sb);
int ret = 0;
if (!handle)
goto out;
blk = EXT4_I(inode)->i_orphan_idx / inodes_per_ob;
off = EXT4_I(inode)->i_orphan_idx % inodes_per_ob;
if (WARN_ON_ONCE(blk >= oi->of_blocks))
goto out;
ret = ext4_journal_get_write_access(handle, inode->i_sb,
oi->of_binfo[blk].ob_bh, EXT4_JTR_ORPHAN_FILE);
if (ret)
goto out;
bdata = (__le32 *)(oi->of_binfo[blk].ob_bh->b_data);
bdata[off] = 0;
atomic_inc(&oi->of_binfo[blk].ob_free_entries);
ret = ext4_handle_dirty_metadata(handle, NULL, oi->of_binfo[blk].ob_bh);
out:
ext4_clear_inode_state(inode, EXT4_STATE_ORPHAN_FILE);
INIT_LIST_HEAD(&EXT4_I(inode)->i_orphan);
return ret;
}
/*
* ext4_orphan_del() removes an unlinked or truncated inode from the list
* of such inodes stored on disk, because it is finally being cleaned up.
*/
int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
return 0;
WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
!inode_is_locked(inode));
if (ext4_test_inode_state(inode, EXT4_STATE_ORPHAN_FILE))
return ext4_orphan_file_del(handle, inode);
/* Do this quick check before taking global s_orphan_lock. */
if (list_empty(&ei->i_orphan))
return 0;
if (handle) {
/* Grab inode buffer early before taking global s_orphan_lock */
err = ext4_reserve_inode_write(handle, inode, &iloc);
}
mutex_lock(&sbi->s_orphan_lock);
ext4_debug("remove inode %lu from orphan list\n", inode->i_ino);
prev = ei->i_orphan.prev;
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle || err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_err;
}
ino_next = NEXT_ORPHAN(inode);
if (prev == &sbi->s_orphan) {
ext4_debug("superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, inode->i_sb,
sbi->s_sbh, EXT4_JTR_NONE);
if (err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_brelse;
}
lock_buffer(sbi->s_sbh);
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
ext4_superblock_csum_set(inode->i_sb);
unlock_buffer(sbi->s_sbh);
mutex_unlock(&sbi->s_orphan_lock);
err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
ext4_debug("orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err) {
mutex_unlock(&sbi->s_orphan_lock);
goto out_brelse;
}
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
mutex_unlock(&sbi->s_orphan_lock);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
#ifdef CONFIG_QUOTA
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb,
rcu_dereference_protected(EXT4_SB(sb)->s_qf_names[type],
lockdep_is_held(&sb->s_umount)),
EXT4_SB(sb)->s_jquota_fmt, type);
}
#endif
static void ext4_process_orphan(struct inode *inode,
int *nr_truncates, int *nr_orphans)
{
struct super_block *sb = inode->i_sb;
int ret;
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
ext4_debug("truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
inode_lock(inode);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ret = ext4_truncate(inode);
if (ret) {
/*
* We need to clean up the in-core orphan list
* manually if ext4_truncate() failed to get a
* transaction handle.
*/
ext4_orphan_del(NULL, inode);
ext4_std_error(inode->i_sb, ret);
}
inode_unlock(inode);
(*nr_truncates)++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
ext4_debug("deleting unreferenced inode %lu\n",
inode->i_ino);
(*nr_orphans)++;
}
iput(inode); /* The delete magic happens here! */
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
void ext4_orphan_cleanup(struct super_block *sb, struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int nr_orphans = 0, nr_truncates = 0;
struct inode *inode;
int i, j;
#ifdef CONFIG_QUOTA
int quota_update = 0;
#endif
__le32 *bdata;
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
int inodes_per_ob = ext4_inodes_per_orphan_block(sb);
if (!es->s_last_orphan && !oi->of_blocks) {
ext4_debug("no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & SB_RDONLY)) {
ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
"clearing orphan list.");
es->s_last_orphan = 0;
}
ext4_debug("Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & SB_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~SB_RDONLY;
}
#ifdef CONFIG_QUOTA
/*
* Turn on quotas which were not enabled for read-only mounts if
* filesystem has quota feature, so that they are updated correctly.
*/
if (ext4_has_feature_quota(sb) && (s_flags & SB_RDONLY)) {
int ret = ext4_enable_quotas(sb);
if (!ret)
quota_update = 1;
else
ext4_msg(sb, KERN_ERR,
"Cannot turn on quotas: error %d", ret);
}
/* Turn on journaled quotas used for old sytle */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (!ret)
quota_update = 1;
else
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: type %d: error %d", i, ret);
}
}
#endif
while (es->s_last_orphan) {
/*
* We may have encountered an error during cleanup; if
* so, skip the rest.
*/
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
ext4_debug("Skipping orphan recovery on fs with errors.\n");
es->s_last_orphan = 0;
break;
}
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
ext4_process_orphan(inode, &nr_truncates, &nr_orphans);
}
for (i = 0; i < oi->of_blocks; i++) {
bdata = (__le32 *)(oi->of_binfo[i].ob_bh->b_data);
for (j = 0; j < inodes_per_ob; j++) {
if (!bdata[j])
continue;
inode = ext4_orphan_get(sb, le32_to_cpu(bdata[j]));
if (IS_ERR(inode))
continue;
ext4_set_inode_state(inode, EXT4_STATE_ORPHAN_FILE);
EXT4_I(inode)->i_orphan_idx = i * inodes_per_ob + j;
ext4_process_orphan(inode, &nr_truncates, &nr_orphans);
}
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn off quotas if they were enabled for orphan cleanup */
if (quota_update) {
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
}
#endif
sb->s_flags = s_flags; /* Restore SB_RDONLY status */
}
void ext4_release_orphan_info(struct super_block *sb)
{
int i;
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
if (!oi->of_blocks)
return;
for (i = 0; i < oi->of_blocks; i++)
brelse(oi->of_binfo[i].ob_bh);
kfree(oi->of_binfo);
}
static struct ext4_orphan_block_tail *ext4_orphan_block_tail(
struct super_block *sb,
struct buffer_head *bh)
{
return (struct ext4_orphan_block_tail *)(bh->b_data + sb->s_blocksize -
sizeof(struct ext4_orphan_block_tail));
}
static int ext4_orphan_file_block_csum_verify(struct super_block *sb,
struct buffer_head *bh)
{
__u32 calculated;
int inodes_per_ob = ext4_inodes_per_orphan_block(sb);
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
struct ext4_orphan_block_tail *ot;
__le64 dsk_block_nr = cpu_to_le64(bh->b_blocknr);
if (!ext4_has_metadata_csum(sb))
return 1;
ot = ext4_orphan_block_tail(sb, bh);
calculated = ext4_chksum(EXT4_SB(sb), oi->of_csum_seed,
(__u8 *)&dsk_block_nr, sizeof(dsk_block_nr));
calculated = ext4_chksum(EXT4_SB(sb), calculated, (__u8 *)bh->b_data,
inodes_per_ob * sizeof(__u32));
return le32_to_cpu(ot->ob_checksum) == calculated;
}
/* This gets called only when checksumming is enabled */
void ext4_orphan_file_block_trigger(struct jbd2_buffer_trigger_type *triggers,
struct buffer_head *bh,
void *data, size_t size)
{
struct super_block *sb = EXT4_TRIGGER(triggers)->sb;
__u32 csum;
int inodes_per_ob = ext4_inodes_per_orphan_block(sb);
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
struct ext4_orphan_block_tail *ot;
__le64 dsk_block_nr = cpu_to_le64(bh->b_blocknr);
csum = ext4_chksum(EXT4_SB(sb), oi->of_csum_seed,
(__u8 *)&dsk_block_nr, sizeof(dsk_block_nr));
csum = ext4_chksum(EXT4_SB(sb), csum, (__u8 *)data,
inodes_per_ob * sizeof(__u32));
ot = ext4_orphan_block_tail(sb, bh);
ot->ob_checksum = cpu_to_le32(csum);
}
int ext4_init_orphan_info(struct super_block *sb)
{
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
struct inode *inode;
int i, j;
int ret;
int free;
__le32 *bdata;
int inodes_per_ob = ext4_inodes_per_orphan_block(sb);
struct ext4_orphan_block_tail *ot;
ino_t orphan_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_orphan_file_inum);
if (!ext4_has_feature_orphan_file(sb))
return 0;
inode = ext4_iget(sb, orphan_ino, EXT4_IGET_SPECIAL);
if (IS_ERR(inode)) {
ext4_msg(sb, KERN_ERR, "get orphan inode failed");
return PTR_ERR(inode);
}
oi->of_blocks = inode->i_size >> sb->s_blocksize_bits;
oi->of_csum_seed = EXT4_I(inode)->i_csum_seed;
oi->of_binfo = kmalloc(oi->of_blocks*sizeof(struct ext4_orphan_block),
GFP_KERNEL);
if (!oi->of_binfo) {
ret = -ENOMEM;
goto out_put;
}
for (i = 0; i < oi->of_blocks; i++) {
oi->of_binfo[i].ob_bh = ext4_bread(NULL, inode, i, 0);
if (IS_ERR(oi->of_binfo[i].ob_bh)) {
ret = PTR_ERR(oi->of_binfo[i].ob_bh);
goto out_free;
}
if (!oi->of_binfo[i].ob_bh) {
ret = -EIO;
goto out_free;
}
ot = ext4_orphan_block_tail(sb, oi->of_binfo[i].ob_bh);
if (le32_to_cpu(ot->ob_magic) != EXT4_ORPHAN_BLOCK_MAGIC) {
ext4_error(sb, "orphan file block %d: bad magic", i);
ret = -EIO;
goto out_free;
}
if (!ext4_orphan_file_block_csum_verify(sb,
oi->of_binfo[i].ob_bh)) {
ext4_error(sb, "orphan file block %d: bad checksum", i);
ret = -EIO;
goto out_free;
}
bdata = (__le32 *)(oi->of_binfo[i].ob_bh->b_data);
free = 0;
for (j = 0; j < inodes_per_ob; j++)
if (bdata[j] == 0)
free++;
atomic_set(&oi->of_binfo[i].ob_free_entries, free);
}
iput(inode);
return 0;
out_free:
for (i--; i >= 0; i--)
brelse(oi->of_binfo[i].ob_bh);
kfree(oi->of_binfo);
out_put:
iput(inode);
return ret;
}
int ext4_orphan_file_empty(struct super_block *sb)
{
struct ext4_orphan_info *oi = &EXT4_SB(sb)->s_orphan_info;
int i;
int inodes_per_ob = ext4_inodes_per_orphan_block(sb);
if (!ext4_has_feature_orphan_file(sb))
return 1;
for (i = 0; i < oi->of_blocks; i++)
if (atomic_read(&oi->of_binfo[i].ob_free_entries) !=
inodes_per_ob)
return 0;
return 1;
}
| linux-master | fs/ext4/orphan.c |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext4/ialloc.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* BSD ufs-inspired inode and directory allocation by
* Stephen Tweedie ([email protected]), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/random.h>
#include <linux/bitops.h>
#include <linux/blkdev.h>
#include <linux/cred.h>
#include <asm/byteorder.h>
#include "ext4.h"
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include <trace/events/ext4.h>
/*
* ialloc.c contains the inodes allocation and deallocation routines
*/
/*
* The free inodes are managed by bitmaps. A file system contains several
* blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap
* block for inodes, N blocks for the inode table and data blocks.
*
* The file system contains group descriptors which are located after the
* super block. Each descriptor contains the number of the bitmap block and
* the free blocks count in the block.
*/
/*
* To avoid calling the atomic setbit hundreds or thousands of times, we only
* need to use it within a single byte (to ensure we get endianness right).
* We can use memset for the rest of the bitmap as there are no other users.
*/
void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
{
int i;
if (start_bit >= end_bit)
return;
ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
ext4_set_bit(i, bitmap);
if (i < end_bit)
memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
}
void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate)
{
if (uptodate) {
set_buffer_uptodate(bh);
set_bitmap_uptodate(bh);
}
unlock_buffer(bh);
put_bh(bh);
}
static int ext4_validate_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *desc,
ext4_group_t block_group,
struct buffer_head *bh)
{
ext4_fsblk_t blk;
struct ext4_group_info *grp;
if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
return 0;
grp = ext4_get_group_info(sb, block_group);
if (buffer_verified(bh))
return 0;
if (!grp || EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
return -EFSCORRUPTED;
ext4_lock_group(sb, block_group);
if (buffer_verified(bh))
goto verified;
blk = ext4_inode_bitmap(sb, desc);
if (!ext4_inode_bitmap_csum_verify(sb, desc, bh,
EXT4_INODES_PER_GROUP(sb) / 8) ||
ext4_simulate_fail(sb, EXT4_SIM_IBITMAP_CRC)) {
ext4_unlock_group(sb, block_group);
ext4_error(sb, "Corrupt inode bitmap - block_group = %u, "
"inode_bitmap = %llu", block_group, blk);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
return -EFSBADCRC;
}
set_buffer_verified(bh);
verified:
ext4_unlock_group(sb, block_group);
return 0;
}
/*
* Read the inode allocation bitmap for a given block_group, reading
* into the specified slot in the superblock's bitmap cache.
*
* Return buffer_head of bitmap on success, or an ERR_PTR on error.
*/
static struct buffer_head *
ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
{
struct ext4_group_desc *desc;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *bh = NULL;
ext4_fsblk_t bitmap_blk;
int err;
desc = ext4_get_group_desc(sb, block_group, NULL);
if (!desc)
return ERR_PTR(-EFSCORRUPTED);
bitmap_blk = ext4_inode_bitmap(sb, desc);
if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
ext4_error(sb, "Invalid inode bitmap blk %llu in "
"block_group %u", bitmap_blk, block_group);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
return ERR_PTR(-EFSCORRUPTED);
}
bh = sb_getblk(sb, bitmap_blk);
if (unlikely(!bh)) {
ext4_warning(sb, "Cannot read inode bitmap - "
"block_group = %u, inode_bitmap = %llu",
block_group, bitmap_blk);
return ERR_PTR(-ENOMEM);
}
if (bitmap_uptodate(bh))
goto verify;
lock_buffer(bh);
if (bitmap_uptodate(bh)) {
unlock_buffer(bh);
goto verify;
}
ext4_lock_group(sb, block_group);
if (ext4_has_group_desc_csum(sb) &&
(desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
if (block_group == 0) {
ext4_unlock_group(sb, block_group);
unlock_buffer(bh);
ext4_error(sb, "Inode bitmap for bg 0 marked "
"uninitialized");
err = -EFSCORRUPTED;
goto out;
}
memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
sb->s_blocksize * 8, bh->b_data);
set_bitmap_uptodate(bh);
set_buffer_uptodate(bh);
set_buffer_verified(bh);
ext4_unlock_group(sb, block_group);
unlock_buffer(bh);
return bh;
}
ext4_unlock_group(sb, block_group);
if (buffer_uptodate(bh)) {
/*
* if not uninit if bh is uptodate,
* bitmap is also uptodate
*/
set_bitmap_uptodate(bh);
unlock_buffer(bh);
goto verify;
}
/*
* submit the buffer_head for reading
*/
trace_ext4_load_inode_bitmap(sb, block_group);
ext4_read_bh(bh, REQ_META | REQ_PRIO, ext4_end_bitmap_read);
ext4_simulate_fail_bh(sb, bh, EXT4_SIM_IBITMAP_EIO);
if (!buffer_uptodate(bh)) {
put_bh(bh);
ext4_error_err(sb, EIO, "Cannot read inode bitmap - "
"block_group = %u, inode_bitmap = %llu",
block_group, bitmap_blk);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
return ERR_PTR(-EIO);
}
verify:
err = ext4_validate_inode_bitmap(sb, desc, block_group, bh);
if (err)
goto out;
return bh;
out:
put_bh(bh);
return ERR_PTR(err);
}
/*
* NOTE! When we get the inode, we're the only people
* that have access to it, and as such there are no
* race conditions we have to worry about. The inode
* is not on the hash-lists, and it cannot be reached
* through the filesystem because the directory entry
* has been deleted earlier.
*
* HOWEVER: we must make sure that we get no aliases,
* which means that we have to call "clear_inode()"
* _before_ we mark the inode not in use in the inode
* bitmaps. Otherwise a newly created file might use
* the same inode number (not actually the same pointer
* though), and then we'd have two inodes sharing the
* same inode number and space on the harddisk.
*/
void ext4_free_inode(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
int is_directory;
unsigned long ino;
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *bh2;
ext4_group_t block_group;
unsigned long bit;
struct ext4_group_desc *gdp;
struct ext4_super_block *es;
struct ext4_sb_info *sbi;
int fatal = 0, err, count, cleared;
struct ext4_group_info *grp;
if (!sb) {
printk(KERN_ERR "EXT4-fs: %s:%d: inode on "
"nonexistent device\n", __func__, __LINE__);
return;
}
if (atomic_read(&inode->i_count) > 1) {
ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d",
__func__, __LINE__, inode->i_ino,
atomic_read(&inode->i_count));
return;
}
if (inode->i_nlink) {
ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n",
__func__, __LINE__, inode->i_ino, inode->i_nlink);
return;
}
sbi = EXT4_SB(sb);
ino = inode->i_ino;
ext4_debug("freeing inode %lu\n", ino);
trace_ext4_free_inode(inode);
dquot_initialize(inode);
dquot_free_inode(inode);
is_directory = S_ISDIR(inode->i_mode);
/* Do this BEFORE marking the inode not in use or returning an error */
ext4_clear_inode(inode);
es = sbi->s_es;
if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
ext4_error(sb, "reserved or nonexistent inode %lu", ino);
goto error_return;
}
block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
/* Don't bother if the inode bitmap is corrupt. */
if (IS_ERR(bitmap_bh)) {
fatal = PTR_ERR(bitmap_bh);
bitmap_bh = NULL;
goto error_return;
}
if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
grp = ext4_get_group_info(sb, block_group);
if (!grp || unlikely(EXT4_MB_GRP_IBITMAP_CORRUPT(grp))) {
fatal = -EFSCORRUPTED;
goto error_return;
}
}
BUFFER_TRACE(bitmap_bh, "get_write_access");
fatal = ext4_journal_get_write_access(handle, sb, bitmap_bh,
EXT4_JTR_NONE);
if (fatal)
goto error_return;
fatal = -ESRCH;
gdp = ext4_get_group_desc(sb, block_group, &bh2);
if (gdp) {
BUFFER_TRACE(bh2, "get_write_access");
fatal = ext4_journal_get_write_access(handle, sb, bh2,
EXT4_JTR_NONE);
}
ext4_lock_group(sb, block_group);
cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data);
if (fatal || !cleared) {
ext4_unlock_group(sb, block_group);
goto out;
}
count = ext4_free_inodes_count(sb, gdp) + 1;
ext4_free_inodes_set(sb, gdp, count);
if (is_directory) {
count = ext4_used_dirs_count(sb, gdp) - 1;
ext4_used_dirs_set(sb, gdp, count);
if (percpu_counter_initialized(&sbi->s_dirs_counter))
percpu_counter_dec(&sbi->s_dirs_counter);
}
ext4_inode_bitmap_csum_set(sb, gdp, bitmap_bh,
EXT4_INODES_PER_GROUP(sb) / 8);
ext4_group_desc_csum_set(sb, block_group, gdp);
ext4_unlock_group(sb, block_group);
if (percpu_counter_initialized(&sbi->s_freeinodes_counter))
percpu_counter_inc(&sbi->s_freeinodes_counter);
if (sbi->s_log_groups_per_flex) {
struct flex_groups *fg;
fg = sbi_array_rcu_deref(sbi, s_flex_groups,
ext4_flex_group(sbi, block_group));
atomic_inc(&fg->free_inodes);
if (is_directory)
atomic_dec(&fg->used_dirs);
}
BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
fatal = ext4_handle_dirty_metadata(handle, NULL, bh2);
out:
if (cleared) {
BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
if (!fatal)
fatal = err;
} else {
ext4_error(sb, "bit already cleared for inode %lu", ino);
ext4_mark_group_bitmap_corrupted(sb, block_group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
}
error_return:
brelse(bitmap_bh);
ext4_std_error(sb, fatal);
}
struct orlov_stats {
__u64 free_clusters;
__u32 free_inodes;
__u32 used_dirs;
};
/*
* Helper function for Orlov's allocator; returns critical information
* for a particular block group or flex_bg. If flex_size is 1, then g
* is a block group number; otherwise it is flex_bg number.
*/
static void get_orlov_stats(struct super_block *sb, ext4_group_t g,
int flex_size, struct orlov_stats *stats)
{
struct ext4_group_desc *desc;
if (flex_size > 1) {
struct flex_groups *fg = sbi_array_rcu_deref(EXT4_SB(sb),
s_flex_groups, g);
stats->free_inodes = atomic_read(&fg->free_inodes);
stats->free_clusters = atomic64_read(&fg->free_clusters);
stats->used_dirs = atomic_read(&fg->used_dirs);
return;
}
desc = ext4_get_group_desc(sb, g, NULL);
if (desc) {
stats->free_inodes = ext4_free_inodes_count(sb, desc);
stats->free_clusters = ext4_free_group_clusters(sb, desc);
stats->used_dirs = ext4_used_dirs_count(sb, desc);
} else {
stats->free_inodes = 0;
stats->free_clusters = 0;
stats->used_dirs = 0;
}
}
/*
* Orlov's allocator for directories.
*
* We always try to spread first-level directories.
*
* If there are blockgroups with both free inodes and free clusters counts
* not worse than average we return one with smallest directory count.
* Otherwise we simply return a random group.
*
* For the rest rules look so:
*
* It's OK to put directory into a group unless
* it has too many directories already (max_dirs) or
* it has too few free inodes left (min_inodes) or
* it has too few free clusters left (min_clusters) or
* Parent's group is preferred, if it doesn't satisfy these
* conditions we search cyclically through the rest. If none
* of the groups look good we just look for a group with more
* free inodes than average (starting at parent's group).
*/
static int find_group_orlov(struct super_block *sb, struct inode *parent,
ext4_group_t *group, umode_t mode,
const struct qstr *qstr)
{
ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t real_ngroups = ext4_get_groups_count(sb);
int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
unsigned int freei, avefreei, grp_free;
ext4_fsblk_t freec, avefreec;
unsigned int ndirs;
int max_dirs, min_inodes;
ext4_grpblk_t min_clusters;
ext4_group_t i, grp, g, ngroups;
struct ext4_group_desc *desc;
struct orlov_stats stats;
int flex_size = ext4_flex_bg_size(sbi);
struct dx_hash_info hinfo;
ngroups = real_ngroups;
if (flex_size > 1) {
ngroups = (real_ngroups + flex_size - 1) >>
sbi->s_log_groups_per_flex;
parent_group >>= sbi->s_log_groups_per_flex;
}
freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
avefreei = freei / ngroups;
freec = percpu_counter_read_positive(&sbi->s_freeclusters_counter);
avefreec = freec;
do_div(avefreec, ngroups);
ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
if (S_ISDIR(mode) &&
((parent == d_inode(sb->s_root)) ||
(ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) {
int best_ndir = inodes_per_group;
int ret = -1;
if (qstr) {
hinfo.hash_version = DX_HASH_HALF_MD4;
hinfo.seed = sbi->s_hash_seed;
ext4fs_dirhash(parent, qstr->name, qstr->len, &hinfo);
parent_group = hinfo.hash % ngroups;
} else
parent_group = get_random_u32_below(ngroups);
for (i = 0; i < ngroups; i++) {
g = (parent_group + i) % ngroups;
get_orlov_stats(sb, g, flex_size, &stats);
if (!stats.free_inodes)
continue;
if (stats.used_dirs >= best_ndir)
continue;
if (stats.free_inodes < avefreei)
continue;
if (stats.free_clusters < avefreec)
continue;
grp = g;
ret = 0;
best_ndir = stats.used_dirs;
}
if (ret)
goto fallback;
found_flex_bg:
if (flex_size == 1) {
*group = grp;
return 0;
}
/*
* We pack inodes at the beginning of the flexgroup's
* inode tables. Block allocation decisions will do
* something similar, although regular files will
* start at 2nd block group of the flexgroup. See
* ext4_ext_find_goal() and ext4_find_near().
*/
grp *= flex_size;
for (i = 0; i < flex_size; i++) {
if (grp+i >= real_ngroups)
break;
desc = ext4_get_group_desc(sb, grp+i, NULL);
if (desc && ext4_free_inodes_count(sb, desc)) {
*group = grp+i;
return 0;
}
}
goto fallback;
}
max_dirs = ndirs / ngroups + inodes_per_group*flex_size / 16;
min_inodes = avefreei - inodes_per_group*flex_size / 4;
if (min_inodes < 1)
min_inodes = 1;
min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4;
/*
* Start looking in the flex group where we last allocated an
* inode for this parent directory
*/
if (EXT4_I(parent)->i_last_alloc_group != ~0) {
parent_group = EXT4_I(parent)->i_last_alloc_group;
if (flex_size > 1)
parent_group >>= sbi->s_log_groups_per_flex;
}
for (i = 0; i < ngroups; i++) {
grp = (parent_group + i) % ngroups;
get_orlov_stats(sb, grp, flex_size, &stats);
if (stats.used_dirs >= max_dirs)
continue;
if (stats.free_inodes < min_inodes)
continue;
if (stats.free_clusters < min_clusters)
continue;
goto found_flex_bg;
}
fallback:
ngroups = real_ngroups;
avefreei = freei / ngroups;
fallback_retry:
parent_group = EXT4_I(parent)->i_block_group;
for (i = 0; i < ngroups; i++) {
grp = (parent_group + i) % ngroups;
desc = ext4_get_group_desc(sb, grp, NULL);
if (desc) {
grp_free = ext4_free_inodes_count(sb, desc);
if (grp_free && grp_free >= avefreei) {
*group = grp;
return 0;
}
}
}
if (avefreei) {
/*
* The free-inodes counter is approximate, and for really small
* filesystems the above test can fail to find any blockgroups
*/
avefreei = 0;
goto fallback_retry;
}
return -1;
}
static int find_group_other(struct super_block *sb, struct inode *parent,
ext4_group_t *group, umode_t mode)
{
ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
ext4_group_t i, last, ngroups = ext4_get_groups_count(sb);
struct ext4_group_desc *desc;
int flex_size = ext4_flex_bg_size(EXT4_SB(sb));
/*
* Try to place the inode is the same flex group as its
* parent. If we can't find space, use the Orlov algorithm to
* find another flex group, and store that information in the
* parent directory's inode information so that use that flex
* group for future allocations.
*/
if (flex_size > 1) {
int retry = 0;
try_again:
parent_group &= ~(flex_size-1);
last = parent_group + flex_size;
if (last > ngroups)
last = ngroups;
for (i = parent_group; i < last; i++) {
desc = ext4_get_group_desc(sb, i, NULL);
if (desc && ext4_free_inodes_count(sb, desc)) {
*group = i;
return 0;
}
}
if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) {
retry = 1;
parent_group = EXT4_I(parent)->i_last_alloc_group;
goto try_again;
}
/*
* If this didn't work, use the Orlov search algorithm
* to find a new flex group; we pass in the mode to
* avoid the topdir algorithms.
*/
*group = parent_group + flex_size;
if (*group > ngroups)
*group = 0;
return find_group_orlov(sb, parent, group, mode, NULL);
}
/*
* Try to place the inode in its parent directory
*/
*group = parent_group;
desc = ext4_get_group_desc(sb, *group, NULL);
if (desc && ext4_free_inodes_count(sb, desc) &&
ext4_free_group_clusters(sb, desc))
return 0;
/*
* We're going to place this inode in a different blockgroup from its
* parent. We want to cause files in a common directory to all land in
* the same blockgroup. But we want files which are in a different
* directory which shares a blockgroup with our parent to land in a
* different blockgroup.
*
* So add our directory's i_ino into the starting point for the hash.
*/
*group = (*group + parent->i_ino) % ngroups;
/*
* Use a quadratic hash to find a group with a free inode and some free
* blocks.
*/
for (i = 1; i < ngroups; i <<= 1) {
*group += i;
if (*group >= ngroups)
*group -= ngroups;
desc = ext4_get_group_desc(sb, *group, NULL);
if (desc && ext4_free_inodes_count(sb, desc) &&
ext4_free_group_clusters(sb, desc))
return 0;
}
/*
* That failed: try linear search for a free inode, even if that group
* has no free blocks.
*/
*group = parent_group;
for (i = 0; i < ngroups; i++) {
if (++*group >= ngroups)
*group = 0;
desc = ext4_get_group_desc(sb, *group, NULL);
if (desc && ext4_free_inodes_count(sb, desc))
return 0;
}
return -1;
}
/*
* In no journal mode, if an inode has recently been deleted, we want
* to avoid reusing it until we're reasonably sure the inode table
* block has been written back to disk. (Yes, these values are
* somewhat arbitrary...)
*/
#define RECENTCY_MIN 60
#define RECENTCY_DIRTY 300
static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino)
{
struct ext4_group_desc *gdp;
struct ext4_inode *raw_inode;
struct buffer_head *bh;
int inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
int offset, ret = 0;
int recentcy = RECENTCY_MIN;
u32 dtime, now;
gdp = ext4_get_group_desc(sb, group, NULL);
if (unlikely(!gdp))
return 0;
bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) +
(ino / inodes_per_block));
if (!bh || !buffer_uptodate(bh))
/*
* If the block is not in the buffer cache, then it
* must have been written out.
*/
goto out;
offset = (ino % inodes_per_block) * EXT4_INODE_SIZE(sb);
raw_inode = (struct ext4_inode *) (bh->b_data + offset);
/* i_dtime is only 32 bits on disk, but we only care about relative
* times in the range of a few minutes (i.e. long enough to sync a
* recently-deleted inode to disk), so using the low 32 bits of the
* clock (a 68 year range) is enough, see time_before32() */
dtime = le32_to_cpu(raw_inode->i_dtime);
now = ktime_get_real_seconds();
if (buffer_dirty(bh))
recentcy += RECENTCY_DIRTY;
if (dtime && time_before32(dtime, now) &&
time_before32(now, dtime + recentcy))
ret = 1;
out:
brelse(bh);
return ret;
}
static int find_inode_bit(struct super_block *sb, ext4_group_t group,
struct buffer_head *bitmap, unsigned long *ino)
{
bool check_recently_deleted = EXT4_SB(sb)->s_journal == NULL;
unsigned long recently_deleted_ino = EXT4_INODES_PER_GROUP(sb);
next:
*ino = ext4_find_next_zero_bit((unsigned long *)
bitmap->b_data,
EXT4_INODES_PER_GROUP(sb), *ino);
if (*ino >= EXT4_INODES_PER_GROUP(sb))
goto not_found;
if (check_recently_deleted && recently_deleted(sb, group, *ino)) {
recently_deleted_ino = *ino;
*ino = *ino + 1;
if (*ino < EXT4_INODES_PER_GROUP(sb))
goto next;
goto not_found;
}
return 1;
not_found:
if (recently_deleted_ino >= EXT4_INODES_PER_GROUP(sb))
return 0;
/*
* Not reusing recently deleted inodes is mostly a preference. We don't
* want to report ENOSPC or skew allocation patterns because of that.
* So return even recently deleted inode if we could find better in the
* given range.
*/
*ino = recently_deleted_ino;
return 1;
}
int ext4_mark_inode_used(struct super_block *sb, int ino)
{
unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
struct buffer_head *inode_bitmap_bh = NULL, *group_desc_bh = NULL;
struct ext4_group_desc *gdp;
ext4_group_t group;
int bit;
int err = -EFSCORRUPTED;
if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
goto out;
group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
if (IS_ERR(inode_bitmap_bh))
return PTR_ERR(inode_bitmap_bh);
if (ext4_test_bit(bit, inode_bitmap_bh->b_data)) {
err = 0;
goto out;
}
gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
if (!gdp || !group_desc_bh) {
err = -EINVAL;
goto out;
}
ext4_set_bit(bit, inode_bitmap_bh->b_data);
BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(NULL, NULL, inode_bitmap_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
err = sync_dirty_buffer(inode_bitmap_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
/* We may have to initialize the block bitmap if it isn't already */
if (ext4_has_group_desc_csum(sb) &&
gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
struct buffer_head *block_bitmap_bh;
block_bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(block_bitmap_bh)) {
err = PTR_ERR(block_bitmap_bh);
goto out;
}
BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
err = ext4_handle_dirty_metadata(NULL, NULL, block_bitmap_bh);
sync_dirty_buffer(block_bitmap_bh);
/* recheck and clear flag under lock if we still need to */
ext4_lock_group(sb, group);
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
ext4_free_group_clusters_set(sb, gdp,
ext4_free_clusters_after_init(sb, group, gdp));
ext4_block_bitmap_csum_set(sb, gdp, block_bitmap_bh);
ext4_group_desc_csum_set(sb, group, gdp);
}
ext4_unlock_group(sb, group);
brelse(block_bitmap_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
}
/* Update the relevant bg descriptor fields */
if (ext4_has_group_desc_csum(sb)) {
int free;
ext4_lock_group(sb, group); /* while we modify the bg desc */
free = EXT4_INODES_PER_GROUP(sb) -
ext4_itable_unused_count(sb, gdp);
if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
free = 0;
}
/*
* Check the relative inode number against the last used
* relative inode number in this group. if it is greater
* we need to update the bg_itable_unused count
*/
if (bit >= free)
ext4_itable_unused_set(sb, gdp,
(EXT4_INODES_PER_GROUP(sb) - bit - 1));
} else {
ext4_lock_group(sb, group);
}
ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
if (ext4_has_group_desc_csum(sb)) {
ext4_inode_bitmap_csum_set(sb, gdp, inode_bitmap_bh,
EXT4_INODES_PER_GROUP(sb) / 8);
ext4_group_desc_csum_set(sb, group, gdp);
}
ext4_unlock_group(sb, group);
err = ext4_handle_dirty_metadata(NULL, NULL, group_desc_bh);
sync_dirty_buffer(group_desc_bh);
out:
return err;
}
static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
bool encrypt)
{
struct super_block *sb = dir->i_sb;
int nblocks = 0;
#ifdef CONFIG_EXT4_FS_POSIX_ACL
struct posix_acl *p = get_inode_acl(dir, ACL_TYPE_DEFAULT);
if (IS_ERR(p))
return PTR_ERR(p);
if (p) {
int acl_size = p->a_count * sizeof(ext4_acl_entry);
nblocks += (S_ISDIR(mode) ? 2 : 1) *
__ext4_xattr_set_credits(sb, NULL /* inode */,
NULL /* block_bh */, acl_size,
true /* is_create */);
posix_acl_release(p);
}
#endif
#ifdef CONFIG_SECURITY
{
int num_security_xattrs = 1;
#ifdef CONFIG_INTEGRITY
num_security_xattrs++;
#endif
/*
* We assume that security xattrs are never more than 1k.
* In practice they are under 128 bytes.
*/
nblocks += num_security_xattrs *
__ext4_xattr_set_credits(sb, NULL /* inode */,
NULL /* block_bh */, 1024,
true /* is_create */);
}
#endif
if (encrypt)
nblocks += __ext4_xattr_set_credits(sb,
NULL /* inode */,
NULL /* block_bh */,
FSCRYPT_SET_CONTEXT_MAX_SIZE,
true /* is_create */);
return nblocks;
}
/*
* There are two policies for allocating an inode. If the new inode is
* a directory, then a forward search is made for a block group with both
* free space and a low directory-to-inode ratio; if that fails, then of
* the groups with above-average free space, that group with the fewest
* directories already is chosen.
*
* For other inodes, search forward from the parent directory's block
* group to find a free inode.
*/
struct inode *__ext4_new_inode(struct mnt_idmap *idmap,
handle_t *handle, struct inode *dir,
umode_t mode, const struct qstr *qstr,
__u32 goal, uid_t *owner, __u32 i_flags,
int handle_type, unsigned int line_no,
int nblocks)
{
struct super_block *sb;
struct buffer_head *inode_bitmap_bh = NULL;
struct buffer_head *group_desc_bh;
ext4_group_t ngroups, group = 0;
unsigned long ino = 0;
struct inode *inode;
struct ext4_group_desc *gdp = NULL;
struct ext4_inode_info *ei;
struct ext4_sb_info *sbi;
int ret2, err;
struct inode *ret;
ext4_group_t i;
ext4_group_t flex_group;
struct ext4_group_info *grp = NULL;
bool encrypt = false;
/* Cannot create files in a deleted directory */
if (!dir || !dir->i_nlink)
return ERR_PTR(-EPERM);
sb = dir->i_sb;
sbi = EXT4_SB(sb);
if (unlikely(ext4_forced_shutdown(sb)))
return ERR_PTR(-EIO);
ngroups = ext4_get_groups_count(sb);
trace_ext4_request_inode(dir, mode);
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
ei = EXT4_I(inode);
/*
* Initialize owners and quota early so that we don't have to account
* for quota initialization worst case in standard inode creating
* transaction
*/
if (owner) {
inode->i_mode = mode;
i_uid_write(inode, owner[0]);
i_gid_write(inode, owner[1]);
} else if (test_opt(sb, GRPID)) {
inode->i_mode = mode;
inode_fsuid_set(inode, idmap);
inode->i_gid = dir->i_gid;
} else
inode_init_owner(idmap, inode, dir, mode);
if (ext4_has_feature_project(sb) &&
ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT))
ei->i_projid = EXT4_I(dir)->i_projid;
else
ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID);
if (!(i_flags & EXT4_EA_INODE_FL)) {
err = fscrypt_prepare_new_inode(dir, inode, &encrypt);
if (err)
goto out;
}
err = dquot_initialize(inode);
if (err)
goto out;
if (!handle && sbi->s_journal && !(i_flags & EXT4_EA_INODE_FL)) {
ret2 = ext4_xattr_credits_for_new_inode(dir, mode, encrypt);
if (ret2 < 0) {
err = ret2;
goto out;
}
nblocks += ret2;
}
if (!goal)
goal = sbi->s_inode_goal;
if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) {
group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
ret2 = 0;
goto got_group;
}
if (S_ISDIR(mode))
ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
else
ret2 = find_group_other(sb, dir, &group, mode);
got_group:
EXT4_I(dir)->i_last_alloc_group = group;
err = -ENOSPC;
if (ret2 == -1)
goto out;
/*
* Normally we will only go through one pass of this loop,
* unless we get unlucky and it turns out the group we selected
* had its last inode grabbed by someone else.
*/
for (i = 0; i < ngroups; i++, ino = 0) {
err = -EIO;
gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
if (!gdp)
goto out;
/*
* Check free inodes count before loading bitmap.
*/
if (ext4_free_inodes_count(sb, gdp) == 0)
goto next_group;
if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
grp = ext4_get_group_info(sb, group);
/*
* Skip groups with already-known suspicious inode
* tables
*/
if (!grp || EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
goto next_group;
}
brelse(inode_bitmap_bh);
inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
/* Skip groups with suspicious inode tables */
if (((!(sbi->s_mount_state & EXT4_FC_REPLAY))
&& EXT4_MB_GRP_IBITMAP_CORRUPT(grp)) ||
IS_ERR(inode_bitmap_bh)) {
inode_bitmap_bh = NULL;
goto next_group;
}
repeat_in_this_group:
ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
if (!ret2)
goto next_group;
if (group == 0 && (ino + 1) < EXT4_FIRST_INO(sb)) {
ext4_error(sb, "reserved inode found cleared - "
"inode=%lu", ino + 1);
ext4_mark_group_bitmap_corrupted(sb, group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
goto next_group;
}
if ((!(sbi->s_mount_state & EXT4_FC_REPLAY)) && !handle) {
BUG_ON(nblocks <= 0);
handle = __ext4_journal_start_sb(NULL, dir->i_sb,
line_no, handle_type, nblocks, 0,
ext4_trans_default_revoke_credits(sb));
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
ext4_std_error(sb, err);
goto out;
}
}
BUFFER_TRACE(inode_bitmap_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, inode_bitmap_bh,
EXT4_JTR_NONE);
if (err) {
ext4_std_error(sb, err);
goto out;
}
ext4_lock_group(sb, group);
ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data);
if (ret2) {
/* Someone already took the bit. Repeat the search
* with lock held.
*/
ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
if (ret2) {
ext4_set_bit(ino, inode_bitmap_bh->b_data);
ret2 = 0;
} else {
ret2 = 1; /* we didn't grab the inode */
}
}
ext4_unlock_group(sb, group);
ino++; /* the inode bitmap is zero-based */
if (!ret2)
goto got; /* we grabbed the inode! */
if (ino < EXT4_INODES_PER_GROUP(sb))
goto repeat_in_this_group;
next_group:
if (++group == ngroups)
group = 0;
}
err = -ENOSPC;
goto out;
got:
BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
BUFFER_TRACE(group_desc_bh, "get_write_access");
err = ext4_journal_get_write_access(handle, sb, group_desc_bh,
EXT4_JTR_NONE);
if (err) {
ext4_std_error(sb, err);
goto out;
}
/* We may have to initialize the block bitmap if it isn't already */
if (ext4_has_group_desc_csum(sb) &&
gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
struct buffer_head *block_bitmap_bh;
block_bitmap_bh = ext4_read_block_bitmap(sb, group);
if (IS_ERR(block_bitmap_bh)) {
err = PTR_ERR(block_bitmap_bh);
goto out;
}
BUFFER_TRACE(block_bitmap_bh, "get block bitmap access");
err = ext4_journal_get_write_access(handle, sb, block_bitmap_bh,
EXT4_JTR_NONE);
if (err) {
brelse(block_bitmap_bh);
ext4_std_error(sb, err);
goto out;
}
BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh);
/* recheck and clear flag under lock if we still need to */
ext4_lock_group(sb, group);
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
ext4_free_group_clusters_set(sb, gdp,
ext4_free_clusters_after_init(sb, group, gdp));
ext4_block_bitmap_csum_set(sb, gdp, block_bitmap_bh);
ext4_group_desc_csum_set(sb, group, gdp);
}
ext4_unlock_group(sb, group);
brelse(block_bitmap_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
}
/* Update the relevant bg descriptor fields */
if (ext4_has_group_desc_csum(sb)) {
int free;
struct ext4_group_info *grp = NULL;
if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
grp = ext4_get_group_info(sb, group);
if (!grp) {
err = -EFSCORRUPTED;
goto out;
}
down_read(&grp->alloc_sem); /*
* protect vs itable
* lazyinit
*/
}
ext4_lock_group(sb, group); /* while we modify the bg desc */
free = EXT4_INODES_PER_GROUP(sb) -
ext4_itable_unused_count(sb, gdp);
if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
free = 0;
}
/*
* Check the relative inode number against the last used
* relative inode number in this group. if it is greater
* we need to update the bg_itable_unused count
*/
if (ino > free)
ext4_itable_unused_set(sb, gdp,
(EXT4_INODES_PER_GROUP(sb) - ino));
if (!(sbi->s_mount_state & EXT4_FC_REPLAY))
up_read(&grp->alloc_sem);
} else {
ext4_lock_group(sb, group);
}
ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
if (S_ISDIR(mode)) {
ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
if (sbi->s_log_groups_per_flex) {
ext4_group_t f = ext4_flex_group(sbi, group);
atomic_inc(&sbi_array_rcu_deref(sbi, s_flex_groups,
f)->used_dirs);
}
}
if (ext4_has_group_desc_csum(sb)) {
ext4_inode_bitmap_csum_set(sb, gdp, inode_bitmap_bh,
EXT4_INODES_PER_GROUP(sb) / 8);
ext4_group_desc_csum_set(sb, group, gdp);
}
ext4_unlock_group(sb, group);
BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
if (err) {
ext4_std_error(sb, err);
goto out;
}
percpu_counter_dec(&sbi->s_freeinodes_counter);
if (S_ISDIR(mode))
percpu_counter_inc(&sbi->s_dirs_counter);
if (sbi->s_log_groups_per_flex) {
flex_group = ext4_flex_group(sbi, group);
atomic_dec(&sbi_array_rcu_deref(sbi, s_flex_groups,
flex_group)->free_inodes);
}
inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
/* This is the optimal IO size (for stat), not the fs block size */
inode->i_blocks = 0;
inode->i_mtime = inode->i_atime = inode_set_ctime_current(inode);
ei->i_crtime = inode->i_mtime;
memset(ei->i_data, 0, sizeof(ei->i_data));
ei->i_dir_start_lookup = 0;
ei->i_disksize = 0;
/* Don't inherit extent flag from directory, amongst others. */
ei->i_flags =
ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
ei->i_flags |= i_flags;
ei->i_file_acl = 0;
ei->i_dtime = 0;
ei->i_block_group = group;
ei->i_last_alloc_group = ~0;
ext4_set_inode_flags(inode, true);
if (IS_DIRSYNC(inode))
ext4_handle_sync(handle);
if (insert_inode_locked(inode) < 0) {
/*
* Likely a bitmap corruption causing inode to be allocated
* twice.
*/
err = -EIO;
ext4_error(sb, "failed to insert inode %lu: doubly allocated?",
inode->i_ino);
ext4_mark_group_bitmap_corrupted(sb, group,
EXT4_GROUP_INFO_IBITMAP_CORRUPT);
goto out;
}
inode->i_generation = get_random_u32();
/* Precompute checksum seed for inode metadata */
if (ext4_has_metadata_csum(sb)) {
__u32 csum;
__le32 inum = cpu_to_le32(inode->i_ino);
__le32 gen = cpu_to_le32(inode->i_generation);
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
sizeof(inum));
ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
sizeof(gen));
}
ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
ext4_set_inode_state(inode, EXT4_STATE_NEW);
ei->i_extra_isize = sbi->s_want_extra_isize;
ei->i_inline_off = 0;
if (ext4_has_feature_inline_data(sb) &&
(!(ei->i_flags & EXT4_DAX_FL) || S_ISDIR(mode)))
ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
ret = inode;
err = dquot_alloc_inode(inode);
if (err)
goto fail_drop;
/*
* Since the encryption xattr will always be unique, create it first so
* that it's less likely to end up in an external xattr block and
* prevent its deduplication.
*/
if (encrypt) {
err = fscrypt_set_context(inode, handle);
if (err)
goto fail_free_drop;
}
if (!(ei->i_flags & EXT4_EA_INODE_FL)) {
err = ext4_init_acl(handle, inode, dir);
if (err)
goto fail_free_drop;
err = ext4_init_security(handle, inode, dir, qstr);
if (err)
goto fail_free_drop;
}
if (ext4_has_feature_extents(sb)) {
/* set extent flag only for directory, file and normal symlink*/
if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
ext4_ext_tree_init(handle, inode);
}
}
if (ext4_handle_valid(handle)) {
ei->i_sync_tid = handle->h_transaction->t_tid;
ei->i_datasync_tid = handle->h_transaction->t_tid;
}
err = ext4_mark_inode_dirty(handle, inode);
if (err) {
ext4_std_error(sb, err);
goto fail_free_drop;
}
ext4_debug("allocating inode %lu\n", inode->i_ino);
trace_ext4_allocate_inode(inode, dir, mode);
brelse(inode_bitmap_bh);
return ret;
fail_free_drop:
dquot_free_inode(inode);
fail_drop:
clear_nlink(inode);
unlock_new_inode(inode);
out:
dquot_drop(inode);
inode->i_flags |= S_NOQUOTA;
iput(inode);
brelse(inode_bitmap_bh);
return ERR_PTR(err);
}
/* Verify that we are loading a valid orphan from disk */
struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
{
unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
ext4_group_t block_group;
int bit;
struct buffer_head *bitmap_bh = NULL;
struct inode *inode = NULL;
int err = -EFSCORRUPTED;
if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
goto bad_orphan;
block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
if (IS_ERR(bitmap_bh))
return ERR_CAST(bitmap_bh);
/* Having the inode bit set should be a 100% indicator that this
* is a valid orphan (no e2fsck run on fs). Orphans also include
* inodes that were being truncated, so we can't check i_nlink==0.
*/
if (!ext4_test_bit(bit, bitmap_bh->b_data))
goto bad_orphan;
inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
ext4_error_err(sb, -err,
"couldn't read orphan inode %lu (err %d)",
ino, err);
brelse(bitmap_bh);
return inode;
}
/*
* If the orphans has i_nlinks > 0 then it should be able to
* be truncated, otherwise it won't be removed from the orphan
* list during processing and an infinite loop will result.
* Similarly, it must not be a bad inode.
*/
if ((inode->i_nlink && !ext4_can_truncate(inode)) ||
is_bad_inode(inode))
goto bad_orphan;
if (NEXT_ORPHAN(inode) > max_ino)
goto bad_orphan;
brelse(bitmap_bh);
return inode;
bad_orphan:
ext4_error(sb, "bad orphan inode %lu", ino);
if (bitmap_bh)
printk(KERN_ERR "ext4_test_bit(bit=%d, block=%llu) = %d\n",
bit, (unsigned long long)bitmap_bh->b_blocknr,
ext4_test_bit(bit, bitmap_bh->b_data));
if (inode) {
printk(KERN_ERR "is_bad_inode(inode)=%d\n",
is_bad_inode(inode));
printk(KERN_ERR "NEXT_ORPHAN(inode)=%u\n",
NEXT_ORPHAN(inode));
printk(KERN_ERR "max_ino=%lu\n", max_ino);
printk(KERN_ERR "i_nlink=%u\n", inode->i_nlink);
/* Avoid freeing blocks if we got a bad deleted inode */
if (inode->i_nlink == 0)
inode->i_blocks = 0;
iput(inode);
}
brelse(bitmap_bh);
return ERR_PTR(err);
}
unsigned long ext4_count_free_inodes(struct super_block *sb)
{
unsigned long desc_count;
struct ext4_group_desc *gdp;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
#ifdef EXT4FS_DEBUG
struct ext4_super_block *es;
unsigned long bitmap_count, x;
struct buffer_head *bitmap_bh = NULL;
es = EXT4_SB(sb)->s_es;
desc_count = 0;
bitmap_count = 0;
gdp = NULL;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
desc_count += ext4_free_inodes_count(sb, gdp);
brelse(bitmap_bh);
bitmap_bh = ext4_read_inode_bitmap(sb, i);
if (IS_ERR(bitmap_bh)) {
bitmap_bh = NULL;
continue;
}
x = ext4_count_free(bitmap_bh->b_data,
EXT4_INODES_PER_GROUP(sb) / 8);
printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
(unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
bitmap_count += x;
}
brelse(bitmap_bh);
printk(KERN_DEBUG "ext4_count_free_inodes: "
"stored = %u, computed = %lu, %lu\n",
le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
return desc_count;
#else
desc_count = 0;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
desc_count += ext4_free_inodes_count(sb, gdp);
cond_resched();
}
return desc_count;
#endif
}
/* Called at mount-time, super-block is locked */
unsigned long ext4_count_dirs(struct super_block * sb)
{
unsigned long count = 0;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
for (i = 0; i < ngroups; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
count += ext4_used_dirs_count(sb, gdp);
}
return count;
}
/*
* Zeroes not yet zeroed inode table - just write zeroes through the whole
* inode table. Must be called without any spinlock held. The only place
* where it is called from on active part of filesystem is ext4lazyinit
* thread, so we do not need any special locks, however we have to prevent
* inode allocation from the current group, so we take alloc_sem lock, to
* block ext4_new_inode() until we are finished.
*/
int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
int barrier)
{
struct ext4_group_info *grp = ext4_get_group_info(sb, group);
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
struct buffer_head *group_desc_bh;
handle_t *handle;
ext4_fsblk_t blk;
int num, ret = 0, used_blks = 0;
unsigned long used_inos = 0;
gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
if (!gdp || !grp)
goto out;
/*
* We do not need to lock this, because we are the only one
* handling this flag.
*/
if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
goto out;
handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
down_write(&grp->alloc_sem);
/*
* If inode bitmap was already initialized there may be some
* used inodes so we need to skip blocks with used inodes in
* inode table.
*/
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
used_inos = EXT4_INODES_PER_GROUP(sb) -
ext4_itable_unused_count(sb, gdp);
used_blks = DIV_ROUND_UP(used_inos, sbi->s_inodes_per_block);
/* Bogus inode unused count? */
if (used_blks < 0 || used_blks > sbi->s_itb_per_group) {
ext4_error(sb, "Something is wrong with group %u: "
"used itable blocks: %d; "
"itable unused count: %u",
group, used_blks,
ext4_itable_unused_count(sb, gdp));
ret = 1;
goto err_out;
}
used_inos += group * EXT4_INODES_PER_GROUP(sb);
/*
* Are there some uninitialized inodes in the inode table
* before the first normal inode?
*/
if ((used_blks != sbi->s_itb_per_group) &&
(used_inos < EXT4_FIRST_INO(sb))) {
ext4_error(sb, "Something is wrong with group %u: "
"itable unused count: %u; "
"itables initialized count: %ld",
group, ext4_itable_unused_count(sb, gdp),
used_inos);
ret = 1;
goto err_out;
}
}
blk = ext4_inode_table(sb, gdp) + used_blks;
num = sbi->s_itb_per_group - used_blks;
BUFFER_TRACE(group_desc_bh, "get_write_access");
ret = ext4_journal_get_write_access(handle, sb, group_desc_bh,
EXT4_JTR_NONE);
if (ret)
goto err_out;
/*
* Skip zeroout if the inode table is full. But we set the ZEROED
* flag anyway, because obviously, when it is full it does not need
* further zeroing.
*/
if (unlikely(num == 0))
goto skip_zeroout;
ext4_debug("going to zero out inode table in group %d\n",
group);
ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
if (ret < 0)
goto err_out;
if (barrier)
blkdev_issue_flush(sb->s_bdev);
skip_zeroout:
ext4_lock_group(sb, group);
gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
ext4_group_desc_csum_set(sb, group, gdp);
ext4_unlock_group(sb, group);
BUFFER_TRACE(group_desc_bh,
"call ext4_handle_dirty_metadata");
ret = ext4_handle_dirty_metadata(handle, NULL,
group_desc_bh);
err_out:
up_write(&grp->alloc_sem);
ext4_journal_stop(handle);
out:
return ret;
}
| linux-master | fs/ext4/ialloc.c |
// SPDX-License-Identifier: GPL-2.0
#include <linux/quotaops.h>
#include <linux/uuid.h>
#include "ext4.h"
#include "xattr.h"
#include "ext4_jbd2.h"
static void ext4_fname_from_fscrypt_name(struct ext4_filename *dst,
const struct fscrypt_name *src)
{
memset(dst, 0, sizeof(*dst));
dst->usr_fname = src->usr_fname;
dst->disk_name = src->disk_name;
dst->hinfo.hash = src->hash;
dst->hinfo.minor_hash = src->minor_hash;
dst->crypto_buf = src->crypto_buf;
}
int ext4_fname_setup_filename(struct inode *dir, const struct qstr *iname,
int lookup, struct ext4_filename *fname)
{
struct fscrypt_name name;
int err;
err = fscrypt_setup_filename(dir, iname, lookup, &name);
if (err)
return err;
ext4_fname_from_fscrypt_name(fname, &name);
#if IS_ENABLED(CONFIG_UNICODE)
err = ext4_fname_setup_ci_filename(dir, iname, fname);
if (err)
ext4_fname_free_filename(fname);
#endif
return err;
}
int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry,
struct ext4_filename *fname)
{
struct fscrypt_name name;
int err;
err = fscrypt_prepare_lookup(dir, dentry, &name);
if (err)
return err;
ext4_fname_from_fscrypt_name(fname, &name);
#if IS_ENABLED(CONFIG_UNICODE)
err = ext4_fname_setup_ci_filename(dir, &dentry->d_name, fname);
if (err)
ext4_fname_free_filename(fname);
#endif
return err;
}
void ext4_fname_free_filename(struct ext4_filename *fname)
{
struct fscrypt_name name;
name.crypto_buf = fname->crypto_buf;
fscrypt_free_filename(&name);
fname->crypto_buf.name = NULL;
fname->usr_fname = NULL;
fname->disk_name.name = NULL;
#if IS_ENABLED(CONFIG_UNICODE)
kfree(fname->cf_name.name);
fname->cf_name.name = NULL;
#endif
}
static bool uuid_is_zero(__u8 u[16])
{
int i;
for (i = 0; i < 16; i++)
if (u[i])
return false;
return true;
}
int ext4_ioctl_get_encryption_pwsalt(struct file *filp, void __user *arg)
{
struct super_block *sb = file_inode(filp)->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int err, err2;
handle_t *handle;
if (!ext4_has_feature_encrypt(sb))
return -EOPNOTSUPP;
if (uuid_is_zero(sbi->s_es->s_encrypt_pw_salt)) {
err = mnt_want_write_file(filp);
if (err)
return err;
handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto pwsalt_err_exit;
}
err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
EXT4_JTR_NONE);
if (err)
goto pwsalt_err_journal;
lock_buffer(sbi->s_sbh);
generate_random_uuid(sbi->s_es->s_encrypt_pw_salt);
ext4_superblock_csum_set(sb);
unlock_buffer(sbi->s_sbh);
err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
pwsalt_err_journal:
err2 = ext4_journal_stop(handle);
if (err2 && !err)
err = err2;
pwsalt_err_exit:
mnt_drop_write_file(filp);
if (err)
return err;
}
if (copy_to_user(arg, sbi->s_es->s_encrypt_pw_salt, 16))
return -EFAULT;
return 0;
}
static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
{
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
}
static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
void *fs_data)
{
handle_t *handle = fs_data;
int res, res2, credits, retries = 0;
/*
* Encrypting the root directory is not allowed because e2fsck expects
* lost+found to exist and be unencrypted, and encrypting the root
* directory would imply encrypting the lost+found directory as well as
* the filename "lost+found" itself.
*/
if (inode->i_ino == EXT4_ROOT_INO)
return -EPERM;
if (WARN_ON_ONCE(IS_DAX(inode) && i_size_read(inode)))
return -EINVAL;
if (ext4_test_inode_flag(inode, EXT4_INODE_DAX))
return -EOPNOTSUPP;
res = ext4_convert_inline_data(inode);
if (res)
return res;
/*
* If a journal handle was specified, then the encryption context is
* being set on a new inode via inheritance and is part of a larger
* transaction to create the inode. Otherwise the encryption context is
* being set on an existing inode in its own transaction. Only in the
* latter case should the "retry on ENOSPC" logic be used.
*/
if (handle) {
res = ext4_xattr_set_handle(handle, inode,
EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, 0);
if (!res) {
ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
ext4_clear_inode_state(inode,
EXT4_STATE_MAY_INLINE_DATA);
/*
* Update inode->i_flags - S_ENCRYPTED will be enabled,
* S_DAX may be disabled
*/
ext4_set_inode_flags(inode, false);
}
return res;
}
res = dquot_initialize(inode);
if (res)
return res;
retry:
res = ext4_xattr_set_credits(inode, len, false /* is_create */,
&credits);
if (res)
return res;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle))
return PTR_ERR(handle);
res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, 0);
if (!res) {
ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
/*
* Update inode->i_flags - S_ENCRYPTED will be enabled,
* S_DAX may be disabled
*/
ext4_set_inode_flags(inode, false);
res = ext4_mark_inode_dirty(handle, inode);
if (res)
EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
}
res2 = ext4_journal_stop(handle);
if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (!res)
res = res2;
return res;
}
static const union fscrypt_policy *ext4_get_dummy_policy(struct super_block *sb)
{
return EXT4_SB(sb)->s_dummy_enc_policy.policy;
}
static bool ext4_has_stable_inodes(struct super_block *sb)
{
return ext4_has_feature_stable_inodes(sb);
}
static void ext4_get_ino_and_lblk_bits(struct super_block *sb,
int *ino_bits_ret, int *lblk_bits_ret)
{
*ino_bits_ret = 8 * sizeof(EXT4_SB(sb)->s_es->s_inodes_count);
*lblk_bits_ret = 8 * sizeof(ext4_lblk_t);
}
const struct fscrypt_operations ext4_cryptops = {
.key_prefix = "ext4:",
.get_context = ext4_get_context,
.set_context = ext4_set_context,
.get_dummy_policy = ext4_get_dummy_policy,
.empty_dir = ext4_empty_dir,
.has_stable_inodes = ext4_has_stable_inodes,
.get_ino_and_lblk_bits = ext4_get_ino_and_lblk_bits,
};
| linux-master | fs/ext4/crypto.c |
// SPDX-License-Identifier: GPL-2.0
/*
* fs/ext4/fast_commit.c
*
* Written by Harshad Shirwadkar <[email protected]>
*
* Ext4 fast commits routines.
*/
#include "ext4.h"
#include "ext4_jbd2.h"
#include "ext4_extents.h"
#include "mballoc.h"
/*
* Ext4 Fast Commits
* -----------------
*
* Ext4 fast commits implement fine grained journalling for Ext4.
*
* Fast commits are organized as a log of tag-length-value (TLV) structs. (See
* struct ext4_fc_tl). Each TLV contains some delta that is replayed TLV by
* TLV during the recovery phase. For the scenarios for which we currently
* don't have replay code, fast commit falls back to full commits.
* Fast commits record delta in one of the following three categories.
*
* (A) Directory entry updates:
*
* - EXT4_FC_TAG_UNLINK - records directory entry unlink
* - EXT4_FC_TAG_LINK - records directory entry link
* - EXT4_FC_TAG_CREAT - records inode and directory entry creation
*
* (B) File specific data range updates:
*
* - EXT4_FC_TAG_ADD_RANGE - records addition of new blocks to an inode
* - EXT4_FC_TAG_DEL_RANGE - records deletion of blocks from an inode
*
* (C) Inode metadata (mtime / ctime etc):
*
* - EXT4_FC_TAG_INODE - record the inode that should be replayed
* during recovery. Note that iblocks field is
* not replayed and instead derived during
* replay.
* Commit Operation
* ----------------
* With fast commits, we maintain all the directory entry operations in the
* order in which they are issued in an in-memory queue. This queue is flushed
* to disk during the commit operation. We also maintain a list of inodes
* that need to be committed during a fast commit in another in memory queue of
* inodes. During the commit operation, we commit in the following order:
*
* [1] Lock inodes for any further data updates by setting COMMITTING state
* [2] Submit data buffers of all the inodes
* [3] Wait for [2] to complete
* [4] Commit all the directory entry updates in the fast commit space
* [5] Commit all the changed inode structures
* [6] Write tail tag (this tag ensures the atomicity, please read the following
* section for more details).
* [7] Wait for [4], [5] and [6] to complete.
*
* All the inode updates must call ext4_fc_start_update() before starting an
* update. If such an ongoing update is present, fast commit waits for it to
* complete. The completion of such an update is marked by
* ext4_fc_stop_update().
*
* Fast Commit Ineligibility
* -------------------------
*
* Not all operations are supported by fast commits today (e.g extended
* attributes). Fast commit ineligibility is marked by calling
* ext4_fc_mark_ineligible(): This makes next fast commit operation to fall back
* to full commit.
*
* Atomicity of commits
* --------------------
* In order to guarantee atomicity during the commit operation, fast commit
* uses "EXT4_FC_TAG_TAIL" tag that marks a fast commit as complete. Tail
* tag contains CRC of the contents and TID of the transaction after which
* this fast commit should be applied. Recovery code replays fast commit
* logs only if there's at least 1 valid tail present. For every fast commit
* operation, there is 1 tail. This means, we may end up with multiple tails
* in the fast commit space. Here's an example:
*
* - Create a new file A and remove existing file B
* - fsync()
* - Append contents to file A
* - Truncate file A
* - fsync()
*
* The fast commit space at the end of above operations would look like this:
* [HEAD] [CREAT A] [UNLINK B] [TAIL] [ADD_RANGE A] [DEL_RANGE A] [TAIL]
* |<--- Fast Commit 1 --->|<--- Fast Commit 2 ---->|
*
* Replay code should thus check for all the valid tails in the FC area.
*
* Fast Commit Replay Idempotence
* ------------------------------
*
* Fast commits tags are idempotent in nature provided the recovery code follows
* certain rules. The guiding principle that the commit path follows while
* committing is that it stores the result of a particular operation instead of
* storing the procedure.
*
* Let's consider this rename operation: 'mv /a /b'. Let's assume dirent '/a'
* was associated with inode 10. During fast commit, instead of storing this
* operation as a procedure "rename a to b", we store the resulting file system
* state as a "series" of outcomes:
*
* - Link dirent b to inode 10
* - Unlink dirent a
* - Inode <10> with valid refcount
*
* Now when recovery code runs, it needs "enforce" this state on the file
* system. This is what guarantees idempotence of fast commit replay.
*
* Let's take an example of a procedure that is not idempotent and see how fast
* commits make it idempotent. Consider following sequence of operations:
*
* rm A; mv B A; read A
* (x) (y) (z)
*
* (x), (y) and (z) are the points at which we can crash. If we store this
* sequence of operations as is then the replay is not idempotent. Let's say
* while in replay, we crash at (z). During the second replay, file A (which was
* actually created as a result of "mv B A" operation) would get deleted. Thus,
* file named A would be absent when we try to read A. So, this sequence of
* operations is not idempotent. However, as mentioned above, instead of storing
* the procedure fast commits store the outcome of each procedure. Thus the fast
* commit log for above procedure would be as follows:
*
* (Let's assume dirent A was linked to inode 10 and dirent B was linked to
* inode 11 before the replay)
*
* [Unlink A] [Link A to inode 11] [Unlink B] [Inode 11]
* (w) (x) (y) (z)
*
* If we crash at (z), we will have file A linked to inode 11. During the second
* replay, we will remove file A (inode 11). But we will create it back and make
* it point to inode 11. We won't find B, so we'll just skip that step. At this
* point, the refcount for inode 11 is not reliable, but that gets fixed by the
* replay of last inode 11 tag. Crashes at points (w), (x) and (y) get handled
* similarly. Thus, by converting a non-idempotent procedure into a series of
* idempotent outcomes, fast commits ensured idempotence during the replay.
*
* TODOs
* -----
*
* 0) Fast commit replay path hardening: Fast commit replay code should use
* journal handles to make sure all the updates it does during the replay
* path are atomic. With that if we crash during fast commit replay, after
* trying to do recovery again, we will find a file system where fast commit
* area is invalid (because new full commit would be found). In order to deal
* with that, fast commit replay code should ensure that the "FC_REPLAY"
* superblock state is persisted before starting the replay, so that after
* the crash, fast commit recovery code can look at that flag and perform
* fast commit recovery even if that area is invalidated by later full
* commits.
*
* 1) Fast commit's commit path locks the entire file system during fast
* commit. This has significant performance penalty. Instead of that, we
* should use ext4_fc_start/stop_update functions to start inode level
* updates from ext4_journal_start/stop. Once we do that we can drop file
* system locking during commit path.
*
* 2) Handle more ineligible cases.
*/
#include <trace/events/ext4.h>
static struct kmem_cache *ext4_fc_dentry_cachep;
static void ext4_end_buffer_io_sync(struct buffer_head *bh, int uptodate)
{
BUFFER_TRACE(bh, "");
if (uptodate) {
ext4_debug("%s: Block %lld up-to-date",
__func__, bh->b_blocknr);
set_buffer_uptodate(bh);
} else {
ext4_debug("%s: Block %lld not up-to-date",
__func__, bh->b_blocknr);
clear_buffer_uptodate(bh);
}
unlock_buffer(bh);
}
static inline void ext4_fc_reset_inode(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
ei->i_fc_lblk_start = 0;
ei->i_fc_lblk_len = 0;
}
void ext4_fc_init_inode(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_fc_reset_inode(inode);
ext4_clear_inode_state(inode, EXT4_STATE_FC_COMMITTING);
INIT_LIST_HEAD(&ei->i_fc_list);
INIT_LIST_HEAD(&ei->i_fc_dilist);
init_waitqueue_head(&ei->i_fc_wait);
atomic_set(&ei->i_fc_updates, 0);
}
/* This function must be called with sbi->s_fc_lock held. */
static void ext4_fc_wait_committing_inode(struct inode *inode)
__releases(&EXT4_SB(inode->i_sb)->s_fc_lock)
{
wait_queue_head_t *wq;
struct ext4_inode_info *ei = EXT4_I(inode);
#if (BITS_PER_LONG < 64)
DEFINE_WAIT_BIT(wait, &ei->i_state_flags,
EXT4_STATE_FC_COMMITTING);
wq = bit_waitqueue(&ei->i_state_flags,
EXT4_STATE_FC_COMMITTING);
#else
DEFINE_WAIT_BIT(wait, &ei->i_flags,
EXT4_STATE_FC_COMMITTING);
wq = bit_waitqueue(&ei->i_flags,
EXT4_STATE_FC_COMMITTING);
#endif
lockdep_assert_held(&EXT4_SB(inode->i_sb)->s_fc_lock);
prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
spin_unlock(&EXT4_SB(inode->i_sb)->s_fc_lock);
schedule();
finish_wait(wq, &wait.wq_entry);
}
static bool ext4_fc_disabled(struct super_block *sb)
{
return (!test_opt2(sb, JOURNAL_FAST_COMMIT) ||
(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY));
}
/*
* Inform Ext4's fast about start of an inode update
*
* This function is called by the high level call VFS callbacks before
* performing any inode update. This function blocks if there's an ongoing
* fast commit on the inode in question.
*/
void ext4_fc_start_update(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
if (ext4_fc_disabled(inode->i_sb))
return;
restart:
spin_lock(&EXT4_SB(inode->i_sb)->s_fc_lock);
if (list_empty(&ei->i_fc_list))
goto out;
if (ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING)) {
ext4_fc_wait_committing_inode(inode);
goto restart;
}
out:
atomic_inc(&ei->i_fc_updates);
spin_unlock(&EXT4_SB(inode->i_sb)->s_fc_lock);
}
/*
* Stop inode update and wake up waiting fast commits if any.
*/
void ext4_fc_stop_update(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
if (ext4_fc_disabled(inode->i_sb))
return;
if (atomic_dec_and_test(&ei->i_fc_updates))
wake_up_all(&ei->i_fc_wait);
}
/*
* Remove inode from fast commit list. If the inode is being committed
* we wait until inode commit is done.
*/
void ext4_fc_del(struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
struct ext4_fc_dentry_update *fc_dentry;
if (ext4_fc_disabled(inode->i_sb))
return;
restart:
spin_lock(&EXT4_SB(inode->i_sb)->s_fc_lock);
if (list_empty(&ei->i_fc_list) && list_empty(&ei->i_fc_dilist)) {
spin_unlock(&EXT4_SB(inode->i_sb)->s_fc_lock);
return;
}
if (ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING)) {
ext4_fc_wait_committing_inode(inode);
goto restart;
}
if (!list_empty(&ei->i_fc_list))
list_del_init(&ei->i_fc_list);
/*
* Since this inode is getting removed, let's also remove all FC
* dentry create references, since it is not needed to log it anyways.
*/
if (list_empty(&ei->i_fc_dilist)) {
spin_unlock(&sbi->s_fc_lock);
return;
}
fc_dentry = list_first_entry(&ei->i_fc_dilist, struct ext4_fc_dentry_update, fcd_dilist);
WARN_ON(fc_dentry->fcd_op != EXT4_FC_TAG_CREAT);
list_del_init(&fc_dentry->fcd_list);
list_del_init(&fc_dentry->fcd_dilist);
WARN_ON(!list_empty(&ei->i_fc_dilist));
spin_unlock(&sbi->s_fc_lock);
if (fc_dentry->fcd_name.name &&
fc_dentry->fcd_name.len > DNAME_INLINE_LEN)
kfree(fc_dentry->fcd_name.name);
kmem_cache_free(ext4_fc_dentry_cachep, fc_dentry);
return;
}
/*
* Mark file system as fast commit ineligible, and record latest
* ineligible transaction tid. This means until the recorded
* transaction, commit operation would result in a full jbd2 commit.
*/
void ext4_fc_mark_ineligible(struct super_block *sb, int reason, handle_t *handle)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
tid_t tid;
if (ext4_fc_disabled(sb))
return;
ext4_set_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
if (handle && !IS_ERR(handle))
tid = handle->h_transaction->t_tid;
else {
read_lock(&sbi->s_journal->j_state_lock);
tid = sbi->s_journal->j_running_transaction ?
sbi->s_journal->j_running_transaction->t_tid : 0;
read_unlock(&sbi->s_journal->j_state_lock);
}
spin_lock(&sbi->s_fc_lock);
if (sbi->s_fc_ineligible_tid < tid)
sbi->s_fc_ineligible_tid = tid;
spin_unlock(&sbi->s_fc_lock);
WARN_ON(reason >= EXT4_FC_REASON_MAX);
sbi->s_fc_stats.fc_ineligible_reason_count[reason]++;
}
/*
* Generic fast commit tracking function. If this is the first time this we are
* called after a full commit, we initialize fast commit fields and then call
* __fc_track_fn() with update = 0. If we have already been called after a full
* commit, we pass update = 1. Based on that, the track function can determine
* if it needs to track a field for the first time or if it needs to just
* update the previously tracked value.
*
* If enqueue is set, this function enqueues the inode in fast commit list.
*/
static int ext4_fc_track_template(
handle_t *handle, struct inode *inode,
int (*__fc_track_fn)(struct inode *, void *, bool),
void *args, int enqueue)
{
bool update = false;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
tid_t tid = 0;
int ret;
tid = handle->h_transaction->t_tid;
mutex_lock(&ei->i_fc_lock);
if (tid == ei->i_sync_tid) {
update = true;
} else {
ext4_fc_reset_inode(inode);
ei->i_sync_tid = tid;
}
ret = __fc_track_fn(inode, args, update);
mutex_unlock(&ei->i_fc_lock);
if (!enqueue)
return ret;
spin_lock(&sbi->s_fc_lock);
if (list_empty(&EXT4_I(inode)->i_fc_list))
list_add_tail(&EXT4_I(inode)->i_fc_list,
(sbi->s_journal->j_flags & JBD2_FULL_COMMIT_ONGOING ||
sbi->s_journal->j_flags & JBD2_FAST_COMMIT_ONGOING) ?
&sbi->s_fc_q[FC_Q_STAGING] :
&sbi->s_fc_q[FC_Q_MAIN]);
spin_unlock(&sbi->s_fc_lock);
return ret;
}
struct __track_dentry_update_args {
struct dentry *dentry;
int op;
};
/* __track_fn for directory entry updates. Called with ei->i_fc_lock. */
static int __track_dentry_update(struct inode *inode, void *arg, bool update)
{
struct ext4_fc_dentry_update *node;
struct ext4_inode_info *ei = EXT4_I(inode);
struct __track_dentry_update_args *dentry_update =
(struct __track_dentry_update_args *)arg;
struct dentry *dentry = dentry_update->dentry;
struct inode *dir = dentry->d_parent->d_inode;
struct super_block *sb = inode->i_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
mutex_unlock(&ei->i_fc_lock);
if (IS_ENCRYPTED(dir)) {
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_ENCRYPTED_FILENAME,
NULL);
mutex_lock(&ei->i_fc_lock);
return -EOPNOTSUPP;
}
node = kmem_cache_alloc(ext4_fc_dentry_cachep, GFP_NOFS);
if (!node) {
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_NOMEM, NULL);
mutex_lock(&ei->i_fc_lock);
return -ENOMEM;
}
node->fcd_op = dentry_update->op;
node->fcd_parent = dir->i_ino;
node->fcd_ino = inode->i_ino;
if (dentry->d_name.len > DNAME_INLINE_LEN) {
node->fcd_name.name = kmalloc(dentry->d_name.len, GFP_NOFS);
if (!node->fcd_name.name) {
kmem_cache_free(ext4_fc_dentry_cachep, node);
ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_NOMEM, NULL);
mutex_lock(&ei->i_fc_lock);
return -ENOMEM;
}
memcpy((u8 *)node->fcd_name.name, dentry->d_name.name,
dentry->d_name.len);
} else {
memcpy(node->fcd_iname, dentry->d_name.name,
dentry->d_name.len);
node->fcd_name.name = node->fcd_iname;
}
node->fcd_name.len = dentry->d_name.len;
INIT_LIST_HEAD(&node->fcd_dilist);
spin_lock(&sbi->s_fc_lock);
if (sbi->s_journal->j_flags & JBD2_FULL_COMMIT_ONGOING ||
sbi->s_journal->j_flags & JBD2_FAST_COMMIT_ONGOING)
list_add_tail(&node->fcd_list,
&sbi->s_fc_dentry_q[FC_Q_STAGING]);
else
list_add_tail(&node->fcd_list, &sbi->s_fc_dentry_q[FC_Q_MAIN]);
/*
* This helps us keep a track of all fc_dentry updates which is part of
* this ext4 inode. So in case the inode is getting unlinked, before
* even we get a chance to fsync, we could remove all fc_dentry
* references while evicting the inode in ext4_fc_del().
* Also with this, we don't need to loop over all the inodes in
* sbi->s_fc_q to get the corresponding inode in
* ext4_fc_commit_dentry_updates().
*/
if (dentry_update->op == EXT4_FC_TAG_CREAT) {
WARN_ON(!list_empty(&ei->i_fc_dilist));
list_add_tail(&node->fcd_dilist, &ei->i_fc_dilist);
}
spin_unlock(&sbi->s_fc_lock);
mutex_lock(&ei->i_fc_lock);
return 0;
}
void __ext4_fc_track_unlink(handle_t *handle,
struct inode *inode, struct dentry *dentry)
{
struct __track_dentry_update_args args;
int ret;
args.dentry = dentry;
args.op = EXT4_FC_TAG_UNLINK;
ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
(void *)&args, 0);
trace_ext4_fc_track_unlink(handle, inode, dentry, ret);
}
void ext4_fc_track_unlink(handle_t *handle, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
if (ext4_fc_disabled(inode->i_sb))
return;
if (ext4_test_mount_flag(inode->i_sb, EXT4_MF_FC_INELIGIBLE))
return;
__ext4_fc_track_unlink(handle, inode, dentry);
}
void __ext4_fc_track_link(handle_t *handle,
struct inode *inode, struct dentry *dentry)
{
struct __track_dentry_update_args args;
int ret;
args.dentry = dentry;
args.op = EXT4_FC_TAG_LINK;
ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
(void *)&args, 0);
trace_ext4_fc_track_link(handle, inode, dentry, ret);
}
void ext4_fc_track_link(handle_t *handle, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
if (ext4_fc_disabled(inode->i_sb))
return;
if (ext4_test_mount_flag(inode->i_sb, EXT4_MF_FC_INELIGIBLE))
return;
__ext4_fc_track_link(handle, inode, dentry);
}
void __ext4_fc_track_create(handle_t *handle, struct inode *inode,
struct dentry *dentry)
{
struct __track_dentry_update_args args;
int ret;
args.dentry = dentry;
args.op = EXT4_FC_TAG_CREAT;
ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
(void *)&args, 0);
trace_ext4_fc_track_create(handle, inode, dentry, ret);
}
void ext4_fc_track_create(handle_t *handle, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
if (ext4_fc_disabled(inode->i_sb))
return;
if (ext4_test_mount_flag(inode->i_sb, EXT4_MF_FC_INELIGIBLE))
return;
__ext4_fc_track_create(handle, inode, dentry);
}
/* __track_fn for inode tracking */
static int __track_inode(struct inode *inode, void *arg, bool update)
{
if (update)
return -EEXIST;
EXT4_I(inode)->i_fc_lblk_len = 0;
return 0;
}
void ext4_fc_track_inode(handle_t *handle, struct inode *inode)
{
int ret;
if (S_ISDIR(inode->i_mode))
return;
if (ext4_fc_disabled(inode->i_sb))
return;
if (ext4_should_journal_data(inode)) {
ext4_fc_mark_ineligible(inode->i_sb,
EXT4_FC_REASON_INODE_JOURNAL_DATA, handle);
return;
}
if (ext4_test_mount_flag(inode->i_sb, EXT4_MF_FC_INELIGIBLE))
return;
ret = ext4_fc_track_template(handle, inode, __track_inode, NULL, 1);
trace_ext4_fc_track_inode(handle, inode, ret);
}
struct __track_range_args {
ext4_lblk_t start, end;
};
/* __track_fn for tracking data updates */
static int __track_range(struct inode *inode, void *arg, bool update)
{
struct ext4_inode_info *ei = EXT4_I(inode);
ext4_lblk_t oldstart;
struct __track_range_args *__arg =
(struct __track_range_args *)arg;
if (inode->i_ino < EXT4_FIRST_INO(inode->i_sb)) {
ext4_debug("Special inode %ld being modified\n", inode->i_ino);
return -ECANCELED;
}
oldstart = ei->i_fc_lblk_start;
if (update && ei->i_fc_lblk_len > 0) {
ei->i_fc_lblk_start = min(ei->i_fc_lblk_start, __arg->start);
ei->i_fc_lblk_len =
max(oldstart + ei->i_fc_lblk_len - 1, __arg->end) -
ei->i_fc_lblk_start + 1;
} else {
ei->i_fc_lblk_start = __arg->start;
ei->i_fc_lblk_len = __arg->end - __arg->start + 1;
}
return 0;
}
void ext4_fc_track_range(handle_t *handle, struct inode *inode, ext4_lblk_t start,
ext4_lblk_t end)
{
struct __track_range_args args;
int ret;
if (S_ISDIR(inode->i_mode))
return;
if (ext4_fc_disabled(inode->i_sb))
return;
if (ext4_test_mount_flag(inode->i_sb, EXT4_MF_FC_INELIGIBLE))
return;
args.start = start;
args.end = end;
ret = ext4_fc_track_template(handle, inode, __track_range, &args, 1);
trace_ext4_fc_track_range(handle, inode, start, end, ret);
}
static void ext4_fc_submit_bh(struct super_block *sb, bool is_tail)
{
blk_opf_t write_flags = REQ_SYNC;
struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh;
/* Add REQ_FUA | REQ_PREFLUSH only its tail */
if (test_opt(sb, BARRIER) && is_tail)
write_flags |= REQ_FUA | REQ_PREFLUSH;
lock_buffer(bh);
set_buffer_dirty(bh);
set_buffer_uptodate(bh);
bh->b_end_io = ext4_end_buffer_io_sync;
submit_bh(REQ_OP_WRITE | write_flags, bh);
EXT4_SB(sb)->s_fc_bh = NULL;
}
/* Ext4 commit path routines */
/*
* Allocate len bytes on a fast commit buffer.
*
* During the commit time this function is used to manage fast commit
* block space. We don't split a fast commit log onto different
* blocks. So this function makes sure that if there's not enough space
* on the current block, the remaining space in the current block is
* marked as unused by adding EXT4_FC_TAG_PAD tag. In that case,
* new block is from jbd2 and CRC is updated to reflect the padding
* we added.
*/
static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc)
{
struct ext4_fc_tl tl;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct buffer_head *bh;
int bsize = sbi->s_journal->j_blocksize;
int ret, off = sbi->s_fc_bytes % bsize;
int remaining;
u8 *dst;
/*
* If 'len' is too long to fit in any block alongside a PAD tlv, then we
* cannot fulfill the request.
*/
if (len > bsize - EXT4_FC_TAG_BASE_LEN)
return NULL;
if (!sbi->s_fc_bh) {
ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh);
if (ret)
return NULL;
sbi->s_fc_bh = bh;
}
dst = sbi->s_fc_bh->b_data + off;
/*
* Allocate the bytes in the current block if we can do so while still
* leaving enough space for a PAD tlv.
*/
remaining = bsize - EXT4_FC_TAG_BASE_LEN - off;
if (len <= remaining) {
sbi->s_fc_bytes += len;
return dst;
}
/*
* Else, terminate the current block with a PAD tlv, then allocate a new
* block and allocate the bytes at the start of that new block.
*/
tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_PAD);
tl.fc_len = cpu_to_le16(remaining);
memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
memset(dst + EXT4_FC_TAG_BASE_LEN, 0, remaining);
*crc = ext4_chksum(sbi, *crc, sbi->s_fc_bh->b_data, bsize);
ext4_fc_submit_bh(sb, false);
ret = jbd2_fc_get_buf(EXT4_SB(sb)->s_journal, &bh);
if (ret)
return NULL;
sbi->s_fc_bh = bh;
sbi->s_fc_bytes += bsize - off + len;
return sbi->s_fc_bh->b_data;
}
/*
* Complete a fast commit by writing tail tag.
*
* Writing tail tag marks the end of a fast commit. In order to guarantee
* atomicity, after writing tail tag, even if there's space remaining
* in the block, next commit shouldn't use it. That's why tail tag
* has the length as that of the remaining space on the block.
*/
static int ext4_fc_write_tail(struct super_block *sb, u32 crc)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_fc_tl tl;
struct ext4_fc_tail tail;
int off, bsize = sbi->s_journal->j_blocksize;
u8 *dst;
/*
* ext4_fc_reserve_space takes care of allocating an extra block if
* there's no enough space on this block for accommodating this tail.
*/
dst = ext4_fc_reserve_space(sb, EXT4_FC_TAG_BASE_LEN + sizeof(tail), &crc);
if (!dst)
return -ENOSPC;
off = sbi->s_fc_bytes % bsize;
tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_TAIL);
tl.fc_len = cpu_to_le16(bsize - off + sizeof(struct ext4_fc_tail));
sbi->s_fc_bytes = round_up(sbi->s_fc_bytes, bsize);
memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
dst += EXT4_FC_TAG_BASE_LEN;
tail.fc_tid = cpu_to_le32(sbi->s_journal->j_running_transaction->t_tid);
memcpy(dst, &tail.fc_tid, sizeof(tail.fc_tid));
dst += sizeof(tail.fc_tid);
crc = ext4_chksum(sbi, crc, sbi->s_fc_bh->b_data,
dst - (u8 *)sbi->s_fc_bh->b_data);
tail.fc_crc = cpu_to_le32(crc);
memcpy(dst, &tail.fc_crc, sizeof(tail.fc_crc));
dst += sizeof(tail.fc_crc);
memset(dst, 0, bsize - off); /* Don't leak uninitialized memory. */
ext4_fc_submit_bh(sb, true);
return 0;
}
/*
* Adds tag, length, value and updates CRC. Returns true if tlv was added.
* Returns false if there's not enough space.
*/
static bool ext4_fc_add_tlv(struct super_block *sb, u16 tag, u16 len, u8 *val,
u32 *crc)
{
struct ext4_fc_tl tl;
u8 *dst;
dst = ext4_fc_reserve_space(sb, EXT4_FC_TAG_BASE_LEN + len, crc);
if (!dst)
return false;
tl.fc_tag = cpu_to_le16(tag);
tl.fc_len = cpu_to_le16(len);
memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
memcpy(dst + EXT4_FC_TAG_BASE_LEN, val, len);
return true;
}
/* Same as above, but adds dentry tlv. */
static bool ext4_fc_add_dentry_tlv(struct super_block *sb, u32 *crc,
struct ext4_fc_dentry_update *fc_dentry)
{
struct ext4_fc_dentry_info fcd;
struct ext4_fc_tl tl;
int dlen = fc_dentry->fcd_name.len;
u8 *dst = ext4_fc_reserve_space(sb,
EXT4_FC_TAG_BASE_LEN + sizeof(fcd) + dlen, crc);
if (!dst)
return false;
fcd.fc_parent_ino = cpu_to_le32(fc_dentry->fcd_parent);
fcd.fc_ino = cpu_to_le32(fc_dentry->fcd_ino);
tl.fc_tag = cpu_to_le16(fc_dentry->fcd_op);
tl.fc_len = cpu_to_le16(sizeof(fcd) + dlen);
memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
dst += EXT4_FC_TAG_BASE_LEN;
memcpy(dst, &fcd, sizeof(fcd));
dst += sizeof(fcd);
memcpy(dst, fc_dentry->fcd_name.name, dlen);
return true;
}
/*
* Writes inode in the fast commit space under TLV with tag @tag.
* Returns 0 on success, error on failure.
*/
static int ext4_fc_write_inode(struct inode *inode, u32 *crc)
{
struct ext4_inode_info *ei = EXT4_I(inode);
int inode_len = EXT4_GOOD_OLD_INODE_SIZE;
int ret;
struct ext4_iloc iloc;
struct ext4_fc_inode fc_inode;
struct ext4_fc_tl tl;
u8 *dst;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA))
inode_len = EXT4_INODE_SIZE(inode->i_sb);
else if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE)
inode_len += ei->i_extra_isize;
fc_inode.fc_ino = cpu_to_le32(inode->i_ino);
tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_INODE);
tl.fc_len = cpu_to_le16(inode_len + sizeof(fc_inode.fc_ino));
ret = -ECANCELED;
dst = ext4_fc_reserve_space(inode->i_sb,
EXT4_FC_TAG_BASE_LEN + inode_len + sizeof(fc_inode.fc_ino), crc);
if (!dst)
goto err;
memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
dst += EXT4_FC_TAG_BASE_LEN;
memcpy(dst, &fc_inode, sizeof(fc_inode));
dst += sizeof(fc_inode);
memcpy(dst, (u8 *)ext4_raw_inode(&iloc), inode_len);
ret = 0;
err:
brelse(iloc.bh);
return ret;
}
/*
* Writes updated data ranges for the inode in question. Updates CRC.
* Returns 0 on success, error otherwise.
*/
static int ext4_fc_write_inode_data(struct inode *inode, u32 *crc)
{
ext4_lblk_t old_blk_size, cur_lblk_off, new_blk_size;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_map_blocks map;
struct ext4_fc_add_range fc_ext;
struct ext4_fc_del_range lrange;
struct ext4_extent *ex;
int ret;
mutex_lock(&ei->i_fc_lock);
if (ei->i_fc_lblk_len == 0) {
mutex_unlock(&ei->i_fc_lock);
return 0;
}
old_blk_size = ei->i_fc_lblk_start;
new_blk_size = ei->i_fc_lblk_start + ei->i_fc_lblk_len - 1;
ei->i_fc_lblk_len = 0;
mutex_unlock(&ei->i_fc_lock);
cur_lblk_off = old_blk_size;
ext4_debug("will try writing %d to %d for inode %ld\n",
cur_lblk_off, new_blk_size, inode->i_ino);
while (cur_lblk_off <= new_blk_size) {
map.m_lblk = cur_lblk_off;
map.m_len = new_blk_size - cur_lblk_off + 1;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
return -ECANCELED;
if (map.m_len == 0) {
cur_lblk_off++;
continue;
}
if (ret == 0) {
lrange.fc_ino = cpu_to_le32(inode->i_ino);
lrange.fc_lblk = cpu_to_le32(map.m_lblk);
lrange.fc_len = cpu_to_le32(map.m_len);
if (!ext4_fc_add_tlv(inode->i_sb, EXT4_FC_TAG_DEL_RANGE,
sizeof(lrange), (u8 *)&lrange, crc))
return -ENOSPC;
} else {
unsigned int max = (map.m_flags & EXT4_MAP_UNWRITTEN) ?
EXT_UNWRITTEN_MAX_LEN : EXT_INIT_MAX_LEN;
/* Limit the number of blocks in one extent */
map.m_len = min(max, map.m_len);
fc_ext.fc_ino = cpu_to_le32(inode->i_ino);
ex = (struct ext4_extent *)&fc_ext.fc_ex;
ex->ee_block = cpu_to_le32(map.m_lblk);
ex->ee_len = cpu_to_le16(map.m_len);
ext4_ext_store_pblock(ex, map.m_pblk);
if (map.m_flags & EXT4_MAP_UNWRITTEN)
ext4_ext_mark_unwritten(ex);
else
ext4_ext_mark_initialized(ex);
if (!ext4_fc_add_tlv(inode->i_sb, EXT4_FC_TAG_ADD_RANGE,
sizeof(fc_ext), (u8 *)&fc_ext, crc))
return -ENOSPC;
}
cur_lblk_off += map.m_len;
}
return 0;
}
/* Submit data for all the fast commit inodes */
static int ext4_fc_submit_inode_data_all(journal_t *journal)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_inode_info *ei;
int ret = 0;
spin_lock(&sbi->s_fc_lock);
list_for_each_entry(ei, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
ext4_set_inode_state(&ei->vfs_inode, EXT4_STATE_FC_COMMITTING);
while (atomic_read(&ei->i_fc_updates)) {
DEFINE_WAIT(wait);
prepare_to_wait(&ei->i_fc_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (atomic_read(&ei->i_fc_updates)) {
spin_unlock(&sbi->s_fc_lock);
schedule();
spin_lock(&sbi->s_fc_lock);
}
finish_wait(&ei->i_fc_wait, &wait);
}
spin_unlock(&sbi->s_fc_lock);
ret = jbd2_submit_inode_data(journal, ei->jinode);
if (ret)
return ret;
spin_lock(&sbi->s_fc_lock);
}
spin_unlock(&sbi->s_fc_lock);
return ret;
}
/* Wait for completion of data for all the fast commit inodes */
static int ext4_fc_wait_inode_data_all(journal_t *journal)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_inode_info *pos, *n;
int ret = 0;
spin_lock(&sbi->s_fc_lock);
list_for_each_entry_safe(pos, n, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
if (!ext4_test_inode_state(&pos->vfs_inode,
EXT4_STATE_FC_COMMITTING))
continue;
spin_unlock(&sbi->s_fc_lock);
ret = jbd2_wait_inode_data(journal, pos->jinode);
if (ret)
return ret;
spin_lock(&sbi->s_fc_lock);
}
spin_unlock(&sbi->s_fc_lock);
return 0;
}
/* Commit all the directory entry updates */
static int ext4_fc_commit_dentry_updates(journal_t *journal, u32 *crc)
__acquires(&sbi->s_fc_lock)
__releases(&sbi->s_fc_lock)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_fc_dentry_update *fc_dentry, *fc_dentry_n;
struct inode *inode;
struct ext4_inode_info *ei;
int ret;
if (list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN]))
return 0;
list_for_each_entry_safe(fc_dentry, fc_dentry_n,
&sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) {
if (fc_dentry->fcd_op != EXT4_FC_TAG_CREAT) {
spin_unlock(&sbi->s_fc_lock);
if (!ext4_fc_add_dentry_tlv(sb, crc, fc_dentry)) {
ret = -ENOSPC;
goto lock_and_exit;
}
spin_lock(&sbi->s_fc_lock);
continue;
}
/*
* With fcd_dilist we need not loop in sbi->s_fc_q to get the
* corresponding inode pointer
*/
WARN_ON(list_empty(&fc_dentry->fcd_dilist));
ei = list_first_entry(&fc_dentry->fcd_dilist,
struct ext4_inode_info, i_fc_dilist);
inode = &ei->vfs_inode;
WARN_ON(inode->i_ino != fc_dentry->fcd_ino);
spin_unlock(&sbi->s_fc_lock);
/*
* We first write the inode and then the create dirent. This
* allows the recovery code to create an unnamed inode first
* and then link it to a directory entry. This allows us
* to use namei.c routines almost as is and simplifies
* the recovery code.
*/
ret = ext4_fc_write_inode(inode, crc);
if (ret)
goto lock_and_exit;
ret = ext4_fc_write_inode_data(inode, crc);
if (ret)
goto lock_and_exit;
if (!ext4_fc_add_dentry_tlv(sb, crc, fc_dentry)) {
ret = -ENOSPC;
goto lock_and_exit;
}
spin_lock(&sbi->s_fc_lock);
}
return 0;
lock_and_exit:
spin_lock(&sbi->s_fc_lock);
return ret;
}
static int ext4_fc_perform_commit(journal_t *journal)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_inode_info *iter;
struct ext4_fc_head head;
struct inode *inode;
struct blk_plug plug;
int ret = 0;
u32 crc = 0;
ret = ext4_fc_submit_inode_data_all(journal);
if (ret)
return ret;
ret = ext4_fc_wait_inode_data_all(journal);
if (ret)
return ret;
/*
* If file system device is different from journal device, issue a cache
* flush before we start writing fast commit blocks.
*/
if (journal->j_fs_dev != journal->j_dev)
blkdev_issue_flush(journal->j_fs_dev);
blk_start_plug(&plug);
if (sbi->s_fc_bytes == 0) {
/*
* Add a head tag only if this is the first fast commit
* in this TID.
*/
head.fc_features = cpu_to_le32(EXT4_FC_SUPPORTED_FEATURES);
head.fc_tid = cpu_to_le32(
sbi->s_journal->j_running_transaction->t_tid);
if (!ext4_fc_add_tlv(sb, EXT4_FC_TAG_HEAD, sizeof(head),
(u8 *)&head, &crc)) {
ret = -ENOSPC;
goto out;
}
}
spin_lock(&sbi->s_fc_lock);
ret = ext4_fc_commit_dentry_updates(journal, &crc);
if (ret) {
spin_unlock(&sbi->s_fc_lock);
goto out;
}
list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
inode = &iter->vfs_inode;
if (!ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING))
continue;
spin_unlock(&sbi->s_fc_lock);
ret = ext4_fc_write_inode_data(inode, &crc);
if (ret)
goto out;
ret = ext4_fc_write_inode(inode, &crc);
if (ret)
goto out;
spin_lock(&sbi->s_fc_lock);
}
spin_unlock(&sbi->s_fc_lock);
ret = ext4_fc_write_tail(sb, crc);
out:
blk_finish_plug(&plug);
return ret;
}
static void ext4_fc_update_stats(struct super_block *sb, int status,
u64 commit_time, int nblks, tid_t commit_tid)
{
struct ext4_fc_stats *stats = &EXT4_SB(sb)->s_fc_stats;
ext4_debug("Fast commit ended with status = %d for tid %u",
status, commit_tid);
if (status == EXT4_FC_STATUS_OK) {
stats->fc_num_commits++;
stats->fc_numblks += nblks;
if (likely(stats->s_fc_avg_commit_time))
stats->s_fc_avg_commit_time =
(commit_time +
stats->s_fc_avg_commit_time * 3) / 4;
else
stats->s_fc_avg_commit_time = commit_time;
} else if (status == EXT4_FC_STATUS_FAILED ||
status == EXT4_FC_STATUS_INELIGIBLE) {
if (status == EXT4_FC_STATUS_FAILED)
stats->fc_failed_commits++;
stats->fc_ineligible_commits++;
} else {
stats->fc_skipped_commits++;
}
trace_ext4_fc_commit_stop(sb, nblks, status, commit_tid);
}
/*
* The main commit entry point. Performs a fast commit for transaction
* commit_tid if needed. If it's not possible to perform a fast commit
* due to various reasons, we fall back to full commit. Returns 0
* on success, error otherwise.
*/
int ext4_fc_commit(journal_t *journal, tid_t commit_tid)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int nblks = 0, ret, bsize = journal->j_blocksize;
int subtid = atomic_read(&sbi->s_fc_subtid);
int status = EXT4_FC_STATUS_OK, fc_bufs_before = 0;
ktime_t start_time, commit_time;
if (!test_opt2(sb, JOURNAL_FAST_COMMIT))
return jbd2_complete_transaction(journal, commit_tid);
trace_ext4_fc_commit_start(sb, commit_tid);
start_time = ktime_get();
restart_fc:
ret = jbd2_fc_begin_commit(journal, commit_tid);
if (ret == -EALREADY) {
/* There was an ongoing commit, check if we need to restart */
if (atomic_read(&sbi->s_fc_subtid) <= subtid &&
commit_tid > journal->j_commit_sequence)
goto restart_fc;
ext4_fc_update_stats(sb, EXT4_FC_STATUS_SKIPPED, 0, 0,
commit_tid);
return 0;
} else if (ret) {
/*
* Commit couldn't start. Just update stats and perform a
* full commit.
*/
ext4_fc_update_stats(sb, EXT4_FC_STATUS_FAILED, 0, 0,
commit_tid);
return jbd2_complete_transaction(journal, commit_tid);
}
/*
* After establishing journal barrier via jbd2_fc_begin_commit(), check
* if we are fast commit ineligible.
*/
if (ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)) {
status = EXT4_FC_STATUS_INELIGIBLE;
goto fallback;
}
fc_bufs_before = (sbi->s_fc_bytes + bsize - 1) / bsize;
ret = ext4_fc_perform_commit(journal);
if (ret < 0) {
status = EXT4_FC_STATUS_FAILED;
goto fallback;
}
nblks = (sbi->s_fc_bytes + bsize - 1) / bsize - fc_bufs_before;
ret = jbd2_fc_wait_bufs(journal, nblks);
if (ret < 0) {
status = EXT4_FC_STATUS_FAILED;
goto fallback;
}
atomic_inc(&sbi->s_fc_subtid);
ret = jbd2_fc_end_commit(journal);
/*
* weight the commit time higher than the average time so we
* don't react too strongly to vast changes in the commit time
*/
commit_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
ext4_fc_update_stats(sb, status, commit_time, nblks, commit_tid);
return ret;
fallback:
ret = jbd2_fc_end_commit_fallback(journal);
ext4_fc_update_stats(sb, status, 0, 0, commit_tid);
return ret;
}
/*
* Fast commit cleanup routine. This is called after every fast commit and
* full commit. full is true if we are called after a full commit.
*/
static void ext4_fc_cleanup(journal_t *journal, int full, tid_t tid)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_inode_info *iter, *iter_n;
struct ext4_fc_dentry_update *fc_dentry;
if (full && sbi->s_fc_bh)
sbi->s_fc_bh = NULL;
trace_ext4_fc_cleanup(journal, full, tid);
jbd2_fc_release_bufs(journal);
spin_lock(&sbi->s_fc_lock);
list_for_each_entry_safe(iter, iter_n, &sbi->s_fc_q[FC_Q_MAIN],
i_fc_list) {
list_del_init(&iter->i_fc_list);
ext4_clear_inode_state(&iter->vfs_inode,
EXT4_STATE_FC_COMMITTING);
if (iter->i_sync_tid <= tid)
ext4_fc_reset_inode(&iter->vfs_inode);
/* Make sure EXT4_STATE_FC_COMMITTING bit is clear */
smp_mb();
#if (BITS_PER_LONG < 64)
wake_up_bit(&iter->i_state_flags, EXT4_STATE_FC_COMMITTING);
#else
wake_up_bit(&iter->i_flags, EXT4_STATE_FC_COMMITTING);
#endif
}
while (!list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])) {
fc_dentry = list_first_entry(&sbi->s_fc_dentry_q[FC_Q_MAIN],
struct ext4_fc_dentry_update,
fcd_list);
list_del_init(&fc_dentry->fcd_list);
list_del_init(&fc_dentry->fcd_dilist);
spin_unlock(&sbi->s_fc_lock);
if (fc_dentry->fcd_name.name &&
fc_dentry->fcd_name.len > DNAME_INLINE_LEN)
kfree(fc_dentry->fcd_name.name);
kmem_cache_free(ext4_fc_dentry_cachep, fc_dentry);
spin_lock(&sbi->s_fc_lock);
}
list_splice_init(&sbi->s_fc_dentry_q[FC_Q_STAGING],
&sbi->s_fc_dentry_q[FC_Q_MAIN]);
list_splice_init(&sbi->s_fc_q[FC_Q_STAGING],
&sbi->s_fc_q[FC_Q_MAIN]);
if (tid >= sbi->s_fc_ineligible_tid) {
sbi->s_fc_ineligible_tid = 0;
ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
}
if (full)
sbi->s_fc_bytes = 0;
spin_unlock(&sbi->s_fc_lock);
trace_ext4_fc_stats(sb);
}
/* Ext4 Replay Path Routines */
/* Helper struct for dentry replay routines */
struct dentry_info_args {
int parent_ino, dname_len, ino, inode_len;
char *dname;
};
/* Same as struct ext4_fc_tl, but uses native endianness fields */
struct ext4_fc_tl_mem {
u16 fc_tag;
u16 fc_len;
};
static inline void tl_to_darg(struct dentry_info_args *darg,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct ext4_fc_dentry_info fcd;
memcpy(&fcd, val, sizeof(fcd));
darg->parent_ino = le32_to_cpu(fcd.fc_parent_ino);
darg->ino = le32_to_cpu(fcd.fc_ino);
darg->dname = val + offsetof(struct ext4_fc_dentry_info, fc_dname);
darg->dname_len = tl->fc_len - sizeof(struct ext4_fc_dentry_info);
}
static inline void ext4_fc_get_tl(struct ext4_fc_tl_mem *tl, u8 *val)
{
struct ext4_fc_tl tl_disk;
memcpy(&tl_disk, val, EXT4_FC_TAG_BASE_LEN);
tl->fc_len = le16_to_cpu(tl_disk.fc_len);
tl->fc_tag = le16_to_cpu(tl_disk.fc_tag);
}
/* Unlink replay function */
static int ext4_fc_replay_unlink(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct inode *inode, *old_parent;
struct qstr entry;
struct dentry_info_args darg;
int ret = 0;
tl_to_darg(&darg, tl, val);
trace_ext4_fc_replay(sb, EXT4_FC_TAG_UNLINK, darg.ino,
darg.parent_ino, darg.dname_len);
entry.name = darg.dname;
entry.len = darg.dname_len;
inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode %d not found", darg.ino);
return 0;
}
old_parent = ext4_iget(sb, darg.parent_ino,
EXT4_IGET_NORMAL);
if (IS_ERR(old_parent)) {
ext4_debug("Dir with inode %d not found", darg.parent_ino);
iput(inode);
return 0;
}
ret = __ext4_unlink(old_parent, &entry, inode, NULL);
/* -ENOENT ok coz it might not exist anymore. */
if (ret == -ENOENT)
ret = 0;
iput(old_parent);
iput(inode);
return ret;
}
static int ext4_fc_replay_link_internal(struct super_block *sb,
struct dentry_info_args *darg,
struct inode *inode)
{
struct inode *dir = NULL;
struct dentry *dentry_dir = NULL, *dentry_inode = NULL;
struct qstr qstr_dname = QSTR_INIT(darg->dname, darg->dname_len);
int ret = 0;
dir = ext4_iget(sb, darg->parent_ino, EXT4_IGET_NORMAL);
if (IS_ERR(dir)) {
ext4_debug("Dir with inode %d not found.", darg->parent_ino);
dir = NULL;
goto out;
}
dentry_dir = d_obtain_alias(dir);
if (IS_ERR(dentry_dir)) {
ext4_debug("Failed to obtain dentry");
dentry_dir = NULL;
goto out;
}
dentry_inode = d_alloc(dentry_dir, &qstr_dname);
if (!dentry_inode) {
ext4_debug("Inode dentry not created.");
ret = -ENOMEM;
goto out;
}
ret = __ext4_link(dir, inode, dentry_inode);
/*
* It's possible that link already existed since data blocks
* for the dir in question got persisted before we crashed OR
* we replayed this tag and crashed before the entire replay
* could complete.
*/
if (ret && ret != -EEXIST) {
ext4_debug("Failed to link\n");
goto out;
}
ret = 0;
out:
if (dentry_dir) {
d_drop(dentry_dir);
dput(dentry_dir);
} else if (dir) {
iput(dir);
}
if (dentry_inode) {
d_drop(dentry_inode);
dput(dentry_inode);
}
return ret;
}
/* Link replay function */
static int ext4_fc_replay_link(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct inode *inode;
struct dentry_info_args darg;
int ret = 0;
tl_to_darg(&darg, tl, val);
trace_ext4_fc_replay(sb, EXT4_FC_TAG_LINK, darg.ino,
darg.parent_ino, darg.dname_len);
inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode not found.");
return 0;
}
ret = ext4_fc_replay_link_internal(sb, &darg, inode);
iput(inode);
return ret;
}
/*
* Record all the modified inodes during replay. We use this later to setup
* block bitmaps correctly.
*/
static int ext4_fc_record_modified_inode(struct super_block *sb, int ino)
{
struct ext4_fc_replay_state *state;
int i;
state = &EXT4_SB(sb)->s_fc_replay_state;
for (i = 0; i < state->fc_modified_inodes_used; i++)
if (state->fc_modified_inodes[i] == ino)
return 0;
if (state->fc_modified_inodes_used == state->fc_modified_inodes_size) {
int *fc_modified_inodes;
fc_modified_inodes = krealloc(state->fc_modified_inodes,
sizeof(int) * (state->fc_modified_inodes_size +
EXT4_FC_REPLAY_REALLOC_INCREMENT),
GFP_KERNEL);
if (!fc_modified_inodes)
return -ENOMEM;
state->fc_modified_inodes = fc_modified_inodes;
state->fc_modified_inodes_size +=
EXT4_FC_REPLAY_REALLOC_INCREMENT;
}
state->fc_modified_inodes[state->fc_modified_inodes_used++] = ino;
return 0;
}
/*
* Inode replay function
*/
static int ext4_fc_replay_inode(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct ext4_fc_inode fc_inode;
struct ext4_inode *raw_inode;
struct ext4_inode *raw_fc_inode;
struct inode *inode = NULL;
struct ext4_iloc iloc;
int inode_len, ino, ret, tag = tl->fc_tag;
struct ext4_extent_header *eh;
size_t off_gen = offsetof(struct ext4_inode, i_generation);
memcpy(&fc_inode, val, sizeof(fc_inode));
ino = le32_to_cpu(fc_inode.fc_ino);
trace_ext4_fc_replay(sb, tag, ino, 0, 0);
inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
if (!IS_ERR(inode)) {
ext4_ext_clear_bb(inode);
iput(inode);
}
inode = NULL;
ret = ext4_fc_record_modified_inode(sb, ino);
if (ret)
goto out;
raw_fc_inode = (struct ext4_inode *)
(val + offsetof(struct ext4_fc_inode, fc_raw_inode));
ret = ext4_get_fc_inode_loc(sb, ino, &iloc);
if (ret)
goto out;
inode_len = tl->fc_len - sizeof(struct ext4_fc_inode);
raw_inode = ext4_raw_inode(&iloc);
memcpy(raw_inode, raw_fc_inode, offsetof(struct ext4_inode, i_block));
memcpy((u8 *)raw_inode + off_gen, (u8 *)raw_fc_inode + off_gen,
inode_len - off_gen);
if (le32_to_cpu(raw_inode->i_flags) & EXT4_EXTENTS_FL) {
eh = (struct ext4_extent_header *)(&raw_inode->i_block[0]);
if (eh->eh_magic != EXT4_EXT_MAGIC) {
memset(eh, 0, sizeof(*eh));
eh->eh_magic = EXT4_EXT_MAGIC;
eh->eh_max = cpu_to_le16(
(sizeof(raw_inode->i_block) -
sizeof(struct ext4_extent_header))
/ sizeof(struct ext4_extent));
}
} else if (le32_to_cpu(raw_inode->i_flags) & EXT4_INLINE_DATA_FL) {
memcpy(raw_inode->i_block, raw_fc_inode->i_block,
sizeof(raw_inode->i_block));
}
/* Immediately update the inode on disk. */
ret = ext4_handle_dirty_metadata(NULL, NULL, iloc.bh);
if (ret)
goto out;
ret = sync_dirty_buffer(iloc.bh);
if (ret)
goto out;
ret = ext4_mark_inode_used(sb, ino);
if (ret)
goto out;
/* Given that we just wrote the inode on disk, this SHOULD succeed. */
inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode not found.");
return -EFSCORRUPTED;
}
/*
* Our allocator could have made different decisions than before
* crashing. This should be fixed but until then, we calculate
* the number of blocks the inode.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA))
ext4_ext_replay_set_iblocks(inode);
inode->i_generation = le32_to_cpu(ext4_raw_inode(&iloc)->i_generation);
ext4_reset_inode_seed(inode);
ext4_inode_csum_set(inode, ext4_raw_inode(&iloc), EXT4_I(inode));
ret = ext4_handle_dirty_metadata(NULL, NULL, iloc.bh);
sync_dirty_buffer(iloc.bh);
brelse(iloc.bh);
out:
iput(inode);
if (!ret)
blkdev_issue_flush(sb->s_bdev);
return 0;
}
/*
* Dentry create replay function.
*
* EXT4_FC_TAG_CREAT is preceded by EXT4_FC_TAG_INODE_FULL. Which means, the
* inode for which we are trying to create a dentry here, should already have
* been replayed before we start here.
*/
static int ext4_fc_replay_create(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
int ret = 0;
struct inode *inode = NULL;
struct inode *dir = NULL;
struct dentry_info_args darg;
tl_to_darg(&darg, tl, val);
trace_ext4_fc_replay(sb, EXT4_FC_TAG_CREAT, darg.ino,
darg.parent_ino, darg.dname_len);
/* This takes care of update group descriptor and other metadata */
ret = ext4_mark_inode_used(sb, darg.ino);
if (ret)
goto out;
inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("inode %d not found.", darg.ino);
inode = NULL;
ret = -EINVAL;
goto out;
}
if (S_ISDIR(inode->i_mode)) {
/*
* If we are creating a directory, we need to make sure that the
* dot and dot dot dirents are setup properly.
*/
dir = ext4_iget(sb, darg.parent_ino, EXT4_IGET_NORMAL);
if (IS_ERR(dir)) {
ext4_debug("Dir %d not found.", darg.ino);
goto out;
}
ret = ext4_init_new_dir(NULL, dir, inode);
iput(dir);
if (ret) {
ret = 0;
goto out;
}
}
ret = ext4_fc_replay_link_internal(sb, &darg, inode);
if (ret)
goto out;
set_nlink(inode, 1);
ext4_mark_inode_dirty(NULL, inode);
out:
iput(inode);
return ret;
}
/*
* Record physical disk regions which are in use as per fast commit area,
* and used by inodes during replay phase. Our simple replay phase
* allocator excludes these regions from allocation.
*/
int ext4_fc_record_regions(struct super_block *sb, int ino,
ext4_lblk_t lblk, ext4_fsblk_t pblk, int len, int replay)
{
struct ext4_fc_replay_state *state;
struct ext4_fc_alloc_region *region;
state = &EXT4_SB(sb)->s_fc_replay_state;
/*
* during replay phase, the fc_regions_valid may not same as
* fc_regions_used, update it when do new additions.
*/
if (replay && state->fc_regions_used != state->fc_regions_valid)
state->fc_regions_used = state->fc_regions_valid;
if (state->fc_regions_used == state->fc_regions_size) {
struct ext4_fc_alloc_region *fc_regions;
fc_regions = krealloc(state->fc_regions,
sizeof(struct ext4_fc_alloc_region) *
(state->fc_regions_size +
EXT4_FC_REPLAY_REALLOC_INCREMENT),
GFP_KERNEL);
if (!fc_regions)
return -ENOMEM;
state->fc_regions_size +=
EXT4_FC_REPLAY_REALLOC_INCREMENT;
state->fc_regions = fc_regions;
}
region = &state->fc_regions[state->fc_regions_used++];
region->ino = ino;
region->lblk = lblk;
region->pblk = pblk;
region->len = len;
if (replay)
state->fc_regions_valid++;
return 0;
}
/* Replay add range tag */
static int ext4_fc_replay_add_range(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct ext4_fc_add_range fc_add_ex;
struct ext4_extent newex, *ex;
struct inode *inode;
ext4_lblk_t start, cur;
int remaining, len;
ext4_fsblk_t start_pblk;
struct ext4_map_blocks map;
struct ext4_ext_path *path = NULL;
int ret;
memcpy(&fc_add_ex, val, sizeof(fc_add_ex));
ex = (struct ext4_extent *)&fc_add_ex.fc_ex;
trace_ext4_fc_replay(sb, EXT4_FC_TAG_ADD_RANGE,
le32_to_cpu(fc_add_ex.fc_ino), le32_to_cpu(ex->ee_block),
ext4_ext_get_actual_len(ex));
inode = ext4_iget(sb, le32_to_cpu(fc_add_ex.fc_ino), EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode not found.");
return 0;
}
ret = ext4_fc_record_modified_inode(sb, inode->i_ino);
if (ret)
goto out;
start = le32_to_cpu(ex->ee_block);
start_pblk = ext4_ext_pblock(ex);
len = ext4_ext_get_actual_len(ex);
cur = start;
remaining = len;
ext4_debug("ADD_RANGE, lblk %d, pblk %lld, len %d, unwritten %d, inode %ld\n",
start, start_pblk, len, ext4_ext_is_unwritten(ex),
inode->i_ino);
while (remaining > 0) {
map.m_lblk = cur;
map.m_len = remaining;
map.m_pblk = 0;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
goto out;
if (ret == 0) {
/* Range is not mapped */
path = ext4_find_extent(inode, cur, NULL, 0);
if (IS_ERR(path))
goto out;
memset(&newex, 0, sizeof(newex));
newex.ee_block = cpu_to_le32(cur);
ext4_ext_store_pblock(
&newex, start_pblk + cur - start);
newex.ee_len = cpu_to_le16(map.m_len);
if (ext4_ext_is_unwritten(ex))
ext4_ext_mark_unwritten(&newex);
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_ext_insert_extent(
NULL, inode, &path, &newex, 0);
up_write((&EXT4_I(inode)->i_data_sem));
ext4_free_ext_path(path);
if (ret)
goto out;
goto next;
}
if (start_pblk + cur - start != map.m_pblk) {
/*
* Logical to physical mapping changed. This can happen
* if this range was removed and then reallocated to
* map to new physical blocks during a fast commit.
*/
ret = ext4_ext_replay_update_ex(inode, cur, map.m_len,
ext4_ext_is_unwritten(ex),
start_pblk + cur - start);
if (ret)
goto out;
/*
* Mark the old blocks as free since they aren't used
* anymore. We maintain an array of all the modified
* inodes. In case these blocks are still used at either
* a different logical range in the same inode or in
* some different inode, we will mark them as allocated
* at the end of the FC replay using our array of
* modified inodes.
*/
ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
goto next;
}
/* Range is mapped and needs a state change */
ext4_debug("Converting from %ld to %d %lld",
map.m_flags & EXT4_MAP_UNWRITTEN,
ext4_ext_is_unwritten(ex), map.m_pblk);
ret = ext4_ext_replay_update_ex(inode, cur, map.m_len,
ext4_ext_is_unwritten(ex), map.m_pblk);
if (ret)
goto out;
/*
* We may have split the extent tree while toggling the state.
* Try to shrink the extent tree now.
*/
ext4_ext_replay_shrink_inode(inode, start + len);
next:
cur += map.m_len;
remaining -= map.m_len;
}
ext4_ext_replay_shrink_inode(inode, i_size_read(inode) >>
sb->s_blocksize_bits);
out:
iput(inode);
return 0;
}
/* Replay DEL_RANGE tag */
static int
ext4_fc_replay_del_range(struct super_block *sb,
struct ext4_fc_tl_mem *tl, u8 *val)
{
struct inode *inode;
struct ext4_fc_del_range lrange;
struct ext4_map_blocks map;
ext4_lblk_t cur, remaining;
int ret;
memcpy(&lrange, val, sizeof(lrange));
cur = le32_to_cpu(lrange.fc_lblk);
remaining = le32_to_cpu(lrange.fc_len);
trace_ext4_fc_replay(sb, EXT4_FC_TAG_DEL_RANGE,
le32_to_cpu(lrange.fc_ino), cur, remaining);
inode = ext4_iget(sb, le32_to_cpu(lrange.fc_ino), EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode %d not found", le32_to_cpu(lrange.fc_ino));
return 0;
}
ret = ext4_fc_record_modified_inode(sb, inode->i_ino);
if (ret)
goto out;
ext4_debug("DEL_RANGE, inode %ld, lblk %d, len %d\n",
inode->i_ino, le32_to_cpu(lrange.fc_lblk),
le32_to_cpu(lrange.fc_len));
while (remaining > 0) {
map.m_lblk = cur;
map.m_len = remaining;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
goto out;
if (ret > 0) {
remaining -= ret;
cur += ret;
ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
} else {
remaining -= map.m_len;
cur += map.m_len;
}
}
down_write(&EXT4_I(inode)->i_data_sem);
ret = ext4_ext_remove_space(inode, le32_to_cpu(lrange.fc_lblk),
le32_to_cpu(lrange.fc_lblk) +
le32_to_cpu(lrange.fc_len) - 1);
up_write(&EXT4_I(inode)->i_data_sem);
if (ret)
goto out;
ext4_ext_replay_shrink_inode(inode,
i_size_read(inode) >> sb->s_blocksize_bits);
ext4_mark_inode_dirty(NULL, inode);
out:
iput(inode);
return 0;
}
static void ext4_fc_set_bitmaps_and_counters(struct super_block *sb)
{
struct ext4_fc_replay_state *state;
struct inode *inode;
struct ext4_ext_path *path = NULL;
struct ext4_map_blocks map;
int i, ret, j;
ext4_lblk_t cur, end;
state = &EXT4_SB(sb)->s_fc_replay_state;
for (i = 0; i < state->fc_modified_inodes_used; i++) {
inode = ext4_iget(sb, state->fc_modified_inodes[i],
EXT4_IGET_NORMAL);
if (IS_ERR(inode)) {
ext4_debug("Inode %d not found.",
state->fc_modified_inodes[i]);
continue;
}
cur = 0;
end = EXT_MAX_BLOCKS;
if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) {
iput(inode);
continue;
}
while (cur < end) {
map.m_lblk = cur;
map.m_len = end - cur;
ret = ext4_map_blocks(NULL, inode, &map, 0);
if (ret < 0)
break;
if (ret > 0) {
path = ext4_find_extent(inode, map.m_lblk, NULL, 0);
if (!IS_ERR(path)) {
for (j = 0; j < path->p_depth; j++)
ext4_mb_mark_bb(inode->i_sb,
path[j].p_block, 1, 1);
ext4_free_ext_path(path);
}
cur += ret;
ext4_mb_mark_bb(inode->i_sb, map.m_pblk,
map.m_len, 1);
} else {
cur = cur + (map.m_len ? map.m_len : 1);
}
}
iput(inode);
}
}
/*
* Check if block is in excluded regions for block allocation. The simple
* allocator that runs during replay phase is calls this function to see
* if it is okay to use a block.
*/
bool ext4_fc_replay_check_excluded(struct super_block *sb, ext4_fsblk_t blk)
{
int i;
struct ext4_fc_replay_state *state;
state = &EXT4_SB(sb)->s_fc_replay_state;
for (i = 0; i < state->fc_regions_valid; i++) {
if (state->fc_regions[i].ino == 0 ||
state->fc_regions[i].len == 0)
continue;
if (in_range(blk, state->fc_regions[i].pblk,
state->fc_regions[i].len))
return true;
}
return false;
}
/* Cleanup function called after replay */
void ext4_fc_replay_cleanup(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
sbi->s_mount_state &= ~EXT4_FC_REPLAY;
kfree(sbi->s_fc_replay_state.fc_regions);
kfree(sbi->s_fc_replay_state.fc_modified_inodes);
}
static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi,
int tag, int len)
{
switch (tag) {
case EXT4_FC_TAG_ADD_RANGE:
return len == sizeof(struct ext4_fc_add_range);
case EXT4_FC_TAG_DEL_RANGE:
return len == sizeof(struct ext4_fc_del_range);
case EXT4_FC_TAG_CREAT:
case EXT4_FC_TAG_LINK:
case EXT4_FC_TAG_UNLINK:
len -= sizeof(struct ext4_fc_dentry_info);
return len >= 1 && len <= EXT4_NAME_LEN;
case EXT4_FC_TAG_INODE:
len -= sizeof(struct ext4_fc_inode);
return len >= EXT4_GOOD_OLD_INODE_SIZE &&
len <= sbi->s_inode_size;
case EXT4_FC_TAG_PAD:
return true; /* padding can have any length */
case EXT4_FC_TAG_TAIL:
return len >= sizeof(struct ext4_fc_tail);
case EXT4_FC_TAG_HEAD:
return len == sizeof(struct ext4_fc_head);
}
return false;
}
/*
* Recovery Scan phase handler
*
* This function is called during the scan phase and is responsible
* for doing following things:
* - Make sure the fast commit area has valid tags for replay
* - Count number of tags that need to be replayed by the replay handler
* - Verify CRC
* - Create a list of excluded blocks for allocation during replay phase
*
* This function returns JBD2_FC_REPLAY_CONTINUE to indicate that SCAN is
* incomplete and JBD2 should send more blocks. It returns JBD2_FC_REPLAY_STOP
* to indicate that scan has finished and JBD2 can now start replay phase.
* It returns a negative error to indicate that there was an error. At the end
* of a successful scan phase, sbi->s_fc_replay_state.fc_replay_num_tags is set
* to indicate the number of tags that need to replayed during the replay phase.
*/
static int ext4_fc_replay_scan(journal_t *journal,
struct buffer_head *bh, int off,
tid_t expected_tid)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_fc_replay_state *state;
int ret = JBD2_FC_REPLAY_CONTINUE;
struct ext4_fc_add_range ext;
struct ext4_fc_tl_mem tl;
struct ext4_fc_tail tail;
__u8 *start, *end, *cur, *val;
struct ext4_fc_head head;
struct ext4_extent *ex;
state = &sbi->s_fc_replay_state;
start = (u8 *)bh->b_data;
end = start + journal->j_blocksize;
if (state->fc_replay_expected_off == 0) {
state->fc_cur_tag = 0;
state->fc_replay_num_tags = 0;
state->fc_crc = 0;
state->fc_regions = NULL;
state->fc_regions_valid = state->fc_regions_used =
state->fc_regions_size = 0;
/* Check if we can stop early */
if (le16_to_cpu(((struct ext4_fc_tl *)start)->fc_tag)
!= EXT4_FC_TAG_HEAD)
return 0;
}
if (off != state->fc_replay_expected_off) {
ret = -EFSCORRUPTED;
goto out_err;
}
state->fc_replay_expected_off++;
for (cur = start; cur <= end - EXT4_FC_TAG_BASE_LEN;
cur = cur + EXT4_FC_TAG_BASE_LEN + tl.fc_len) {
ext4_fc_get_tl(&tl, cur);
val = cur + EXT4_FC_TAG_BASE_LEN;
if (tl.fc_len > end - val ||
!ext4_fc_value_len_isvalid(sbi, tl.fc_tag, tl.fc_len)) {
ret = state->fc_replay_num_tags ?
JBD2_FC_REPLAY_STOP : -ECANCELED;
goto out_err;
}
ext4_debug("Scan phase, tag:%s, blk %lld\n",
tag2str(tl.fc_tag), bh->b_blocknr);
switch (tl.fc_tag) {
case EXT4_FC_TAG_ADD_RANGE:
memcpy(&ext, val, sizeof(ext));
ex = (struct ext4_extent *)&ext.fc_ex;
ret = ext4_fc_record_regions(sb,
le32_to_cpu(ext.fc_ino),
le32_to_cpu(ex->ee_block), ext4_ext_pblock(ex),
ext4_ext_get_actual_len(ex), 0);
if (ret < 0)
break;
ret = JBD2_FC_REPLAY_CONTINUE;
fallthrough;
case EXT4_FC_TAG_DEL_RANGE:
case EXT4_FC_TAG_LINK:
case EXT4_FC_TAG_UNLINK:
case EXT4_FC_TAG_CREAT:
case EXT4_FC_TAG_INODE:
case EXT4_FC_TAG_PAD:
state->fc_cur_tag++;
state->fc_crc = ext4_chksum(sbi, state->fc_crc, cur,
EXT4_FC_TAG_BASE_LEN + tl.fc_len);
break;
case EXT4_FC_TAG_TAIL:
state->fc_cur_tag++;
memcpy(&tail, val, sizeof(tail));
state->fc_crc = ext4_chksum(sbi, state->fc_crc, cur,
EXT4_FC_TAG_BASE_LEN +
offsetof(struct ext4_fc_tail,
fc_crc));
if (le32_to_cpu(tail.fc_tid) == expected_tid &&
le32_to_cpu(tail.fc_crc) == state->fc_crc) {
state->fc_replay_num_tags = state->fc_cur_tag;
state->fc_regions_valid =
state->fc_regions_used;
} else {
ret = state->fc_replay_num_tags ?
JBD2_FC_REPLAY_STOP : -EFSBADCRC;
}
state->fc_crc = 0;
break;
case EXT4_FC_TAG_HEAD:
memcpy(&head, val, sizeof(head));
if (le32_to_cpu(head.fc_features) &
~EXT4_FC_SUPPORTED_FEATURES) {
ret = -EOPNOTSUPP;
break;
}
if (le32_to_cpu(head.fc_tid) != expected_tid) {
ret = JBD2_FC_REPLAY_STOP;
break;
}
state->fc_cur_tag++;
state->fc_crc = ext4_chksum(sbi, state->fc_crc, cur,
EXT4_FC_TAG_BASE_LEN + tl.fc_len);
break;
default:
ret = state->fc_replay_num_tags ?
JBD2_FC_REPLAY_STOP : -ECANCELED;
}
if (ret < 0 || ret == JBD2_FC_REPLAY_STOP)
break;
}
out_err:
trace_ext4_fc_replay_scan(sb, ret, off);
return ret;
}
/*
* Main recovery path entry point.
* The meaning of return codes is similar as above.
*/
static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh,
enum passtype pass, int off, tid_t expected_tid)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_fc_tl_mem tl;
__u8 *start, *end, *cur, *val;
int ret = JBD2_FC_REPLAY_CONTINUE;
struct ext4_fc_replay_state *state = &sbi->s_fc_replay_state;
struct ext4_fc_tail tail;
if (pass == PASS_SCAN) {
state->fc_current_pass = PASS_SCAN;
return ext4_fc_replay_scan(journal, bh, off, expected_tid);
}
if (state->fc_current_pass != pass) {
state->fc_current_pass = pass;
sbi->s_mount_state |= EXT4_FC_REPLAY;
}
if (!sbi->s_fc_replay_state.fc_replay_num_tags) {
ext4_debug("Replay stops\n");
ext4_fc_set_bitmaps_and_counters(sb);
return 0;
}
#ifdef CONFIG_EXT4_DEBUG
if (sbi->s_fc_debug_max_replay && off >= sbi->s_fc_debug_max_replay) {
pr_warn("Dropping fc block %d because max_replay set\n", off);
return JBD2_FC_REPLAY_STOP;
}
#endif
start = (u8 *)bh->b_data;
end = start + journal->j_blocksize;
for (cur = start; cur <= end - EXT4_FC_TAG_BASE_LEN;
cur = cur + EXT4_FC_TAG_BASE_LEN + tl.fc_len) {
ext4_fc_get_tl(&tl, cur);
val = cur + EXT4_FC_TAG_BASE_LEN;
if (state->fc_replay_num_tags == 0) {
ret = JBD2_FC_REPLAY_STOP;
ext4_fc_set_bitmaps_and_counters(sb);
break;
}
ext4_debug("Replay phase, tag:%s\n", tag2str(tl.fc_tag));
state->fc_replay_num_tags--;
switch (tl.fc_tag) {
case EXT4_FC_TAG_LINK:
ret = ext4_fc_replay_link(sb, &tl, val);
break;
case EXT4_FC_TAG_UNLINK:
ret = ext4_fc_replay_unlink(sb, &tl, val);
break;
case EXT4_FC_TAG_ADD_RANGE:
ret = ext4_fc_replay_add_range(sb, &tl, val);
break;
case EXT4_FC_TAG_CREAT:
ret = ext4_fc_replay_create(sb, &tl, val);
break;
case EXT4_FC_TAG_DEL_RANGE:
ret = ext4_fc_replay_del_range(sb, &tl, val);
break;
case EXT4_FC_TAG_INODE:
ret = ext4_fc_replay_inode(sb, &tl, val);
break;
case EXT4_FC_TAG_PAD:
trace_ext4_fc_replay(sb, EXT4_FC_TAG_PAD, 0,
tl.fc_len, 0);
break;
case EXT4_FC_TAG_TAIL:
trace_ext4_fc_replay(sb, EXT4_FC_TAG_TAIL,
0, tl.fc_len, 0);
memcpy(&tail, val, sizeof(tail));
WARN_ON(le32_to_cpu(tail.fc_tid) != expected_tid);
break;
case EXT4_FC_TAG_HEAD:
break;
default:
trace_ext4_fc_replay(sb, tl.fc_tag, 0, tl.fc_len, 0);
ret = -ECANCELED;
break;
}
if (ret < 0)
break;
ret = JBD2_FC_REPLAY_CONTINUE;
}
return ret;
}
void ext4_fc_init(struct super_block *sb, journal_t *journal)
{
/*
* We set replay callback even if fast commit disabled because we may
* could still have fast commit blocks that need to be replayed even if
* fast commit has now been turned off.
*/
journal->j_fc_replay_callback = ext4_fc_replay;
if (!test_opt2(sb, JOURNAL_FAST_COMMIT))
return;
journal->j_fc_cleanup_callback = ext4_fc_cleanup;
}
static const char * const fc_ineligible_reasons[] = {
[EXT4_FC_REASON_XATTR] = "Extended attributes changed",
[EXT4_FC_REASON_CROSS_RENAME] = "Cross rename",
[EXT4_FC_REASON_JOURNAL_FLAG_CHANGE] = "Journal flag changed",
[EXT4_FC_REASON_NOMEM] = "Insufficient memory",
[EXT4_FC_REASON_SWAP_BOOT] = "Swap boot",
[EXT4_FC_REASON_RESIZE] = "Resize",
[EXT4_FC_REASON_RENAME_DIR] = "Dir renamed",
[EXT4_FC_REASON_FALLOC_RANGE] = "Falloc range op",
[EXT4_FC_REASON_INODE_JOURNAL_DATA] = "Data journalling",
[EXT4_FC_REASON_ENCRYPTED_FILENAME] = "Encrypted filename",
};
int ext4_fc_info_show(struct seq_file *seq, void *v)
{
struct ext4_sb_info *sbi = EXT4_SB((struct super_block *)seq->private);
struct ext4_fc_stats *stats = &sbi->s_fc_stats;
int i;
if (v != SEQ_START_TOKEN)
return 0;
seq_printf(seq,
"fc stats:\n%ld commits\n%ld ineligible\n%ld numblks\n%lluus avg_commit_time\n",
stats->fc_num_commits, stats->fc_ineligible_commits,
stats->fc_numblks,
div_u64(stats->s_fc_avg_commit_time, 1000));
seq_puts(seq, "Ineligible reasons:\n");
for (i = 0; i < EXT4_FC_REASON_MAX; i++)
seq_printf(seq, "\"%s\":\t%d\n", fc_ineligible_reasons[i],
stats->fc_ineligible_reason_count[i]);
return 0;
}
int __init ext4_fc_init_dentry_cache(void)
{
ext4_fc_dentry_cachep = KMEM_CACHE(ext4_fc_dentry_update,
SLAB_RECLAIM_ACCOUNT);
if (ext4_fc_dentry_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_fc_destroy_dentry_cache(void)
{
kmem_cache_destroy(ext4_fc_dentry_cachep);
}
| linux-master | fs/ext4/fast_commit.c |
// SPDX-License-Identifier: LGPL-2.1
/*
* Copyright (c) 2012 Taobao.
* Written by Tao Ma <[email protected]>
*/
#include <linux/iomap.h>
#include <linux/fiemap.h>
#include <linux/namei.h>
#include <linux/iversion.h>
#include <linux/sched/mm.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "truncate.h"
#define EXT4_XATTR_SYSTEM_DATA "data"
#define EXT4_MIN_INLINE_DATA_SIZE ((sizeof(__le32) * EXT4_N_BLOCKS))
#define EXT4_INLINE_DOTDOT_OFFSET 2
#define EXT4_INLINE_DOTDOT_SIZE 4
static int ext4_get_inline_size(struct inode *inode)
{
if (EXT4_I(inode)->i_inline_off)
return EXT4_I(inode)->i_inline_size;
return 0;
}
static int get_max_inline_xattr_value_size(struct inode *inode,
struct ext4_iloc *iloc)
{
struct ext4_xattr_ibody_header *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
void *end;
int free, min_offs;
if (!EXT4_INODE_HAS_XATTR_SPACE(inode))
return 0;
min_offs = EXT4_SB(inode->i_sb)->s_inode_size -
EXT4_GOOD_OLD_INODE_SIZE -
EXT4_I(inode)->i_extra_isize -
sizeof(struct ext4_xattr_ibody_header);
/*
* We need to subtract another sizeof(__u32) since an in-inode xattr
* needs an empty 4 bytes to indicate the gap between the xattr entry
* and the name/value pair.
*/
if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR))
return EXT4_XATTR_SIZE(min_offs -
EXT4_XATTR_LEN(strlen(EXT4_XATTR_SYSTEM_DATA)) -
EXT4_XATTR_ROUND - sizeof(__u32));
raw_inode = ext4_raw_inode(iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
/* Compute min_offs. */
while (!IS_LAST_ENTRY(entry)) {
void *next = EXT4_XATTR_NEXT(entry);
if (next >= end) {
EXT4_ERROR_INODE(inode,
"corrupt xattr in inline inode");
return 0;
}
if (!entry->e_value_inum && entry->e_value_size) {
size_t offs = le16_to_cpu(entry->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
entry = next;
}
free = min_offs -
((void *)entry - (void *)IFIRST(header)) - sizeof(__u32);
if (EXT4_I(inode)->i_inline_off) {
entry = (struct ext4_xattr_entry *)
((void *)raw_inode + EXT4_I(inode)->i_inline_off);
free += EXT4_XATTR_SIZE(le32_to_cpu(entry->e_value_size));
goto out;
}
free -= EXT4_XATTR_LEN(strlen(EXT4_XATTR_SYSTEM_DATA));
if (free > EXT4_XATTR_ROUND)
free = EXT4_XATTR_SIZE(free - EXT4_XATTR_ROUND);
else
free = 0;
out:
return free;
}
/*
* Get the maximum size we now can store in an inode.
* If we can't find the space for a xattr entry, don't use the space
* of the extents since we have no space to indicate the inline data.
*/
int ext4_get_max_inline_size(struct inode *inode)
{
int error, max_inline_size;
struct ext4_iloc iloc;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error) {
ext4_error_inode_err(inode, __func__, __LINE__, 0, -error,
"can't get inode location %lu",
inode->i_ino);
return 0;
}
down_read(&EXT4_I(inode)->xattr_sem);
max_inline_size = get_max_inline_xattr_value_size(inode, &iloc);
up_read(&EXT4_I(inode)->xattr_sem);
brelse(iloc.bh);
if (!max_inline_size)
return 0;
return max_inline_size + EXT4_MIN_INLINE_DATA_SIZE;
}
/*
* this function does not take xattr_sem, which is OK because it is
* currently only used in a code path coming form ext4_iget, before
* the new inode has been unlocked
*/
int ext4_find_inline_data_nolock(struct inode *inode)
{
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_info i = {
.name_index = EXT4_XATTR_INDEX_SYSTEM,
.name = EXT4_XATTR_SYSTEM_DATA,
};
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
return error;
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto out;
if (!is.s.not_found) {
if (is.s.here->e_value_inum) {
EXT4_ERROR_INODE(inode, "inline data xattr refers "
"to an external xattr inode");
error = -EFSCORRUPTED;
goto out;
}
EXT4_I(inode)->i_inline_off = (u16)((void *)is.s.here -
(void *)ext4_raw_inode(&is.iloc));
EXT4_I(inode)->i_inline_size = EXT4_MIN_INLINE_DATA_SIZE +
le32_to_cpu(is.s.here->e_value_size);
}
out:
brelse(is.iloc.bh);
return error;
}
static int ext4_read_inline_data(struct inode *inode, void *buffer,
unsigned int len,
struct ext4_iloc *iloc)
{
struct ext4_xattr_entry *entry;
struct ext4_xattr_ibody_header *header;
int cp_len = 0;
struct ext4_inode *raw_inode;
if (!len)
return 0;
BUG_ON(len > EXT4_I(inode)->i_inline_size);
cp_len = min_t(unsigned int, len, EXT4_MIN_INLINE_DATA_SIZE);
raw_inode = ext4_raw_inode(iloc);
memcpy(buffer, (void *)(raw_inode->i_block), cp_len);
len -= cp_len;
buffer += cp_len;
if (!len)
goto out;
header = IHDR(inode, raw_inode);
entry = (struct ext4_xattr_entry *)((void *)raw_inode +
EXT4_I(inode)->i_inline_off);
len = min_t(unsigned int, len,
(unsigned int)le32_to_cpu(entry->e_value_size));
memcpy(buffer,
(void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs), len);
cp_len += len;
out:
return cp_len;
}
/*
* write the buffer to the inline inode.
* If 'create' is set, we don't need to do the extra copy in the xattr
* value since it is already handled by ext4_xattr_ibody_set.
* That saves us one memcpy.
*/
static void ext4_write_inline_data(struct inode *inode, struct ext4_iloc *iloc,
void *buffer, loff_t pos, unsigned int len)
{
struct ext4_xattr_entry *entry;
struct ext4_xattr_ibody_header *header;
struct ext4_inode *raw_inode;
int cp_len = 0;
if (unlikely(ext4_forced_shutdown(inode->i_sb)))
return;
BUG_ON(!EXT4_I(inode)->i_inline_off);
BUG_ON(pos + len > EXT4_I(inode)->i_inline_size);
raw_inode = ext4_raw_inode(iloc);
buffer += pos;
if (pos < EXT4_MIN_INLINE_DATA_SIZE) {
cp_len = pos + len > EXT4_MIN_INLINE_DATA_SIZE ?
EXT4_MIN_INLINE_DATA_SIZE - pos : len;
memcpy((void *)raw_inode->i_block + pos, buffer, cp_len);
len -= cp_len;
buffer += cp_len;
pos += cp_len;
}
if (!len)
return;
pos -= EXT4_MIN_INLINE_DATA_SIZE;
header = IHDR(inode, raw_inode);
entry = (struct ext4_xattr_entry *)((void *)raw_inode +
EXT4_I(inode)->i_inline_off);
memcpy((void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs) + pos,
buffer, len);
}
static int ext4_create_inline_data(handle_t *handle,
struct inode *inode, unsigned len)
{
int error;
void *value = NULL;
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_info i = {
.name_index = EXT4_XATTR_INDEX_SYSTEM,
.name = EXT4_XATTR_SYSTEM_DATA,
};
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
return error;
BUFFER_TRACE(is.iloc.bh, "get_write_access");
error = ext4_journal_get_write_access(handle, inode->i_sb, is.iloc.bh,
EXT4_JTR_NONE);
if (error)
goto out;
if (len > EXT4_MIN_INLINE_DATA_SIZE) {
value = EXT4_ZERO_XATTR_VALUE;
len -= EXT4_MIN_INLINE_DATA_SIZE;
} else {
value = "";
len = 0;
}
/* Insert the xttr entry. */
i.value = value;
i.value_len = len;
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto out;
BUG_ON(!is.s.not_found);
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (error) {
if (error == -ENOSPC)
ext4_clear_inode_state(inode,
EXT4_STATE_MAY_INLINE_DATA);
goto out;
}
memset((void *)ext4_raw_inode(&is.iloc)->i_block,
0, EXT4_MIN_INLINE_DATA_SIZE);
EXT4_I(inode)->i_inline_off = (u16)((void *)is.s.here -
(void *)ext4_raw_inode(&is.iloc));
EXT4_I(inode)->i_inline_size = len + EXT4_MIN_INLINE_DATA_SIZE;
ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
ext4_set_inode_flag(inode, EXT4_INODE_INLINE_DATA);
get_bh(is.iloc.bh);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
out:
brelse(is.iloc.bh);
return error;
}
static int ext4_update_inline_data(handle_t *handle, struct inode *inode,
unsigned int len)
{
int error;
void *value = NULL;
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_info i = {
.name_index = EXT4_XATTR_INDEX_SYSTEM,
.name = EXT4_XATTR_SYSTEM_DATA,
};
/* If the old space is ok, write the data directly. */
if (len <= EXT4_I(inode)->i_inline_size)
return 0;
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
return error;
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto out;
BUG_ON(is.s.not_found);
len -= EXT4_MIN_INLINE_DATA_SIZE;
value = kzalloc(len, GFP_NOFS);
if (!value) {
error = -ENOMEM;
goto out;
}
error = ext4_xattr_ibody_get(inode, i.name_index, i.name,
value, len);
if (error < 0)
goto out;
BUFFER_TRACE(is.iloc.bh, "get_write_access");
error = ext4_journal_get_write_access(handle, inode->i_sb, is.iloc.bh,
EXT4_JTR_NONE);
if (error)
goto out;
/* Update the xattr entry. */
i.value = value;
i.value_len = len;
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (error)
goto out;
EXT4_I(inode)->i_inline_off = (u16)((void *)is.s.here -
(void *)ext4_raw_inode(&is.iloc));
EXT4_I(inode)->i_inline_size = EXT4_MIN_INLINE_DATA_SIZE +
le32_to_cpu(is.s.here->e_value_size);
ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
get_bh(is.iloc.bh);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
out:
kfree(value);
brelse(is.iloc.bh);
return error;
}
static int ext4_prepare_inline_data(handle_t *handle, struct inode *inode,
unsigned int len)
{
int ret, size, no_expand;
struct ext4_inode_info *ei = EXT4_I(inode);
if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
return -ENOSPC;
size = ext4_get_max_inline_size(inode);
if (size < len)
return -ENOSPC;
ext4_write_lock_xattr(inode, &no_expand);
if (ei->i_inline_off)
ret = ext4_update_inline_data(handle, inode, len);
else
ret = ext4_create_inline_data(handle, inode, len);
ext4_write_unlock_xattr(inode, &no_expand);
return ret;
}
static int ext4_destroy_inline_data_nolock(handle_t *handle,
struct inode *inode)
{
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_xattr_ibody_find is = {
.s = { .not_found = 0, },
};
struct ext4_xattr_info i = {
.name_index = EXT4_XATTR_INDEX_SYSTEM,
.name = EXT4_XATTR_SYSTEM_DATA,
.value = NULL,
.value_len = 0,
};
int error;
if (!ei->i_inline_off)
return 0;
error = ext4_get_inode_loc(inode, &is.iloc);
if (error)
return error;
error = ext4_xattr_ibody_find(inode, &i, &is);
if (error)
goto out;
BUFFER_TRACE(is.iloc.bh, "get_write_access");
error = ext4_journal_get_write_access(handle, inode->i_sb, is.iloc.bh,
EXT4_JTR_NONE);
if (error)
goto out;
error = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (error)
goto out;
memset((void *)ext4_raw_inode(&is.iloc)->i_block,
0, EXT4_MIN_INLINE_DATA_SIZE);
memset(ei->i_data, 0, EXT4_MIN_INLINE_DATA_SIZE);
if (ext4_has_feature_extents(inode->i_sb)) {
if (S_ISDIR(inode->i_mode) ||
S_ISREG(inode->i_mode) || S_ISLNK(inode->i_mode)) {
ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
ext4_ext_tree_init(handle, inode);
}
}
ext4_clear_inode_flag(inode, EXT4_INODE_INLINE_DATA);
get_bh(is.iloc.bh);
error = ext4_mark_iloc_dirty(handle, inode, &is.iloc);
EXT4_I(inode)->i_inline_off = 0;
EXT4_I(inode)->i_inline_size = 0;
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
out:
brelse(is.iloc.bh);
if (error == -ENODATA)
error = 0;
return error;
}
static int ext4_read_inline_folio(struct inode *inode, struct folio *folio)
{
void *kaddr;
int ret = 0;
size_t len;
struct ext4_iloc iloc;
BUG_ON(!folio_test_locked(folio));
BUG_ON(!ext4_has_inline_data(inode));
BUG_ON(folio->index);
if (!EXT4_I(inode)->i_inline_off) {
ext4_warning(inode->i_sb, "inode %lu doesn't have inline data.",
inode->i_ino);
goto out;
}
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
goto out;
len = min_t(size_t, ext4_get_inline_size(inode), i_size_read(inode));
BUG_ON(len > PAGE_SIZE);
kaddr = kmap_local_folio(folio, 0);
ret = ext4_read_inline_data(inode, kaddr, len, &iloc);
flush_dcache_folio(folio);
kunmap_local(kaddr);
folio_zero_segment(folio, len, folio_size(folio));
folio_mark_uptodate(folio);
brelse(iloc.bh);
out:
return ret;
}
int ext4_readpage_inline(struct inode *inode, struct folio *folio)
{
int ret = 0;
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
up_read(&EXT4_I(inode)->xattr_sem);
return -EAGAIN;
}
/*
* Current inline data can only exist in the 1st page,
* So for all the other pages, just set them uptodate.
*/
if (!folio->index)
ret = ext4_read_inline_folio(inode, folio);
else if (!folio_test_uptodate(folio)) {
folio_zero_segment(folio, 0, folio_size(folio));
folio_mark_uptodate(folio);
}
up_read(&EXT4_I(inode)->xattr_sem);
folio_unlock(folio);
return ret >= 0 ? 0 : ret;
}
static int ext4_convert_inline_data_to_extent(struct address_space *mapping,
struct inode *inode)
{
int ret, needed_blocks, no_expand;
handle_t *handle = NULL;
int retries = 0, sem_held = 0;
struct folio *folio = NULL;
unsigned from, to;
struct ext4_iloc iloc;
if (!ext4_has_inline_data(inode)) {
/*
* clear the flag so that no new write
* will trap here again.
*/
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
return 0;
}
needed_blocks = ext4_writepage_trans_blocks(inode);
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
retry:
handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
handle = NULL;
goto out;
}
/* We cannot recurse into the filesystem as the transaction is already
* started */
folio = __filemap_get_folio(mapping, 0, FGP_WRITEBEGIN | FGP_NOFS,
mapping_gfp_mask(mapping));
if (IS_ERR(folio)) {
ret = PTR_ERR(folio);
goto out_nofolio;
}
ext4_write_lock_xattr(inode, &no_expand);
sem_held = 1;
/* If some one has already done this for us, just exit. */
if (!ext4_has_inline_data(inode)) {
ret = 0;
goto out;
}
from = 0;
to = ext4_get_inline_size(inode);
if (!folio_test_uptodate(folio)) {
ret = ext4_read_inline_folio(inode, folio);
if (ret < 0)
goto out;
}
ret = ext4_destroy_inline_data_nolock(handle, inode);
if (ret)
goto out;
if (ext4_should_dioread_nolock(inode)) {
ret = __block_write_begin(&folio->page, from, to,
ext4_get_block_unwritten);
} else
ret = __block_write_begin(&folio->page, from, to, ext4_get_block);
if (!ret && ext4_should_journal_data(inode)) {
ret = ext4_walk_page_buffers(handle, inode,
folio_buffers(folio), from, to,
NULL, do_journal_get_write_access);
}
if (ret) {
folio_unlock(folio);
folio_put(folio);
folio = NULL;
ext4_orphan_add(handle, inode);
ext4_write_unlock_xattr(inode, &no_expand);
sem_held = 0;
ext4_journal_stop(handle);
handle = NULL;
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might
* still be on the orphan list; we need to
* make sure the inode is removed from the
* orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (folio)
block_commit_write(&folio->page, from, to);
out:
if (folio) {
folio_unlock(folio);
folio_put(folio);
}
out_nofolio:
if (sem_held)
ext4_write_unlock_xattr(inode, &no_expand);
if (handle)
ext4_journal_stop(handle);
brelse(iloc.bh);
return ret;
}
/*
* Try to write data in the inode.
* If the inode has inline data, check whether the new write can be
* in the inode also. If not, create the page the handle, move the data
* to the page make it update and let the later codes create extent for it.
*/
int ext4_try_to_write_inline_data(struct address_space *mapping,
struct inode *inode,
loff_t pos, unsigned len,
struct page **pagep)
{
int ret;
handle_t *handle;
struct folio *folio;
struct ext4_iloc iloc;
if (pos + len > ext4_get_max_inline_size(inode))
goto convert;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
/*
* The possible write could happen in the inode,
* so try to reserve the space in inode first.
*/
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
handle = NULL;
goto out;
}
ret = ext4_prepare_inline_data(handle, inode, pos + len);
if (ret && ret != -ENOSPC)
goto out;
/* We don't have space in inline inode, so convert it to extent. */
if (ret == -ENOSPC) {
ext4_journal_stop(handle);
brelse(iloc.bh);
goto convert;
}
ret = ext4_journal_get_write_access(handle, inode->i_sb, iloc.bh,
EXT4_JTR_NONE);
if (ret)
goto out;
folio = __filemap_get_folio(mapping, 0, FGP_WRITEBEGIN | FGP_NOFS,
mapping_gfp_mask(mapping));
if (IS_ERR(folio)) {
ret = PTR_ERR(folio);
goto out;
}
*pagep = &folio->page;
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
ret = 0;
folio_unlock(folio);
folio_put(folio);
goto out_up_read;
}
if (!folio_test_uptodate(folio)) {
ret = ext4_read_inline_folio(inode, folio);
if (ret < 0) {
folio_unlock(folio);
folio_put(folio);
goto out_up_read;
}
}
ret = 1;
handle = NULL;
out_up_read:
up_read(&EXT4_I(inode)->xattr_sem);
out:
if (handle && (ret != 1))
ext4_journal_stop(handle);
brelse(iloc.bh);
return ret;
convert:
return ext4_convert_inline_data_to_extent(mapping, inode);
}
int ext4_write_inline_data_end(struct inode *inode, loff_t pos, unsigned len,
unsigned copied, struct folio *folio)
{
handle_t *handle = ext4_journal_current_handle();
int no_expand;
void *kaddr;
struct ext4_iloc iloc;
int ret = 0, ret2;
if (unlikely(copied < len) && !folio_test_uptodate(folio))
copied = 0;
if (likely(copied)) {
ret = ext4_get_inode_loc(inode, &iloc);
if (ret) {
folio_unlock(folio);
folio_put(folio);
ext4_std_error(inode->i_sb, ret);
goto out;
}
ext4_write_lock_xattr(inode, &no_expand);
BUG_ON(!ext4_has_inline_data(inode));
/*
* ei->i_inline_off may have changed since
* ext4_write_begin() called
* ext4_try_to_write_inline_data()
*/
(void) ext4_find_inline_data_nolock(inode);
kaddr = kmap_local_folio(folio, 0);
ext4_write_inline_data(inode, &iloc, kaddr, pos, copied);
kunmap_local(kaddr);
folio_mark_uptodate(folio);
/* clear dirty flag so that writepages wouldn't work for us. */
folio_clear_dirty(folio);
ext4_write_unlock_xattr(inode, &no_expand);
brelse(iloc.bh);
/*
* It's important to update i_size while still holding folio
* lock: page writeout could otherwise come in and zero
* beyond i_size.
*/
ext4_update_inode_size(inode, pos + copied);
}
folio_unlock(folio);
folio_put(folio);
/*
* Don't mark the inode dirty under folio lock. First, it unnecessarily
* makes the holding time of folio lock longer. Second, it forces lock
* ordering of folio lock and transaction start for journaling
* filesystems.
*/
if (likely(copied))
mark_inode_dirty(inode);
out:
/*
* If we didn't copy as much data as expected, we need to trim back
* size of xattr containing inline data.
*/
if (pos + len > inode->i_size && ext4_can_truncate(inode))
ext4_orphan_add(handle, inode);
ret2 = ext4_journal_stop(handle);
if (!ret)
ret = ret2;
if (pos + len > inode->i_size) {
ext4_truncate_failed_write(inode);
/*
* If truncate failed early the inode might still be
* on the orphan list; we need to make sure the inode
* is removed from the orphan list in that case.
*/
if (inode->i_nlink)
ext4_orphan_del(NULL, inode);
}
return ret ? ret : copied;
}
/*
* Try to make the page cache and handle ready for the inline data case.
* We can call this function in 2 cases:
* 1. The inode is created and the first write exceeds inline size. We can
* clear the inode state safely.
* 2. The inode has inline data, then we need to read the data, make it
* update and dirty so that ext4_da_writepages can handle it. We don't
* need to start the journal since the file's metadata isn't changed now.
*/
static int ext4_da_convert_inline_data_to_extent(struct address_space *mapping,
struct inode *inode,
void **fsdata)
{
int ret = 0, inline_size;
struct folio *folio;
folio = __filemap_get_folio(mapping, 0, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping));
if (IS_ERR(folio))
return PTR_ERR(folio);
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
goto out;
}
inline_size = ext4_get_inline_size(inode);
if (!folio_test_uptodate(folio)) {
ret = ext4_read_inline_folio(inode, folio);
if (ret < 0)
goto out;
}
ret = __block_write_begin(&folio->page, 0, inline_size,
ext4_da_get_block_prep);
if (ret) {
up_read(&EXT4_I(inode)->xattr_sem);
folio_unlock(folio);
folio_put(folio);
ext4_truncate_failed_write(inode);
return ret;
}
folio_mark_dirty(folio);
folio_mark_uptodate(folio);
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
*fsdata = (void *)CONVERT_INLINE_DATA;
out:
up_read(&EXT4_I(inode)->xattr_sem);
if (folio) {
folio_unlock(folio);
folio_put(folio);
}
return ret;
}
/*
* Prepare the write for the inline data.
* If the data can be written into the inode, we just read
* the page and make it uptodate, and start the journal.
* Otherwise read the page, makes it dirty so that it can be
* handle in writepages(the i_disksize update is left to the
* normal ext4_da_write_end).
*/
int ext4_da_write_inline_data_begin(struct address_space *mapping,
struct inode *inode,
loff_t pos, unsigned len,
struct page **pagep,
void **fsdata)
{
int ret;
handle_t *handle;
struct folio *folio;
struct ext4_iloc iloc;
int retries = 0;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
retry_journal:
handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext4_prepare_inline_data(handle, inode, pos + len);
if (ret && ret != -ENOSPC)
goto out_journal;
if (ret == -ENOSPC) {
ext4_journal_stop(handle);
ret = ext4_da_convert_inline_data_to_extent(mapping,
inode,
fsdata);
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry_journal;
goto out;
}
/*
* We cannot recurse into the filesystem as the transaction
* is already started.
*/
folio = __filemap_get_folio(mapping, 0, FGP_WRITEBEGIN | FGP_NOFS,
mapping_gfp_mask(mapping));
if (IS_ERR(folio)) {
ret = PTR_ERR(folio);
goto out_journal;
}
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
ret = 0;
goto out_release_page;
}
if (!folio_test_uptodate(folio)) {
ret = ext4_read_inline_folio(inode, folio);
if (ret < 0)
goto out_release_page;
}
ret = ext4_journal_get_write_access(handle, inode->i_sb, iloc.bh,
EXT4_JTR_NONE);
if (ret)
goto out_release_page;
up_read(&EXT4_I(inode)->xattr_sem);
*pagep = &folio->page;
brelse(iloc.bh);
return 1;
out_release_page:
up_read(&EXT4_I(inode)->xattr_sem);
folio_unlock(folio);
folio_put(folio);
out_journal:
ext4_journal_stop(handle);
out:
brelse(iloc.bh);
return ret;
}
#ifdef INLINE_DIR_DEBUG
void ext4_show_inline_dir(struct inode *dir, struct buffer_head *bh,
void *inline_start, int inline_size)
{
int offset;
unsigned short de_len;
struct ext4_dir_entry_2 *de = inline_start;
void *dlimit = inline_start + inline_size;
trace_printk("inode %lu\n", dir->i_ino);
offset = 0;
while ((void *)de < dlimit) {
de_len = ext4_rec_len_from_disk(de->rec_len, inline_size);
trace_printk("de: off %u rlen %u name %.*s nlen %u ino %u\n",
offset, de_len, de->name_len, de->name,
de->name_len, le32_to_cpu(de->inode));
if (ext4_check_dir_entry(dir, NULL, de, bh,
inline_start, inline_size, offset))
BUG();
offset += de_len;
de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
}
}
#else
#define ext4_show_inline_dir(dir, bh, inline_start, inline_size)
#endif
/*
* Add a new entry into a inline dir.
* It will return -ENOSPC if no space is available, and -EIO
* and -EEXIST if directory entry already exists.
*/
static int ext4_add_dirent_to_inline(handle_t *handle,
struct ext4_filename *fname,
struct inode *dir,
struct inode *inode,
struct ext4_iloc *iloc,
void *inline_start, int inline_size)
{
int err;
struct ext4_dir_entry_2 *de;
err = ext4_find_dest_de(dir, inode, iloc->bh, inline_start,
inline_size, fname, &de);
if (err)
return err;
BUFFER_TRACE(iloc->bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, iloc->bh,
EXT4_JTR_NONE);
if (err)
return err;
ext4_insert_dentry(dir, inode, de, inline_size, fname);
ext4_show_inline_dir(dir, iloc->bh, inline_start, inline_size);
/*
* XXX shouldn't update any times until successful
* completion of syscall, but too many callers depend
* on this.
*
* XXX similarly, too many callers depend on
* ext4_new_inode() setting the times, but error
* recovery deletes the inode, so the worst that can
* happen is that the times are slightly out of date
* and/or different from the directory change time.
*/
dir->i_mtime = inode_set_ctime_current(dir);
ext4_update_dx_flag(dir);
inode_inc_iversion(dir);
return 1;
}
static void *ext4_get_inline_xattr_pos(struct inode *inode,
struct ext4_iloc *iloc)
{
struct ext4_xattr_entry *entry;
struct ext4_xattr_ibody_header *header;
BUG_ON(!EXT4_I(inode)->i_inline_off);
header = IHDR(inode, ext4_raw_inode(iloc));
entry = (struct ext4_xattr_entry *)((void *)ext4_raw_inode(iloc) +
EXT4_I(inode)->i_inline_off);
return (void *)IFIRST(header) + le16_to_cpu(entry->e_value_offs);
}
/* Set the final de to cover the whole block. */
static void ext4_update_final_de(void *de_buf, int old_size, int new_size)
{
struct ext4_dir_entry_2 *de, *prev_de;
void *limit;
int de_len;
de = de_buf;
if (old_size) {
limit = de_buf + old_size;
do {
prev_de = de;
de_len = ext4_rec_len_from_disk(de->rec_len, old_size);
de_buf += de_len;
de = de_buf;
} while (de_buf < limit);
prev_de->rec_len = ext4_rec_len_to_disk(de_len + new_size -
old_size, new_size);
} else {
/* this is just created, so create an empty entry. */
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(new_size, new_size);
}
}
static int ext4_update_inline_dir(handle_t *handle, struct inode *dir,
struct ext4_iloc *iloc)
{
int ret;
int old_size = EXT4_I(dir)->i_inline_size - EXT4_MIN_INLINE_DATA_SIZE;
int new_size = get_max_inline_xattr_value_size(dir, iloc);
if (new_size - old_size <= ext4_dir_rec_len(1, NULL))
return -ENOSPC;
ret = ext4_update_inline_data(handle, dir,
new_size + EXT4_MIN_INLINE_DATA_SIZE);
if (ret)
return ret;
ext4_update_final_de(ext4_get_inline_xattr_pos(dir, iloc), old_size,
EXT4_I(dir)->i_inline_size -
EXT4_MIN_INLINE_DATA_SIZE);
dir->i_size = EXT4_I(dir)->i_disksize = EXT4_I(dir)->i_inline_size;
return 0;
}
static void ext4_restore_inline_data(handle_t *handle, struct inode *inode,
struct ext4_iloc *iloc,
void *buf, int inline_size)
{
int ret;
ret = ext4_create_inline_data(handle, inode, inline_size);
if (ret) {
ext4_msg(inode->i_sb, KERN_EMERG,
"error restoring inline_data for inode -- potential data loss! (inode %lu, error %d)",
inode->i_ino, ret);
return;
}
ext4_write_inline_data(inode, iloc, buf, 0, inline_size);
ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
}
static int ext4_finish_convert_inline_dir(handle_t *handle,
struct inode *inode,
struct buffer_head *dir_block,
void *buf,
int inline_size)
{
int err, csum_size = 0, header_size = 0;
struct ext4_dir_entry_2 *de;
void *target = dir_block->b_data;
/*
* First create "." and ".." and then copy the dir information
* back to the block.
*/
de = target;
de = ext4_init_dot_dotdot(inode, de,
inode->i_sb->s_blocksize, csum_size,
le32_to_cpu(((struct ext4_dir_entry_2 *)buf)->inode), 1);
header_size = (void *)de - target;
memcpy((void *)de, buf + EXT4_INLINE_DOTDOT_SIZE,
inline_size - EXT4_INLINE_DOTDOT_SIZE);
if (ext4_has_metadata_csum(inode->i_sb))
csum_size = sizeof(struct ext4_dir_entry_tail);
inode->i_size = inode->i_sb->s_blocksize;
i_size_write(inode, inode->i_sb->s_blocksize);
EXT4_I(inode)->i_disksize = inode->i_sb->s_blocksize;
ext4_update_final_de(dir_block->b_data,
inline_size - EXT4_INLINE_DOTDOT_SIZE + header_size,
inode->i_sb->s_blocksize - csum_size);
if (csum_size)
ext4_initialize_dirent_tail(dir_block,
inode->i_sb->s_blocksize);
set_buffer_uptodate(dir_block);
unlock_buffer(dir_block);
err = ext4_handle_dirty_dirblock(handle, inode, dir_block);
if (err)
return err;
set_buffer_verified(dir_block);
return ext4_mark_inode_dirty(handle, inode);
}
static int ext4_convert_inline_data_nolock(handle_t *handle,
struct inode *inode,
struct ext4_iloc *iloc)
{
int error;
void *buf = NULL;
struct buffer_head *data_bh = NULL;
struct ext4_map_blocks map;
int inline_size;
inline_size = ext4_get_inline_size(inode);
buf = kmalloc(inline_size, GFP_NOFS);
if (!buf) {
error = -ENOMEM;
goto out;
}
error = ext4_read_inline_data(inode, buf, inline_size, iloc);
if (error < 0)
goto out;
/*
* Make sure the inline directory entries pass checks before we try to
* convert them, so that we avoid touching stuff that needs fsck.
*/
if (S_ISDIR(inode->i_mode)) {
error = ext4_check_all_de(inode, iloc->bh,
buf + EXT4_INLINE_DOTDOT_SIZE,
inline_size - EXT4_INLINE_DOTDOT_SIZE);
if (error)
goto out;
}
error = ext4_destroy_inline_data_nolock(handle, inode);
if (error)
goto out;
map.m_lblk = 0;
map.m_len = 1;
map.m_flags = 0;
error = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CREATE);
if (error < 0)
goto out_restore;
if (!(map.m_flags & EXT4_MAP_MAPPED)) {
error = -EIO;
goto out_restore;
}
data_bh = sb_getblk(inode->i_sb, map.m_pblk);
if (!data_bh) {
error = -ENOMEM;
goto out_restore;
}
lock_buffer(data_bh);
error = ext4_journal_get_create_access(handle, inode->i_sb, data_bh,
EXT4_JTR_NONE);
if (error) {
unlock_buffer(data_bh);
error = -EIO;
goto out_restore;
}
memset(data_bh->b_data, 0, inode->i_sb->s_blocksize);
if (!S_ISDIR(inode->i_mode)) {
memcpy(data_bh->b_data, buf, inline_size);
set_buffer_uptodate(data_bh);
unlock_buffer(data_bh);
error = ext4_handle_dirty_metadata(handle,
inode, data_bh);
} else {
error = ext4_finish_convert_inline_dir(handle, inode, data_bh,
buf, inline_size);
}
out_restore:
if (error)
ext4_restore_inline_data(handle, inode, iloc, buf, inline_size);
out:
brelse(data_bh);
kfree(buf);
return error;
}
/*
* Try to add the new entry to the inline data.
* If succeeds, return 0. If not, extended the inline dir and copied data to
* the new created block.
*/
int ext4_try_add_inline_entry(handle_t *handle, struct ext4_filename *fname,
struct inode *dir, struct inode *inode)
{
int ret, ret2, inline_size, no_expand;
void *inline_start;
struct ext4_iloc iloc;
ret = ext4_get_inode_loc(dir, &iloc);
if (ret)
return ret;
ext4_write_lock_xattr(dir, &no_expand);
if (!ext4_has_inline_data(dir))
goto out;
inline_start = (void *)ext4_raw_inode(&iloc)->i_block +
EXT4_INLINE_DOTDOT_SIZE;
inline_size = EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DOTDOT_SIZE;
ret = ext4_add_dirent_to_inline(handle, fname, dir, inode, &iloc,
inline_start, inline_size);
if (ret != -ENOSPC)
goto out;
/* check whether it can be inserted to inline xattr space. */
inline_size = EXT4_I(dir)->i_inline_size -
EXT4_MIN_INLINE_DATA_SIZE;
if (!inline_size) {
/* Try to use the xattr space.*/
ret = ext4_update_inline_dir(handle, dir, &iloc);
if (ret && ret != -ENOSPC)
goto out;
inline_size = EXT4_I(dir)->i_inline_size -
EXT4_MIN_INLINE_DATA_SIZE;
}
if (inline_size) {
inline_start = ext4_get_inline_xattr_pos(dir, &iloc);
ret = ext4_add_dirent_to_inline(handle, fname, dir,
inode, &iloc, inline_start,
inline_size);
if (ret != -ENOSPC)
goto out;
}
/*
* The inline space is filled up, so create a new block for it.
* As the extent tree will be created, we have to save the inline
* dir first.
*/
ret = ext4_convert_inline_data_nolock(handle, dir, &iloc);
out:
ext4_write_unlock_xattr(dir, &no_expand);
ret2 = ext4_mark_inode_dirty(handle, dir);
if (unlikely(ret2 && !ret))
ret = ret2;
brelse(iloc.bh);
return ret;
}
/*
* This function fills a red-black tree with information from an
* inlined dir. It returns the number directory entries loaded
* into the tree. If there is an error it is returned in err.
*/
int ext4_inlinedir_to_tree(struct file *dir_file,
struct inode *dir, ext4_lblk_t block,
struct dx_hash_info *hinfo,
__u32 start_hash, __u32 start_minor_hash,
int *has_inline_data)
{
int err = 0, count = 0;
unsigned int parent_ino;
int pos;
struct ext4_dir_entry_2 *de;
struct inode *inode = file_inode(dir_file);
int ret, inline_size = 0;
struct ext4_iloc iloc;
void *dir_buf = NULL;
struct ext4_dir_entry_2 fake;
struct fscrypt_str tmp_str;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
up_read(&EXT4_I(inode)->xattr_sem);
*has_inline_data = 0;
goto out;
}
inline_size = ext4_get_inline_size(inode);
dir_buf = kmalloc(inline_size, GFP_NOFS);
if (!dir_buf) {
ret = -ENOMEM;
up_read(&EXT4_I(inode)->xattr_sem);
goto out;
}
ret = ext4_read_inline_data(inode, dir_buf, inline_size, &iloc);
up_read(&EXT4_I(inode)->xattr_sem);
if (ret < 0)
goto out;
pos = 0;
parent_ino = le32_to_cpu(((struct ext4_dir_entry_2 *)dir_buf)->inode);
while (pos < inline_size) {
/*
* As inlined dir doesn't store any information about '.' and
* only the inode number of '..' is stored, we have to handle
* them differently.
*/
if (pos == 0) {
fake.inode = cpu_to_le32(inode->i_ino);
fake.name_len = 1;
strcpy(fake.name, ".");
fake.rec_len = ext4_rec_len_to_disk(
ext4_dir_rec_len(fake.name_len, NULL),
inline_size);
ext4_set_de_type(inode->i_sb, &fake, S_IFDIR);
de = &fake;
pos = EXT4_INLINE_DOTDOT_OFFSET;
} else if (pos == EXT4_INLINE_DOTDOT_OFFSET) {
fake.inode = cpu_to_le32(parent_ino);
fake.name_len = 2;
strcpy(fake.name, "..");
fake.rec_len = ext4_rec_len_to_disk(
ext4_dir_rec_len(fake.name_len, NULL),
inline_size);
ext4_set_de_type(inode->i_sb, &fake, S_IFDIR);
de = &fake;
pos = EXT4_INLINE_DOTDOT_SIZE;
} else {
de = (struct ext4_dir_entry_2 *)(dir_buf + pos);
pos += ext4_rec_len_from_disk(de->rec_len, inline_size);
if (ext4_check_dir_entry(inode, dir_file, de,
iloc.bh, dir_buf,
inline_size, pos)) {
ret = count;
goto out;
}
}
if (ext4_hash_in_dirent(dir)) {
hinfo->hash = EXT4_DIRENT_HASH(de);
hinfo->minor_hash = EXT4_DIRENT_MINOR_HASH(de);
} else {
ext4fs_dirhash(dir, de->name, de->name_len, hinfo);
}
if ((hinfo->hash < start_hash) ||
((hinfo->hash == start_hash) &&
(hinfo->minor_hash < start_minor_hash)))
continue;
if (de->inode == 0)
continue;
tmp_str.name = de->name;
tmp_str.len = de->name_len;
err = ext4_htree_store_dirent(dir_file, hinfo->hash,
hinfo->minor_hash, de, &tmp_str);
if (err) {
ret = err;
goto out;
}
count++;
}
ret = count;
out:
kfree(dir_buf);
brelse(iloc.bh);
return ret;
}
/*
* So this function is called when the volume is mkfsed with
* dir_index disabled. In order to keep f_pos persistent
* after we convert from an inlined dir to a blocked based,
* we just pretend that we are a normal dir and return the
* offset as if '.' and '..' really take place.
*
*/
int ext4_read_inline_dir(struct file *file,
struct dir_context *ctx,
int *has_inline_data)
{
unsigned int offset, parent_ino;
int i;
struct ext4_dir_entry_2 *de;
struct super_block *sb;
struct inode *inode = file_inode(file);
int ret, inline_size = 0;
struct ext4_iloc iloc;
void *dir_buf = NULL;
int dotdot_offset, dotdot_size, extra_offset, extra_size;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode)) {
up_read(&EXT4_I(inode)->xattr_sem);
*has_inline_data = 0;
goto out;
}
inline_size = ext4_get_inline_size(inode);
dir_buf = kmalloc(inline_size, GFP_NOFS);
if (!dir_buf) {
ret = -ENOMEM;
up_read(&EXT4_I(inode)->xattr_sem);
goto out;
}
ret = ext4_read_inline_data(inode, dir_buf, inline_size, &iloc);
up_read(&EXT4_I(inode)->xattr_sem);
if (ret < 0)
goto out;
ret = 0;
sb = inode->i_sb;
parent_ino = le32_to_cpu(((struct ext4_dir_entry_2 *)dir_buf)->inode);
offset = ctx->pos;
/*
* dotdot_offset and dotdot_size is the real offset and
* size for ".." and "." if the dir is block based while
* the real size for them are only EXT4_INLINE_DOTDOT_SIZE.
* So we will use extra_offset and extra_size to indicate them
* during the inline dir iteration.
*/
dotdot_offset = ext4_dir_rec_len(1, NULL);
dotdot_size = dotdot_offset + ext4_dir_rec_len(2, NULL);
extra_offset = dotdot_size - EXT4_INLINE_DOTDOT_SIZE;
extra_size = extra_offset + inline_size;
/*
* If the version has changed since the last call to
* readdir(2), then we might be pointing to an invalid
* dirent right now. Scan from the start of the inline
* dir to make sure.
*/
if (!inode_eq_iversion(inode, file->f_version)) {
for (i = 0; i < extra_size && i < offset;) {
/*
* "." is with offset 0 and
* ".." is dotdot_offset.
*/
if (!i) {
i = dotdot_offset;
continue;
} else if (i == dotdot_offset) {
i = dotdot_size;
continue;
}
/* for other entry, the real offset in
* the buf has to be tuned accordingly.
*/
de = (struct ext4_dir_entry_2 *)
(dir_buf + i - extra_offset);
/* It's too expensive to do a full
* dirent test each time round this
* loop, but we do have to test at
* least that it is non-zero. A
* failure will be detected in the
* dirent test below. */
if (ext4_rec_len_from_disk(de->rec_len, extra_size)
< ext4_dir_rec_len(1, NULL))
break;
i += ext4_rec_len_from_disk(de->rec_len,
extra_size);
}
offset = i;
ctx->pos = offset;
file->f_version = inode_query_iversion(inode);
}
while (ctx->pos < extra_size) {
if (ctx->pos == 0) {
if (!dir_emit(ctx, ".", 1, inode->i_ino, DT_DIR))
goto out;
ctx->pos = dotdot_offset;
continue;
}
if (ctx->pos == dotdot_offset) {
if (!dir_emit(ctx, "..", 2, parent_ino, DT_DIR))
goto out;
ctx->pos = dotdot_size;
continue;
}
de = (struct ext4_dir_entry_2 *)
(dir_buf + ctx->pos - extra_offset);
if (ext4_check_dir_entry(inode, file, de, iloc.bh, dir_buf,
extra_size, ctx->pos))
goto out;
if (le32_to_cpu(de->inode)) {
if (!dir_emit(ctx, de->name, de->name_len,
le32_to_cpu(de->inode),
get_dtype(sb, de->file_type)))
goto out;
}
ctx->pos += ext4_rec_len_from_disk(de->rec_len, extra_size);
}
out:
kfree(dir_buf);
brelse(iloc.bh);
return ret;
}
void *ext4_read_inline_link(struct inode *inode)
{
struct ext4_iloc iloc;
int ret, inline_size;
void *link;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ERR_PTR(ret);
ret = -ENOMEM;
inline_size = ext4_get_inline_size(inode);
link = kmalloc(inline_size + 1, GFP_NOFS);
if (!link)
goto out;
ret = ext4_read_inline_data(inode, link, inline_size, &iloc);
if (ret < 0) {
kfree(link);
goto out;
}
nd_terminate_link(link, inode->i_size, ret);
out:
if (ret < 0)
link = ERR_PTR(ret);
brelse(iloc.bh);
return link;
}
struct buffer_head *ext4_get_first_inline_block(struct inode *inode,
struct ext4_dir_entry_2 **parent_de,
int *retval)
{
struct ext4_iloc iloc;
*retval = ext4_get_inode_loc(inode, &iloc);
if (*retval)
return NULL;
*parent_de = (struct ext4_dir_entry_2 *)ext4_raw_inode(&iloc)->i_block;
return iloc.bh;
}
/*
* Try to create the inline data for the new dir.
* If it succeeds, return 0, otherwise return the error.
* In case of ENOSPC, the caller should create the normal disk layout dir.
*/
int ext4_try_create_inline_dir(handle_t *handle, struct inode *parent,
struct inode *inode)
{
int ret, inline_size = EXT4_MIN_INLINE_DATA_SIZE;
struct ext4_iloc iloc;
struct ext4_dir_entry_2 *de;
ret = ext4_get_inode_loc(inode, &iloc);
if (ret)
return ret;
ret = ext4_prepare_inline_data(handle, inode, inline_size);
if (ret)
goto out;
/*
* For inline dir, we only save the inode information for the ".."
* and create a fake dentry to cover the left space.
*/
de = (struct ext4_dir_entry_2 *)ext4_raw_inode(&iloc)->i_block;
de->inode = cpu_to_le32(parent->i_ino);
de = (struct ext4_dir_entry_2 *)((void *)de + EXT4_INLINE_DOTDOT_SIZE);
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(
inline_size - EXT4_INLINE_DOTDOT_SIZE,
inline_size);
set_nlink(inode, 2);
inode->i_size = EXT4_I(inode)->i_disksize = inline_size;
out:
brelse(iloc.bh);
return ret;
}
struct buffer_head *ext4_find_inline_entry(struct inode *dir,
struct ext4_filename *fname,
struct ext4_dir_entry_2 **res_dir,
int *has_inline_data)
{
int ret;
struct ext4_iloc iloc;
void *inline_start;
int inline_size;
if (ext4_get_inode_loc(dir, &iloc))
return NULL;
down_read(&EXT4_I(dir)->xattr_sem);
if (!ext4_has_inline_data(dir)) {
*has_inline_data = 0;
goto out;
}
inline_start = (void *)ext4_raw_inode(&iloc)->i_block +
EXT4_INLINE_DOTDOT_SIZE;
inline_size = EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DOTDOT_SIZE;
ret = ext4_search_dir(iloc.bh, inline_start, inline_size,
dir, fname, 0, res_dir);
if (ret == 1)
goto out_find;
if (ret < 0)
goto out;
if (ext4_get_inline_size(dir) == EXT4_MIN_INLINE_DATA_SIZE)
goto out;
inline_start = ext4_get_inline_xattr_pos(dir, &iloc);
inline_size = ext4_get_inline_size(dir) - EXT4_MIN_INLINE_DATA_SIZE;
ret = ext4_search_dir(iloc.bh, inline_start, inline_size,
dir, fname, 0, res_dir);
if (ret == 1)
goto out_find;
out:
brelse(iloc.bh);
iloc.bh = NULL;
out_find:
up_read(&EXT4_I(dir)->xattr_sem);
return iloc.bh;
}
int ext4_delete_inline_entry(handle_t *handle,
struct inode *dir,
struct ext4_dir_entry_2 *de_del,
struct buffer_head *bh,
int *has_inline_data)
{
int err, inline_size, no_expand;
struct ext4_iloc iloc;
void *inline_start;
err = ext4_get_inode_loc(dir, &iloc);
if (err)
return err;
ext4_write_lock_xattr(dir, &no_expand);
if (!ext4_has_inline_data(dir)) {
*has_inline_data = 0;
goto out;
}
if ((void *)de_del - ((void *)ext4_raw_inode(&iloc)->i_block) <
EXT4_MIN_INLINE_DATA_SIZE) {
inline_start = (void *)ext4_raw_inode(&iloc)->i_block +
EXT4_INLINE_DOTDOT_SIZE;
inline_size = EXT4_MIN_INLINE_DATA_SIZE -
EXT4_INLINE_DOTDOT_SIZE;
} else {
inline_start = ext4_get_inline_xattr_pos(dir, &iloc);
inline_size = ext4_get_inline_size(dir) -
EXT4_MIN_INLINE_DATA_SIZE;
}
BUFFER_TRACE(bh, "get_write_access");
err = ext4_journal_get_write_access(handle, dir->i_sb, bh,
EXT4_JTR_NONE);
if (err)
goto out;
err = ext4_generic_delete_entry(dir, de_del, bh,
inline_start, inline_size, 0);
if (err)
goto out;
ext4_show_inline_dir(dir, iloc.bh, inline_start, inline_size);
out:
ext4_write_unlock_xattr(dir, &no_expand);
if (likely(err == 0))
err = ext4_mark_inode_dirty(handle, dir);
brelse(iloc.bh);
if (err != -ENOENT)
ext4_std_error(dir->i_sb, err);
return err;
}
/*
* Get the inline dentry at offset.
*/
static inline struct ext4_dir_entry_2 *
ext4_get_inline_entry(struct inode *inode,
struct ext4_iloc *iloc,
unsigned int offset,
void **inline_start,
int *inline_size)
{
void *inline_pos;
BUG_ON(offset > ext4_get_inline_size(inode));
if (offset < EXT4_MIN_INLINE_DATA_SIZE) {
inline_pos = (void *)ext4_raw_inode(iloc)->i_block;
*inline_size = EXT4_MIN_INLINE_DATA_SIZE;
} else {
inline_pos = ext4_get_inline_xattr_pos(inode, iloc);
offset -= EXT4_MIN_INLINE_DATA_SIZE;
*inline_size = ext4_get_inline_size(inode) -
EXT4_MIN_INLINE_DATA_SIZE;
}
if (inline_start)
*inline_start = inline_pos;
return (struct ext4_dir_entry_2 *)(inline_pos + offset);
}
bool empty_inline_dir(struct inode *dir, int *has_inline_data)
{
int err, inline_size;
struct ext4_iloc iloc;
size_t inline_len;
void *inline_pos;
unsigned int offset;
struct ext4_dir_entry_2 *de;
bool ret = false;
err = ext4_get_inode_loc(dir, &iloc);
if (err) {
EXT4_ERROR_INODE_ERR(dir, -err,
"error %d getting inode %lu block",
err, dir->i_ino);
return false;
}
down_read(&EXT4_I(dir)->xattr_sem);
if (!ext4_has_inline_data(dir)) {
*has_inline_data = 0;
ret = true;
goto out;
}
de = (struct ext4_dir_entry_2 *)ext4_raw_inode(&iloc)->i_block;
if (!le32_to_cpu(de->inode)) {
ext4_warning(dir->i_sb,
"bad inline directory (dir #%lu) - no `..'",
dir->i_ino);
goto out;
}
inline_len = ext4_get_inline_size(dir);
offset = EXT4_INLINE_DOTDOT_SIZE;
while (offset < inline_len) {
de = ext4_get_inline_entry(dir, &iloc, offset,
&inline_pos, &inline_size);
if (ext4_check_dir_entry(dir, NULL, de,
iloc.bh, inline_pos,
inline_size, offset)) {
ext4_warning(dir->i_sb,
"bad inline directory (dir #%lu) - "
"inode %u, rec_len %u, name_len %d"
"inline size %d",
dir->i_ino, le32_to_cpu(de->inode),
le16_to_cpu(de->rec_len), de->name_len,
inline_size);
goto out;
}
if (le32_to_cpu(de->inode)) {
goto out;
}
offset += ext4_rec_len_from_disk(de->rec_len, inline_size);
}
ret = true;
out:
up_read(&EXT4_I(dir)->xattr_sem);
brelse(iloc.bh);
return ret;
}
int ext4_destroy_inline_data(handle_t *handle, struct inode *inode)
{
int ret, no_expand;
ext4_write_lock_xattr(inode, &no_expand);
ret = ext4_destroy_inline_data_nolock(handle, inode);
ext4_write_unlock_xattr(inode, &no_expand);
return ret;
}
int ext4_inline_data_iomap(struct inode *inode, struct iomap *iomap)
{
__u64 addr;
int error = -EAGAIN;
struct ext4_iloc iloc;
down_read(&EXT4_I(inode)->xattr_sem);
if (!ext4_has_inline_data(inode))
goto out;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
goto out;
addr = (__u64)iloc.bh->b_blocknr << inode->i_sb->s_blocksize_bits;
addr += (char *)ext4_raw_inode(&iloc) - iloc.bh->b_data;
addr += offsetof(struct ext4_inode, i_block);
brelse(iloc.bh);
iomap->addr = addr;
iomap->offset = 0;
iomap->length = min_t(loff_t, ext4_get_inline_size(inode),
i_size_read(inode));
iomap->type = IOMAP_INLINE;
iomap->flags = 0;
out:
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
int ext4_inline_data_truncate(struct inode *inode, int *has_inline)
{
handle_t *handle;
int inline_size, value_len, needed_blocks, no_expand, err = 0;
size_t i_size;
void *value = NULL;
struct ext4_xattr_ibody_find is = {
.s = { .not_found = -ENODATA, },
};
struct ext4_xattr_info i = {
.name_index = EXT4_XATTR_INDEX_SYSTEM,
.name = EXT4_XATTR_SYSTEM_DATA,
};
needed_blocks = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_INODE, needed_blocks);
if (IS_ERR(handle))
return PTR_ERR(handle);
ext4_write_lock_xattr(inode, &no_expand);
if (!ext4_has_inline_data(inode)) {
ext4_write_unlock_xattr(inode, &no_expand);
*has_inline = 0;
ext4_journal_stop(handle);
return 0;
}
if ((err = ext4_orphan_add(handle, inode)) != 0)
goto out;
if ((err = ext4_get_inode_loc(inode, &is.iloc)) != 0)
goto out;
down_write(&EXT4_I(inode)->i_data_sem);
i_size = inode->i_size;
inline_size = ext4_get_inline_size(inode);
EXT4_I(inode)->i_disksize = i_size;
if (i_size < inline_size) {
/*
* if there's inline data to truncate and this file was
* converted to extents after that inline data was written,
* the extent status cache must be cleared to avoid leaving
* behind stale delayed allocated extent entries
*/
if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
/* Clear the content in the xattr space. */
if (inline_size > EXT4_MIN_INLINE_DATA_SIZE) {
if ((err = ext4_xattr_ibody_find(inode, &i, &is)) != 0)
goto out_error;
BUG_ON(is.s.not_found);
value_len = le32_to_cpu(is.s.here->e_value_size);
value = kmalloc(value_len, GFP_NOFS);
if (!value) {
err = -ENOMEM;
goto out_error;
}
err = ext4_xattr_ibody_get(inode, i.name_index,
i.name, value, value_len);
if (err <= 0)
goto out_error;
i.value = value;
i.value_len = i_size > EXT4_MIN_INLINE_DATA_SIZE ?
i_size - EXT4_MIN_INLINE_DATA_SIZE : 0;
err = ext4_xattr_ibody_set(handle, inode, &i, &is);
if (err)
goto out_error;
}
/* Clear the content within i_blocks. */
if (i_size < EXT4_MIN_INLINE_DATA_SIZE) {
void *p = (void *) ext4_raw_inode(&is.iloc)->i_block;
memset(p + i_size, 0,
EXT4_MIN_INLINE_DATA_SIZE - i_size);
}
EXT4_I(inode)->i_inline_size = i_size <
EXT4_MIN_INLINE_DATA_SIZE ?
EXT4_MIN_INLINE_DATA_SIZE : i_size;
}
out_error:
up_write(&EXT4_I(inode)->i_data_sem);
out:
brelse(is.iloc.bh);
ext4_write_unlock_xattr(inode, &no_expand);
kfree(value);
if (inode->i_nlink)
ext4_orphan_del(handle, inode);
if (err == 0) {
inode->i_mtime = inode_set_ctime_current(inode);
err = ext4_mark_inode_dirty(handle, inode);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
ext4_journal_stop(handle);
return err;
}
int ext4_convert_inline_data(struct inode *inode)
{
int error, needed_blocks, no_expand;
handle_t *handle;
struct ext4_iloc iloc;
if (!ext4_has_inline_data(inode)) {
ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
return 0;
} else if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
/*
* Inode has inline data but EXT4_STATE_MAY_INLINE_DATA is
* cleared. This means we are in the middle of moving of
* inline data to delay allocated block. Just force writeout
* here to finish conversion.
*/
error = filemap_flush(inode->i_mapping);
if (error)
return error;
if (!ext4_has_inline_data(inode))
return 0;
}
needed_blocks = ext4_writepage_trans_blocks(inode);
iloc.bh = NULL;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
goto out_free;
}
ext4_write_lock_xattr(inode, &no_expand);
if (ext4_has_inline_data(inode))
error = ext4_convert_inline_data_nolock(handle, inode, &iloc);
ext4_write_unlock_xattr(inode, &no_expand);
ext4_journal_stop(handle);
out_free:
brelse(iloc.bh);
return error;
}
| linux-master | fs/ext4/inline.c |
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2017 Oracle. All Rights Reserved.
*
* Author: Darrick J. Wong <[email protected]>
*/
#include "ext4.h"
#include <linux/fsmap.h>
#include "fsmap.h"
#include "mballoc.h"
#include <linux/sort.h>
#include <linux/list_sort.h>
#include <trace/events/ext4.h>
/* Convert an ext4_fsmap to an fsmap. */
void ext4_fsmap_from_internal(struct super_block *sb, struct fsmap *dest,
struct ext4_fsmap *src)
{
dest->fmr_device = src->fmr_device;
dest->fmr_flags = src->fmr_flags;
dest->fmr_physical = src->fmr_physical << sb->s_blocksize_bits;
dest->fmr_owner = src->fmr_owner;
dest->fmr_offset = 0;
dest->fmr_length = src->fmr_length << sb->s_blocksize_bits;
dest->fmr_reserved[0] = 0;
dest->fmr_reserved[1] = 0;
dest->fmr_reserved[2] = 0;
}
/* Convert an fsmap to an ext4_fsmap. */
void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest,
struct fsmap *src)
{
dest->fmr_device = src->fmr_device;
dest->fmr_flags = src->fmr_flags;
dest->fmr_physical = src->fmr_physical >> sb->s_blocksize_bits;
dest->fmr_owner = src->fmr_owner;
dest->fmr_length = src->fmr_length >> sb->s_blocksize_bits;
}
/* getfsmap query state */
struct ext4_getfsmap_info {
struct ext4_fsmap_head *gfi_head;
ext4_fsmap_format_t gfi_formatter; /* formatting fn */
void *gfi_format_arg;/* format buffer */
ext4_fsblk_t gfi_next_fsblk; /* next fsblock we expect */
u32 gfi_dev; /* device id */
ext4_group_t gfi_agno; /* bg number, if applicable */
struct ext4_fsmap gfi_low; /* low rmap key */
struct ext4_fsmap gfi_high; /* high rmap key */
struct ext4_fsmap gfi_lastfree; /* free ext at end of last bg */
struct list_head gfi_meta_list; /* fixed metadata list */
bool gfi_last; /* last extent? */
};
/* Associate a device with a getfsmap handler. */
struct ext4_getfsmap_dev {
int (*gfd_fn)(struct super_block *sb,
struct ext4_fsmap *keys,
struct ext4_getfsmap_info *info);
u32 gfd_dev;
};
/* Compare two getfsmap device handlers. */
static int ext4_getfsmap_dev_compare(const void *p1, const void *p2)
{
const struct ext4_getfsmap_dev *d1 = p1;
const struct ext4_getfsmap_dev *d2 = p2;
return d1->gfd_dev - d2->gfd_dev;
}
/* Compare a record against our starting point */
static bool ext4_getfsmap_rec_before_low_key(struct ext4_getfsmap_info *info,
struct ext4_fsmap *rec)
{
return rec->fmr_physical < info->gfi_low.fmr_physical;
}
/*
* Format a reverse mapping for getfsmap, having translated rm_startblock
* into the appropriate daddr units.
*/
static int ext4_getfsmap_helper(struct super_block *sb,
struct ext4_getfsmap_info *info,
struct ext4_fsmap *rec)
{
struct ext4_fsmap fmr;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t rec_fsblk = rec->fmr_physical;
ext4_group_t agno;
ext4_grpblk_t cno;
int error;
if (fatal_signal_pending(current))
return -EINTR;
/*
* Filter out records that start before our startpoint, if the
* caller requested that.
*/
if (ext4_getfsmap_rec_before_low_key(info, rec)) {
rec_fsblk += rec->fmr_length;
if (info->gfi_next_fsblk < rec_fsblk)
info->gfi_next_fsblk = rec_fsblk;
return EXT4_QUERY_RANGE_CONTINUE;
}
/* Are we just counting mappings? */
if (info->gfi_head->fmh_count == 0) {
if (info->gfi_head->fmh_entries == UINT_MAX)
return EXT4_QUERY_RANGE_ABORT;
if (rec_fsblk > info->gfi_next_fsblk)
info->gfi_head->fmh_entries++;
if (info->gfi_last)
return EXT4_QUERY_RANGE_CONTINUE;
info->gfi_head->fmh_entries++;
rec_fsblk += rec->fmr_length;
if (info->gfi_next_fsblk < rec_fsblk)
info->gfi_next_fsblk = rec_fsblk;
return EXT4_QUERY_RANGE_CONTINUE;
}
/*
* If the record starts past the last physical block we saw,
* then we've found a gap. Report the gap as being owned by
* whatever the caller specified is the missing owner.
*/
if (rec_fsblk > info->gfi_next_fsblk) {
if (info->gfi_head->fmh_entries >= info->gfi_head->fmh_count)
return EXT4_QUERY_RANGE_ABORT;
ext4_get_group_no_and_offset(sb, info->gfi_next_fsblk,
&agno, &cno);
trace_ext4_fsmap_mapping(sb, info->gfi_dev, agno,
EXT4_C2B(sbi, cno),
rec_fsblk - info->gfi_next_fsblk,
EXT4_FMR_OWN_UNKNOWN);
fmr.fmr_device = info->gfi_dev;
fmr.fmr_physical = info->gfi_next_fsblk;
fmr.fmr_owner = EXT4_FMR_OWN_UNKNOWN;
fmr.fmr_length = rec_fsblk - info->gfi_next_fsblk;
fmr.fmr_flags = FMR_OF_SPECIAL_OWNER;
error = info->gfi_formatter(&fmr, info->gfi_format_arg);
if (error)
return error;
info->gfi_head->fmh_entries++;
}
if (info->gfi_last)
goto out;
/* Fill out the extent we found */
if (info->gfi_head->fmh_entries >= info->gfi_head->fmh_count)
return EXT4_QUERY_RANGE_ABORT;
ext4_get_group_no_and_offset(sb, rec_fsblk, &agno, &cno);
trace_ext4_fsmap_mapping(sb, info->gfi_dev, agno, EXT4_C2B(sbi, cno),
rec->fmr_length, rec->fmr_owner);
fmr.fmr_device = info->gfi_dev;
fmr.fmr_physical = rec_fsblk;
fmr.fmr_owner = rec->fmr_owner;
fmr.fmr_flags = FMR_OF_SPECIAL_OWNER;
fmr.fmr_length = rec->fmr_length;
error = info->gfi_formatter(&fmr, info->gfi_format_arg);
if (error)
return error;
info->gfi_head->fmh_entries++;
out:
rec_fsblk += rec->fmr_length;
if (info->gfi_next_fsblk < rec_fsblk)
info->gfi_next_fsblk = rec_fsblk;
return EXT4_QUERY_RANGE_CONTINUE;
}
static inline ext4_fsblk_t ext4_fsmap_next_pblk(struct ext4_fsmap *fmr)
{
return fmr->fmr_physical + fmr->fmr_length;
}
/* Transform a blockgroup's free record into a fsmap */
static int ext4_getfsmap_datadev_helper(struct super_block *sb,
ext4_group_t agno, ext4_grpblk_t start,
ext4_grpblk_t len, void *priv)
{
struct ext4_fsmap irec;
struct ext4_getfsmap_info *info = priv;
struct ext4_fsmap *p;
struct ext4_fsmap *tmp;
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t fsb;
ext4_fsblk_t fslen;
int error;
fsb = (EXT4_C2B(sbi, start) + ext4_group_first_block_no(sb, agno));
fslen = EXT4_C2B(sbi, len);
/* If the retained free extent record is set... */
if (info->gfi_lastfree.fmr_owner) {
/* ...and abuts this one, lengthen it and return. */
if (ext4_fsmap_next_pblk(&info->gfi_lastfree) == fsb) {
info->gfi_lastfree.fmr_length += fslen;
return 0;
}
/*
* There's a gap between the two free extents; emit the
* retained extent prior to merging the meta_list.
*/
error = ext4_getfsmap_helper(sb, info, &info->gfi_lastfree);
if (error)
return error;
info->gfi_lastfree.fmr_owner = 0;
}
/* Merge in any relevant extents from the meta_list */
list_for_each_entry_safe(p, tmp, &info->gfi_meta_list, fmr_list) {
if (p->fmr_physical + p->fmr_length <= info->gfi_next_fsblk) {
list_del(&p->fmr_list);
kfree(p);
} else if (p->fmr_physical < fsb) {
error = ext4_getfsmap_helper(sb, info, p);
if (error)
return error;
list_del(&p->fmr_list);
kfree(p);
}
}
irec.fmr_device = 0;
irec.fmr_physical = fsb;
irec.fmr_length = fslen;
irec.fmr_owner = EXT4_FMR_OWN_FREE;
irec.fmr_flags = 0;
/* If this is a free extent at the end of a bg, buffer it. */
if (ext4_fsmap_next_pblk(&irec) ==
ext4_group_first_block_no(sb, agno + 1)) {
info->gfi_lastfree = irec;
return 0;
}
/* Otherwise, emit it */
return ext4_getfsmap_helper(sb, info, &irec);
}
/* Execute a getfsmap query against the log device. */
static int ext4_getfsmap_logdev(struct super_block *sb, struct ext4_fsmap *keys,
struct ext4_getfsmap_info *info)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
struct ext4_fsmap irec;
/* Set up search keys */
info->gfi_low = keys[0];
info->gfi_low.fmr_length = 0;
memset(&info->gfi_high, 0xFF, sizeof(info->gfi_high));
trace_ext4_fsmap_low_key(sb, info->gfi_dev, 0,
info->gfi_low.fmr_physical,
info->gfi_low.fmr_length,
info->gfi_low.fmr_owner);
trace_ext4_fsmap_high_key(sb, info->gfi_dev, 0,
info->gfi_high.fmr_physical,
info->gfi_high.fmr_length,
info->gfi_high.fmr_owner);
if (keys[0].fmr_physical > 0)
return 0;
/* Fabricate an rmap entry for the external log device. */
irec.fmr_physical = journal->j_blk_offset;
irec.fmr_length = journal->j_total_len;
irec.fmr_owner = EXT4_FMR_OWN_LOG;
irec.fmr_flags = 0;
return ext4_getfsmap_helper(sb, info, &irec);
}
/* Helper to fill out an ext4_fsmap. */
static inline int ext4_getfsmap_fill(struct list_head *meta_list,
ext4_fsblk_t fsb, ext4_fsblk_t len,
uint64_t owner)
{
struct ext4_fsmap *fsm;
fsm = kmalloc(sizeof(*fsm), GFP_NOFS);
if (!fsm)
return -ENOMEM;
fsm->fmr_device = 0;
fsm->fmr_flags = 0;
fsm->fmr_physical = fsb;
fsm->fmr_owner = owner;
fsm->fmr_length = len;
list_add_tail(&fsm->fmr_list, meta_list);
return 0;
}
/*
* This function returns the number of file system metadata blocks at
* the beginning of a block group, including the reserved gdt blocks.
*/
static unsigned int ext4_getfsmap_find_sb(struct super_block *sb,
ext4_group_t agno,
struct list_head *meta_list)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t fsb = ext4_group_first_block_no(sb, agno);
ext4_fsblk_t len;
unsigned long first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
unsigned long metagroup = agno / EXT4_DESC_PER_BLOCK(sb);
int error;
/* Record the superblock. */
if (ext4_bg_has_super(sb, agno)) {
error = ext4_getfsmap_fill(meta_list, fsb, 1, EXT4_FMR_OWN_FS);
if (error)
return error;
fsb++;
}
/* Record the group descriptors. */
len = ext4_bg_num_gdb(sb, agno);
if (!len)
return 0;
error = ext4_getfsmap_fill(meta_list, fsb, len,
EXT4_FMR_OWN_GDT);
if (error)
return error;
fsb += len;
/* Reserved GDT blocks */
if (!ext4_has_feature_meta_bg(sb) || metagroup < first_meta_bg) {
len = le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks);
error = ext4_getfsmap_fill(meta_list, fsb, len,
EXT4_FMR_OWN_RESV_GDT);
if (error)
return error;
}
return 0;
}
/* Compare two fsmap items. */
static int ext4_getfsmap_compare(void *priv,
const struct list_head *a,
const struct list_head *b)
{
struct ext4_fsmap *fa;
struct ext4_fsmap *fb;
fa = container_of(a, struct ext4_fsmap, fmr_list);
fb = container_of(b, struct ext4_fsmap, fmr_list);
if (fa->fmr_physical < fb->fmr_physical)
return -1;
else if (fa->fmr_physical > fb->fmr_physical)
return 1;
return 0;
}
/* Merge adjacent extents of fixed metadata. */
static void ext4_getfsmap_merge_fixed_metadata(struct list_head *meta_list)
{
struct ext4_fsmap *p;
struct ext4_fsmap *prev = NULL;
struct ext4_fsmap *tmp;
list_for_each_entry_safe(p, tmp, meta_list, fmr_list) {
if (!prev) {
prev = p;
continue;
}
if (prev->fmr_owner == p->fmr_owner &&
prev->fmr_physical + prev->fmr_length == p->fmr_physical) {
prev->fmr_length += p->fmr_length;
list_del(&p->fmr_list);
kfree(p);
} else
prev = p;
}
}
/* Free a list of fixed metadata. */
static void ext4_getfsmap_free_fixed_metadata(struct list_head *meta_list)
{
struct ext4_fsmap *p;
struct ext4_fsmap *tmp;
list_for_each_entry_safe(p, tmp, meta_list, fmr_list) {
list_del(&p->fmr_list);
kfree(p);
}
}
/* Find all the fixed metadata in the filesystem. */
static int ext4_getfsmap_find_fixed_metadata(struct super_block *sb,
struct list_head *meta_list)
{
struct ext4_group_desc *gdp;
ext4_group_t agno;
int error;
INIT_LIST_HEAD(meta_list);
/* Collect everything. */
for (agno = 0; agno < EXT4_SB(sb)->s_groups_count; agno++) {
gdp = ext4_get_group_desc(sb, agno, NULL);
if (!gdp) {
error = -EFSCORRUPTED;
goto err;
}
/* Superblock & GDT */
error = ext4_getfsmap_find_sb(sb, agno, meta_list);
if (error)
goto err;
/* Block bitmap */
error = ext4_getfsmap_fill(meta_list,
ext4_block_bitmap(sb, gdp), 1,
EXT4_FMR_OWN_BLKBM);
if (error)
goto err;
/* Inode bitmap */
error = ext4_getfsmap_fill(meta_list,
ext4_inode_bitmap(sb, gdp), 1,
EXT4_FMR_OWN_INOBM);
if (error)
goto err;
/* Inodes */
error = ext4_getfsmap_fill(meta_list,
ext4_inode_table(sb, gdp),
EXT4_SB(sb)->s_itb_per_group,
EXT4_FMR_OWN_INODES);
if (error)
goto err;
}
/* Sort the list */
list_sort(NULL, meta_list, ext4_getfsmap_compare);
/* Merge adjacent extents */
ext4_getfsmap_merge_fixed_metadata(meta_list);
return 0;
err:
ext4_getfsmap_free_fixed_metadata(meta_list);
return error;
}
/* Execute a getfsmap query against the buddy bitmaps */
static int ext4_getfsmap_datadev(struct super_block *sb,
struct ext4_fsmap *keys,
struct ext4_getfsmap_info *info)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t start_fsb;
ext4_fsblk_t end_fsb;
ext4_fsblk_t bofs;
ext4_fsblk_t eofs;
ext4_group_t start_ag;
ext4_group_t end_ag;
ext4_grpblk_t first_cluster;
ext4_grpblk_t last_cluster;
int error = 0;
bofs = le32_to_cpu(sbi->s_es->s_first_data_block);
eofs = ext4_blocks_count(sbi->s_es);
if (keys[0].fmr_physical >= eofs)
return 0;
else if (keys[0].fmr_physical < bofs)
keys[0].fmr_physical = bofs;
if (keys[1].fmr_physical >= eofs)
keys[1].fmr_physical = eofs - 1;
if (keys[1].fmr_physical < keys[0].fmr_physical)
return 0;
start_fsb = keys[0].fmr_physical;
end_fsb = keys[1].fmr_physical;
/* Determine first and last group to examine based on start and end */
ext4_get_group_no_and_offset(sb, start_fsb, &start_ag, &first_cluster);
ext4_get_group_no_and_offset(sb, end_fsb, &end_ag, &last_cluster);
/*
* Convert the fsmap low/high keys to bg based keys. Initialize
* low to the fsmap low key and max out the high key to the end
* of the bg.
*/
info->gfi_low = keys[0];
info->gfi_low.fmr_physical = EXT4_C2B(sbi, first_cluster);
info->gfi_low.fmr_length = 0;
memset(&info->gfi_high, 0xFF, sizeof(info->gfi_high));
/* Assemble a list of all the fixed-location metadata. */
error = ext4_getfsmap_find_fixed_metadata(sb, &info->gfi_meta_list);
if (error)
goto err;
/* Query each bg */
for (info->gfi_agno = start_ag;
info->gfi_agno <= end_ag;
info->gfi_agno++) {
/*
* Set the bg high key from the fsmap high key if this
* is the last bg that we're querying.
*/
if (info->gfi_agno == end_ag) {
info->gfi_high = keys[1];
info->gfi_high.fmr_physical = EXT4_C2B(sbi,
last_cluster);
info->gfi_high.fmr_length = 0;
}
trace_ext4_fsmap_low_key(sb, info->gfi_dev, info->gfi_agno,
info->gfi_low.fmr_physical,
info->gfi_low.fmr_length,
info->gfi_low.fmr_owner);
trace_ext4_fsmap_high_key(sb, info->gfi_dev, info->gfi_agno,
info->gfi_high.fmr_physical,
info->gfi_high.fmr_length,
info->gfi_high.fmr_owner);
error = ext4_mballoc_query_range(sb, info->gfi_agno,
EXT4_B2C(sbi, info->gfi_low.fmr_physical),
EXT4_B2C(sbi, info->gfi_high.fmr_physical),
ext4_getfsmap_datadev_helper, info);
if (error)
goto err;
/*
* Set the bg low key to the start of the bg prior to
* moving on to the next bg.
*/
if (info->gfi_agno == start_ag)
memset(&info->gfi_low, 0, sizeof(info->gfi_low));
}
/* Do we have a retained free extent? */
if (info->gfi_lastfree.fmr_owner) {
error = ext4_getfsmap_helper(sb, info, &info->gfi_lastfree);
if (error)
goto err;
}
/* Report any gaps at the end of the bg */
info->gfi_last = true;
error = ext4_getfsmap_datadev_helper(sb, end_ag, last_cluster, 0, info);
if (error)
goto err;
err:
ext4_getfsmap_free_fixed_metadata(&info->gfi_meta_list);
return error;
}
/* Do we recognize the device? */
static bool ext4_getfsmap_is_valid_device(struct super_block *sb,
struct ext4_fsmap *fm)
{
if (fm->fmr_device == 0 || fm->fmr_device == UINT_MAX ||
fm->fmr_device == new_encode_dev(sb->s_bdev->bd_dev))
return true;
if (EXT4_SB(sb)->s_journal_bdev &&
fm->fmr_device == new_encode_dev(EXT4_SB(sb)->s_journal_bdev->bd_dev))
return true;
return false;
}
/* Ensure that the low key is less than the high key. */
static bool ext4_getfsmap_check_keys(struct ext4_fsmap *low_key,
struct ext4_fsmap *high_key)
{
if (low_key->fmr_device > high_key->fmr_device)
return false;
if (low_key->fmr_device < high_key->fmr_device)
return true;
if (low_key->fmr_physical > high_key->fmr_physical)
return false;
if (low_key->fmr_physical < high_key->fmr_physical)
return true;
if (low_key->fmr_owner > high_key->fmr_owner)
return false;
if (low_key->fmr_owner < high_key->fmr_owner)
return true;
return false;
}
#define EXT4_GETFSMAP_DEVS 2
/*
* Get filesystem's extents as described in head, and format for
* output. Calls formatter to fill the user's buffer until all
* extents are mapped, until the passed-in head->fmh_count slots have
* been filled, or until the formatter short-circuits the loop, if it
* is tracking filled-in extents on its own.
*
* Key to Confusion
* ----------------
* There are multiple levels of keys and counters at work here:
* _fsmap_head.fmh_keys -- low and high fsmap keys passed in;
* these reflect fs-wide block addrs.
* dkeys -- fmh_keys used to query each device;
* these are fmh_keys but w/ the low key
* bumped up by fmr_length.
* _getfsmap_info.gfi_next_fsblk-- next fs block we expect to see; this
* is how we detect gaps in the fsmap
* records and report them.
* _getfsmap_info.gfi_low/high -- per-bg low/high keys computed from
* dkeys; used to query the free space.
*/
int ext4_getfsmap(struct super_block *sb, struct ext4_fsmap_head *head,
ext4_fsmap_format_t formatter, void *arg)
{
struct ext4_fsmap dkeys[2]; /* per-dev keys */
struct ext4_getfsmap_dev handlers[EXT4_GETFSMAP_DEVS];
struct ext4_getfsmap_info info = { NULL };
int i;
int error = 0;
if (head->fmh_iflags & ~FMH_IF_VALID)
return -EINVAL;
if (!ext4_getfsmap_is_valid_device(sb, &head->fmh_keys[0]) ||
!ext4_getfsmap_is_valid_device(sb, &head->fmh_keys[1]))
return -EINVAL;
head->fmh_entries = 0;
/* Set up our device handlers. */
memset(handlers, 0, sizeof(handlers));
handlers[0].gfd_dev = new_encode_dev(sb->s_bdev->bd_dev);
handlers[0].gfd_fn = ext4_getfsmap_datadev;
if (EXT4_SB(sb)->s_journal_bdev) {
handlers[1].gfd_dev = new_encode_dev(
EXT4_SB(sb)->s_journal_bdev->bd_dev);
handlers[1].gfd_fn = ext4_getfsmap_logdev;
}
sort(handlers, EXT4_GETFSMAP_DEVS, sizeof(struct ext4_getfsmap_dev),
ext4_getfsmap_dev_compare, NULL);
/*
* To continue where we left off, we allow userspace to use the
* last mapping from a previous call as the low key of the next.
* This is identified by a non-zero length in the low key. We
* have to increment the low key in this scenario to ensure we
* don't return the same mapping again, and instead return the
* very next mapping.
*
* Bump the physical offset as there can be no other mapping for
* the same physical block range.
*/
dkeys[0] = head->fmh_keys[0];
dkeys[0].fmr_physical += dkeys[0].fmr_length;
dkeys[0].fmr_owner = 0;
dkeys[0].fmr_length = 0;
memset(&dkeys[1], 0xFF, sizeof(struct ext4_fsmap));
if (!ext4_getfsmap_check_keys(dkeys, &head->fmh_keys[1]))
return -EINVAL;
info.gfi_next_fsblk = head->fmh_keys[0].fmr_physical +
head->fmh_keys[0].fmr_length;
info.gfi_formatter = formatter;
info.gfi_format_arg = arg;
info.gfi_head = head;
/* For each device we support... */
for (i = 0; i < EXT4_GETFSMAP_DEVS; i++) {
/* Is this device within the range the user asked for? */
if (!handlers[i].gfd_fn)
continue;
if (head->fmh_keys[0].fmr_device > handlers[i].gfd_dev)
continue;
if (head->fmh_keys[1].fmr_device < handlers[i].gfd_dev)
break;
/*
* If this device number matches the high key, we have
* to pass the high key to the handler to limit the
* query results. If the device number exceeds the
* low key, zero out the low key so that we get
* everything from the beginning.
*/
if (handlers[i].gfd_dev == head->fmh_keys[1].fmr_device)
dkeys[1] = head->fmh_keys[1];
if (handlers[i].gfd_dev > head->fmh_keys[0].fmr_device)
memset(&dkeys[0], 0, sizeof(struct ext4_fsmap));
info.gfi_dev = handlers[i].gfd_dev;
info.gfi_last = false;
info.gfi_agno = -1;
error = handlers[i].gfd_fn(sb, dkeys, &info);
if (error)
break;
info.gfi_next_fsblk = 0;
}
head->fmh_oflags = FMH_OF_DEV_T;
return error;
}
| linux-master | fs/ext4/fsmap.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2012 Google, Inc.
*/
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/irqflags.h>
#include <linux/percpu.h>
#include <linux/smp.h>
#include <linux/atomic.h>
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/ftrace.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/err.h>
#include <linux/cache.h>
#include <linux/slab.h>
#include <asm/barrier.h>
#include "internal.h"
/* This doesn't need to be atomic: speed is chosen over correctness here. */
static u64 pstore_ftrace_stamp;
static void notrace pstore_ftrace_call(unsigned long ip,
unsigned long parent_ip,
struct ftrace_ops *op,
struct ftrace_regs *fregs)
{
int bit;
unsigned long flags;
struct pstore_ftrace_record rec = {};
struct pstore_record record = {
.type = PSTORE_TYPE_FTRACE,
.buf = (char *)&rec,
.size = sizeof(rec),
.psi = psinfo,
};
if (unlikely(oops_in_progress))
return;
bit = ftrace_test_recursion_trylock(ip, parent_ip);
if (bit < 0)
return;
local_irq_save(flags);
rec.ip = ip;
rec.parent_ip = parent_ip;
pstore_ftrace_write_timestamp(&rec, pstore_ftrace_stamp++);
pstore_ftrace_encode_cpu(&rec, raw_smp_processor_id());
psinfo->write(&record);
local_irq_restore(flags);
ftrace_test_recursion_unlock(bit);
}
static struct ftrace_ops pstore_ftrace_ops __read_mostly = {
.func = pstore_ftrace_call,
};
static DEFINE_MUTEX(pstore_ftrace_lock);
static bool pstore_ftrace_enabled;
static int pstore_set_ftrace_enabled(bool on)
{
ssize_t ret;
if (on == pstore_ftrace_enabled)
return 0;
if (on) {
ftrace_ops_set_global_filter(&pstore_ftrace_ops);
ret = register_ftrace_function(&pstore_ftrace_ops);
} else {
ret = unregister_ftrace_function(&pstore_ftrace_ops);
}
if (ret) {
pr_err("%s: unable to %sregister ftrace ops: %zd\n",
__func__, on ? "" : "un", ret);
} else {
pstore_ftrace_enabled = on;
}
return ret;
}
static ssize_t pstore_ftrace_knob_write(struct file *f, const char __user *buf,
size_t count, loff_t *ppos)
{
u8 on;
ssize_t ret;
ret = kstrtou8_from_user(buf, count, 2, &on);
if (ret)
return ret;
mutex_lock(&pstore_ftrace_lock);
ret = pstore_set_ftrace_enabled(on);
mutex_unlock(&pstore_ftrace_lock);
if (ret == 0)
ret = count;
return ret;
}
static ssize_t pstore_ftrace_knob_read(struct file *f, char __user *buf,
size_t count, loff_t *ppos)
{
char val[] = { '0' + pstore_ftrace_enabled, '\n' };
return simple_read_from_buffer(buf, count, ppos, val, sizeof(val));
}
static const struct file_operations pstore_knob_fops = {
.open = simple_open,
.read = pstore_ftrace_knob_read,
.write = pstore_ftrace_knob_write,
};
static struct dentry *pstore_ftrace_dir;
static bool record_ftrace;
module_param(record_ftrace, bool, 0400);
MODULE_PARM_DESC(record_ftrace,
"enable ftrace recording immediately (default: off)");
void pstore_register_ftrace(void)
{
if (!psinfo->write)
return;
pstore_ftrace_dir = debugfs_create_dir("pstore", NULL);
pstore_set_ftrace_enabled(record_ftrace);
debugfs_create_file("record_ftrace", 0600, pstore_ftrace_dir, NULL,
&pstore_knob_fops);
}
void pstore_unregister_ftrace(void)
{
mutex_lock(&pstore_ftrace_lock);
if (pstore_ftrace_enabled) {
unregister_ftrace_function(&pstore_ftrace_ops);
pstore_ftrace_enabled = false;
}
mutex_unlock(&pstore_ftrace_lock);
debugfs_remove_recursive(pstore_ftrace_dir);
}
ssize_t pstore_ftrace_combine_log(char **dest_log, size_t *dest_log_size,
const char *src_log, size_t src_log_size)
{
size_t dest_size, src_size, total, dest_off, src_off;
size_t dest_idx = 0, src_idx = 0, merged_idx = 0;
void *merged_buf;
struct pstore_ftrace_record *drec, *srec, *mrec;
size_t record_size = sizeof(struct pstore_ftrace_record);
dest_off = *dest_log_size % record_size;
dest_size = *dest_log_size - dest_off;
src_off = src_log_size % record_size;
src_size = src_log_size - src_off;
total = dest_size + src_size;
merged_buf = kmalloc(total, GFP_KERNEL);
if (!merged_buf)
return -ENOMEM;
drec = (struct pstore_ftrace_record *)(*dest_log + dest_off);
srec = (struct pstore_ftrace_record *)(src_log + src_off);
mrec = (struct pstore_ftrace_record *)(merged_buf);
while (dest_size > 0 && src_size > 0) {
if (pstore_ftrace_read_timestamp(&drec[dest_idx]) <
pstore_ftrace_read_timestamp(&srec[src_idx])) {
mrec[merged_idx++] = drec[dest_idx++];
dest_size -= record_size;
} else {
mrec[merged_idx++] = srec[src_idx++];
src_size -= record_size;
}
}
while (dest_size > 0) {
mrec[merged_idx++] = drec[dest_idx++];
dest_size -= record_size;
}
while (src_size > 0) {
mrec[merged_idx++] = srec[src_idx++];
src_size -= record_size;
}
kfree(*dest_log);
*dest_log = merged_buf;
*dest_log_size = total;
return 0;
}
EXPORT_SYMBOL_GPL(pstore_ftrace_combine_log);
| linux-master | fs/pstore/ftrace.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Persistent Storage - platform driver interface parts.
*
* Copyright (C) 2007-2008 Google, Inc.
* Copyright (C) 2010 Intel Corporation <[email protected]>
*/
#define pr_fmt(fmt) "pstore: " fmt
#include <linux/atomic.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kmsg_dump.h>
#include <linux/console.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/pstore.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/jiffies.h>
#include <linux/vmalloc.h>
#include <linux/workqueue.h>
#include <linux/zlib.h>
#include "internal.h"
/*
* We defer making "oops" entries appear in pstore - see
* whether the system is actually still running well enough
* to let someone see the entry
*/
static int pstore_update_ms = -1;
module_param_named(update_ms, pstore_update_ms, int, 0600);
MODULE_PARM_DESC(update_ms, "milliseconds before pstore updates its content "
"(default is -1, which means runtime updates are disabled; "
"enabling this option may not be safe; it may lead to further "
"corruption on Oopses)");
/* Names should be in the same order as the enum pstore_type_id */
static const char * const pstore_type_names[] = {
"dmesg",
"mce",
"console",
"ftrace",
"rtas",
"powerpc-ofw",
"powerpc-common",
"pmsg",
"powerpc-opal",
};
static int pstore_new_entry;
static void pstore_timefunc(struct timer_list *);
static DEFINE_TIMER(pstore_timer, pstore_timefunc);
static void pstore_dowork(struct work_struct *);
static DECLARE_WORK(pstore_work, pstore_dowork);
/*
* psinfo_lock protects "psinfo" during calls to
* pstore_register(), pstore_unregister(), and
* the filesystem mount/unmount routines.
*/
static DEFINE_MUTEX(psinfo_lock);
struct pstore_info *psinfo;
static char *backend;
module_param(backend, charp, 0444);
MODULE_PARM_DESC(backend, "specific backend to use");
/*
* pstore no longer implements compression via the crypto API, and only
* supports zlib deflate compression implemented using the zlib library
* interface. This removes additional complexity which is hard to justify for a
* diagnostic facility that has to operate in conditions where the system may
* have become unstable. Zlib deflate is comparatively small in terms of code
* size, and compresses ASCII text comparatively well. In terms of compression
* speed, deflate is not the best performer but for recording the log output on
* a kernel panic, this is not considered critical.
*
* The only remaining arguments supported by the compress= module parameter are
* 'deflate' and 'none'. To retain compatibility with existing installations,
* all other values are logged and replaced with 'deflate'.
*/
static char *compress = "deflate";
module_param(compress, charp, 0444);
MODULE_PARM_DESC(compress, "compression to use");
/* How much of the kernel log to snapshot */
unsigned long kmsg_bytes = CONFIG_PSTORE_DEFAULT_KMSG_BYTES;
module_param(kmsg_bytes, ulong, 0444);
MODULE_PARM_DESC(kmsg_bytes, "amount of kernel log to snapshot (in bytes)");
static void *compress_workspace;
/*
* Compression is only used for dmesg output, which consists of low-entropy
* ASCII text, and so we can assume worst-case 60%.
*/
#define DMESG_COMP_PERCENT 60
static char *big_oops_buf;
static size_t max_compressed_size;
void pstore_set_kmsg_bytes(int bytes)
{
kmsg_bytes = bytes;
}
/* Tag each group of saved records with a sequence number */
static int oopscount;
const char *pstore_type_to_name(enum pstore_type_id type)
{
BUILD_BUG_ON(ARRAY_SIZE(pstore_type_names) != PSTORE_TYPE_MAX);
if (WARN_ON_ONCE(type >= PSTORE_TYPE_MAX))
return "unknown";
return pstore_type_names[type];
}
EXPORT_SYMBOL_GPL(pstore_type_to_name);
enum pstore_type_id pstore_name_to_type(const char *name)
{
int i;
for (i = 0; i < PSTORE_TYPE_MAX; i++) {
if (!strcmp(pstore_type_names[i], name))
return i;
}
return PSTORE_TYPE_MAX;
}
EXPORT_SYMBOL_GPL(pstore_name_to_type);
static void pstore_timer_kick(void)
{
if (pstore_update_ms < 0)
return;
mod_timer(&pstore_timer, jiffies + msecs_to_jiffies(pstore_update_ms));
}
static bool pstore_cannot_block_path(enum kmsg_dump_reason reason)
{
/*
* In case of NMI path, pstore shouldn't be blocked
* regardless of reason.
*/
if (in_nmi())
return true;
switch (reason) {
/* In panic case, other cpus are stopped by smp_send_stop(). */
case KMSG_DUMP_PANIC:
/*
* Emergency restart shouldn't be blocked by spinning on
* pstore_info::buf_lock.
*/
case KMSG_DUMP_EMERG:
return true;
default:
return false;
}
}
static int pstore_compress(const void *in, void *out,
unsigned int inlen, unsigned int outlen)
{
struct z_stream_s zstream = {
.next_in = in,
.avail_in = inlen,
.next_out = out,
.avail_out = outlen,
.workspace = compress_workspace,
};
int ret;
if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS))
return -EINVAL;
ret = zlib_deflateInit2(&zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
if (ret != Z_OK)
return -EINVAL;
ret = zlib_deflate(&zstream, Z_FINISH);
if (ret != Z_STREAM_END)
return -EINVAL;
ret = zlib_deflateEnd(&zstream);
if (ret != Z_OK)
pr_warn_once("zlib_deflateEnd() failed: %d\n", ret);
return zstream.total_out;
}
static void allocate_buf_for_compression(void)
{
size_t compressed_size;
char *buf;
/* Skip if not built-in or compression disabled. */
if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !compress ||
!strcmp(compress, "none")) {
compress = NULL;
return;
}
if (strcmp(compress, "deflate")) {
pr_err("Unsupported compression '%s', falling back to deflate\n",
compress);
compress = "deflate";
}
/*
* The compression buffer only needs to be as large as the maximum
* uncompressed record size, since any record that would be expanded by
* compression is just stored uncompressed.
*/
compressed_size = (psinfo->bufsize * 100) / DMESG_COMP_PERCENT;
buf = kvzalloc(compressed_size, GFP_KERNEL);
if (!buf) {
pr_err("Failed %zu byte compression buffer allocation for: %s\n",
psinfo->bufsize, compress);
return;
}
compress_workspace =
vmalloc(zlib_deflate_workspacesize(MAX_WBITS, DEF_MEM_LEVEL));
if (!compress_workspace) {
pr_err("Failed to allocate zlib deflate workspace\n");
kvfree(buf);
return;
}
/* A non-NULL big_oops_buf indicates compression is available. */
big_oops_buf = buf;
max_compressed_size = compressed_size;
pr_info("Using crash dump compression: %s\n", compress);
}
static void free_buf_for_compression(void)
{
if (IS_ENABLED(CONFIG_PSTORE_COMPRESS) && compress_workspace) {
vfree(compress_workspace);
compress_workspace = NULL;
}
kvfree(big_oops_buf);
big_oops_buf = NULL;
max_compressed_size = 0;
}
void pstore_record_init(struct pstore_record *record,
struct pstore_info *psinfo)
{
memset(record, 0, sizeof(*record));
record->psi = psinfo;
/* Report zeroed timestamp if called before timekeeping has resumed. */
record->time = ns_to_timespec64(ktime_get_real_fast_ns());
}
/*
* callback from kmsg_dump. Save as much as we can (up to kmsg_bytes) from the
* end of the buffer.
*/
static void pstore_dump(struct kmsg_dumper *dumper,
enum kmsg_dump_reason reason)
{
struct kmsg_dump_iter iter;
unsigned long total = 0;
const char *why;
unsigned int part = 1;
unsigned long flags = 0;
int saved_ret = 0;
int ret;
why = kmsg_dump_reason_str(reason);
if (pstore_cannot_block_path(reason)) {
if (!spin_trylock_irqsave(&psinfo->buf_lock, flags)) {
pr_err("dump skipped in %s path because of concurrent dump\n",
in_nmi() ? "NMI" : why);
return;
}
} else {
spin_lock_irqsave(&psinfo->buf_lock, flags);
}
kmsg_dump_rewind(&iter);
oopscount++;
while (total < kmsg_bytes) {
char *dst;
size_t dst_size;
int header_size;
int zipped_len = -1;
size_t dump_size;
struct pstore_record record;
pstore_record_init(&record, psinfo);
record.type = PSTORE_TYPE_DMESG;
record.count = oopscount;
record.reason = reason;
record.part = part;
record.buf = psinfo->buf;
dst = big_oops_buf ?: psinfo->buf;
dst_size = max_compressed_size ?: psinfo->bufsize;
/* Write dump header. */
header_size = snprintf(dst, dst_size, "%s#%d Part%u\n", why,
oopscount, part);
dst_size -= header_size;
/* Write dump contents. */
if (!kmsg_dump_get_buffer(&iter, true, dst + header_size,
dst_size, &dump_size))
break;
if (big_oops_buf) {
zipped_len = pstore_compress(dst, psinfo->buf,
header_size + dump_size,
psinfo->bufsize);
if (zipped_len > 0) {
record.compressed = true;
record.size = zipped_len;
} else {
/*
* Compression failed, so the buffer is most
* likely filled with binary data that does not
* compress as well as ASCII text. Copy as much
* of the uncompressed data as possible into
* the pstore record, and discard the rest.
*/
record.size = psinfo->bufsize;
memcpy(psinfo->buf, dst, psinfo->bufsize);
}
} else {
record.size = header_size + dump_size;
}
ret = psinfo->write(&record);
if (ret == 0 && reason == KMSG_DUMP_OOPS) {
pstore_new_entry = 1;
pstore_timer_kick();
} else {
/* Preserve only the first non-zero returned value. */
if (!saved_ret)
saved_ret = ret;
}
total += record.size;
part++;
}
spin_unlock_irqrestore(&psinfo->buf_lock, flags);
if (saved_ret) {
pr_err_once("backend (%s) writing error (%d)\n", psinfo->name,
saved_ret);
}
}
static struct kmsg_dumper pstore_dumper = {
.dump = pstore_dump,
};
/*
* Register with kmsg_dump to save last part of console log on panic.
*/
static void pstore_register_kmsg(void)
{
kmsg_dump_register(&pstore_dumper);
}
static void pstore_unregister_kmsg(void)
{
kmsg_dump_unregister(&pstore_dumper);
}
#ifdef CONFIG_PSTORE_CONSOLE
static void pstore_console_write(struct console *con, const char *s, unsigned c)
{
struct pstore_record record;
if (!c)
return;
pstore_record_init(&record, psinfo);
record.type = PSTORE_TYPE_CONSOLE;
record.buf = (char *)s;
record.size = c;
psinfo->write(&record);
}
static struct console pstore_console = {
.write = pstore_console_write,
.index = -1,
};
static void pstore_register_console(void)
{
/* Show which backend is going to get console writes. */
strscpy(pstore_console.name, psinfo->name,
sizeof(pstore_console.name));
/*
* Always initialize flags here since prior unregister_console()
* calls may have changed settings (specifically CON_ENABLED).
*/
pstore_console.flags = CON_PRINTBUFFER | CON_ENABLED | CON_ANYTIME;
register_console(&pstore_console);
}
static void pstore_unregister_console(void)
{
unregister_console(&pstore_console);
}
#else
static void pstore_register_console(void) {}
static void pstore_unregister_console(void) {}
#endif
static int pstore_write_user_compat(struct pstore_record *record,
const char __user *buf)
{
int ret = 0;
if (record->buf)
return -EINVAL;
record->buf = vmemdup_user(buf, record->size);
if (IS_ERR(record->buf)) {
ret = PTR_ERR(record->buf);
goto out;
}
ret = record->psi->write(record);
kvfree(record->buf);
out:
record->buf = NULL;
return unlikely(ret < 0) ? ret : record->size;
}
/*
* platform specific persistent storage driver registers with
* us here. If pstore is already mounted, call the platform
* read function right away to populate the file system. If not
* then the pstore mount code will call us later to fill out
* the file system.
*/
int pstore_register(struct pstore_info *psi)
{
if (backend && strcmp(backend, psi->name)) {
pr_warn("backend '%s' already in use: ignoring '%s'\n",
backend, psi->name);
return -EBUSY;
}
/* Sanity check flags. */
if (!psi->flags) {
pr_warn("backend '%s' must support at least one frontend\n",
psi->name);
return -EINVAL;
}
/* Check for required functions. */
if (!psi->read || !psi->write) {
pr_warn("backend '%s' must implement read() and write()\n",
psi->name);
return -EINVAL;
}
mutex_lock(&psinfo_lock);
if (psinfo) {
pr_warn("backend '%s' already loaded: ignoring '%s'\n",
psinfo->name, psi->name);
mutex_unlock(&psinfo_lock);
return -EBUSY;
}
if (!psi->write_user)
psi->write_user = pstore_write_user_compat;
psinfo = psi;
mutex_init(&psinfo->read_mutex);
spin_lock_init(&psinfo->buf_lock);
if (psi->flags & PSTORE_FLAGS_DMESG)
allocate_buf_for_compression();
pstore_get_records(0);
if (psi->flags & PSTORE_FLAGS_DMESG) {
pstore_dumper.max_reason = psinfo->max_reason;
pstore_register_kmsg();
}
if (psi->flags & PSTORE_FLAGS_CONSOLE)
pstore_register_console();
if (psi->flags & PSTORE_FLAGS_FTRACE)
pstore_register_ftrace();
if (psi->flags & PSTORE_FLAGS_PMSG)
pstore_register_pmsg();
/* Start watching for new records, if desired. */
pstore_timer_kick();
/*
* Update the module parameter backend, so it is visible
* through /sys/module/pstore/parameters/backend
*/
backend = kstrdup(psi->name, GFP_KERNEL);
pr_info("Registered %s as persistent store backend\n", psi->name);
mutex_unlock(&psinfo_lock);
return 0;
}
EXPORT_SYMBOL_GPL(pstore_register);
void pstore_unregister(struct pstore_info *psi)
{
/* It's okay to unregister nothing. */
if (!psi)
return;
mutex_lock(&psinfo_lock);
/* Only one backend can be registered at a time. */
if (WARN_ON(psi != psinfo)) {
mutex_unlock(&psinfo_lock);
return;
}
/* Unregister all callbacks. */
if (psi->flags & PSTORE_FLAGS_PMSG)
pstore_unregister_pmsg();
if (psi->flags & PSTORE_FLAGS_FTRACE)
pstore_unregister_ftrace();
if (psi->flags & PSTORE_FLAGS_CONSOLE)
pstore_unregister_console();
if (psi->flags & PSTORE_FLAGS_DMESG)
pstore_unregister_kmsg();
/* Stop timer and make sure all work has finished. */
del_timer_sync(&pstore_timer);
flush_work(&pstore_work);
/* Remove all backend records from filesystem tree. */
pstore_put_backend_records(psi);
free_buf_for_compression();
psinfo = NULL;
kfree(backend);
backend = NULL;
pr_info("Unregistered %s as persistent store backend\n", psi->name);
mutex_unlock(&psinfo_lock);
}
EXPORT_SYMBOL_GPL(pstore_unregister);
static void decompress_record(struct pstore_record *record,
struct z_stream_s *zstream)
{
int ret;
int unzipped_len;
char *unzipped, *workspace;
size_t max_uncompressed_size;
if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !record->compressed)
return;
/* Only PSTORE_TYPE_DMESG support compression. */
if (record->type != PSTORE_TYPE_DMESG) {
pr_warn("ignored compressed record type %d\n", record->type);
return;
}
/* Missing compression buffer means compression was not initialized. */
if (!zstream->workspace) {
pr_warn("no decompression method initialized!\n");
return;
}
ret = zlib_inflateReset(zstream);
if (ret != Z_OK) {
pr_err("zlib_inflateReset() failed, ret = %d!\n", ret);
return;
}
/* Allocate enough space to hold max decompression and ECC. */
max_uncompressed_size = 3 * psinfo->bufsize;
workspace = kvzalloc(max_uncompressed_size + record->ecc_notice_size,
GFP_KERNEL);
if (!workspace)
return;
zstream->next_in = record->buf;
zstream->avail_in = record->size;
zstream->next_out = workspace;
zstream->avail_out = max_uncompressed_size;
ret = zlib_inflate(zstream, Z_FINISH);
if (ret != Z_STREAM_END) {
pr_err_ratelimited("zlib_inflate() failed, ret = %d!\n", ret);
kvfree(workspace);
return;
}
unzipped_len = zstream->total_out;
/* Append ECC notice to decompressed buffer. */
memcpy(workspace + unzipped_len, record->buf + record->size,
record->ecc_notice_size);
/* Copy decompressed contents into an minimum-sized allocation. */
unzipped = kvmemdup(workspace, unzipped_len + record->ecc_notice_size,
GFP_KERNEL);
kvfree(workspace);
if (!unzipped)
return;
/* Swap out compressed contents with decompressed contents. */
kvfree(record->buf);
record->buf = unzipped;
record->size = unzipped_len;
record->compressed = false;
}
/*
* Read all the records from one persistent store backend. Create
* files in our filesystem. Don't warn about -EEXIST errors
* when we are re-scanning the backing store looking to add new
* error records.
*/
void pstore_get_backend_records(struct pstore_info *psi,
struct dentry *root, int quiet)
{
int failed = 0;
unsigned int stop_loop = 65536;
struct z_stream_s zstream = {};
if (!psi || !root)
return;
if (IS_ENABLED(CONFIG_PSTORE_COMPRESS) && compress) {
zstream.workspace = kvmalloc(zlib_inflate_workspacesize(),
GFP_KERNEL);
zlib_inflateInit2(&zstream, -DEF_WBITS);
}
mutex_lock(&psi->read_mutex);
if (psi->open && psi->open(psi))
goto out;
/*
* Backend callback read() allocates record.buf. decompress_record()
* may reallocate record.buf. On success, pstore_mkfile() will keep
* the record.buf, so free it only on failure.
*/
for (; stop_loop; stop_loop--) {
struct pstore_record *record;
int rc;
record = kzalloc(sizeof(*record), GFP_KERNEL);
if (!record) {
pr_err("out of memory creating record\n");
break;
}
pstore_record_init(record, psi);
record->size = psi->read(record);
/* No more records left in backend? */
if (record->size <= 0) {
kfree(record);
break;
}
decompress_record(record, &zstream);
rc = pstore_mkfile(root, record);
if (rc) {
/* pstore_mkfile() did not take record, so free it. */
kvfree(record->buf);
kfree(record->priv);
kfree(record);
if (rc != -EEXIST || !quiet)
failed++;
}
}
if (psi->close)
psi->close(psi);
out:
mutex_unlock(&psi->read_mutex);
if (IS_ENABLED(CONFIG_PSTORE_COMPRESS) && compress) {
if (zlib_inflateEnd(&zstream) != Z_OK)
pr_warn("zlib_inflateEnd() failed\n");
kvfree(zstream.workspace);
}
if (failed)
pr_warn("failed to create %d record(s) from '%s'\n",
failed, psi->name);
if (!stop_loop)
pr_err("looping? Too many records seen from '%s'\n",
psi->name);
}
static void pstore_dowork(struct work_struct *work)
{
pstore_get_records(1);
}
static void pstore_timefunc(struct timer_list *unused)
{
if (pstore_new_entry) {
pstore_new_entry = 0;
schedule_work(&pstore_work);
}
pstore_timer_kick();
}
static int __init pstore_init(void)
{
int ret;
ret = pstore_init_fs();
if (ret)
free_buf_for_compression();
return ret;
}
late_initcall(pstore_init);
static void __exit pstore_exit(void)
{
pstore_exit_fs();
}
module_exit(pstore_exit)
MODULE_AUTHOR("Tony Luck <[email protected]>");
MODULE_LICENSE("GPL");
| linux-master | fs/pstore/platform.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2014 Google, Inc.
*/
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include "internal.h"
static DEFINE_MUTEX(pmsg_lock);
static ssize_t write_pmsg(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct pstore_record record;
int ret;
if (!count)
return 0;
pstore_record_init(&record, psinfo);
record.type = PSTORE_TYPE_PMSG;
record.size = count;
/* check outside lock, page in any data. write_user also checks */
if (!access_ok(buf, count))
return -EFAULT;
mutex_lock(&pmsg_lock);
ret = psinfo->write_user(&record, buf);
mutex_unlock(&pmsg_lock);
return ret ? ret : count;
}
static const struct file_operations pmsg_fops = {
.owner = THIS_MODULE,
.llseek = noop_llseek,
.write = write_pmsg,
};
static struct class *pmsg_class;
static int pmsg_major;
#define PMSG_NAME "pmsg"
#undef pr_fmt
#define pr_fmt(fmt) PMSG_NAME ": " fmt
static char *pmsg_devnode(const struct device *dev, umode_t *mode)
{
if (mode)
*mode = 0220;
return NULL;
}
void pstore_register_pmsg(void)
{
struct device *pmsg_device;
pmsg_major = register_chrdev(0, PMSG_NAME, &pmsg_fops);
if (pmsg_major < 0) {
pr_err("register_chrdev failed\n");
goto err;
}
pmsg_class = class_create(PMSG_NAME);
if (IS_ERR(pmsg_class)) {
pr_err("device class file already in use\n");
goto err_class;
}
pmsg_class->devnode = pmsg_devnode;
pmsg_device = device_create(pmsg_class, NULL, MKDEV(pmsg_major, 0),
NULL, "%s%d", PMSG_NAME, 0);
if (IS_ERR(pmsg_device)) {
pr_err("failed to create device\n");
goto err_device;
}
return;
err_device:
class_destroy(pmsg_class);
err_class:
unregister_chrdev(pmsg_major, PMSG_NAME);
err:
return;
}
void pstore_unregister_pmsg(void)
{
device_destroy(pmsg_class, MKDEV(pmsg_major, 0));
class_destroy(pmsg_class);
unregister_chrdev(pmsg_major, PMSG_NAME);
}
| linux-master | fs/pstore/pmsg.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Provide a pstore intermediate backend, organized into kernel memory
* allocated zones that are then mapped and flushed into a single
* contiguous region on a storage backend of some kind (block, mtd, etc).
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mount.h>
#include <linux/printk.h>
#include <linux/fs.h>
#include <linux/pstore_zone.h>
#include <linux/kdev_t.h>
#include <linux/device.h>
#include <linux/namei.h>
#include <linux/fcntl.h>
#include <linux/uio.h>
#include <linux/writeback.h>
#include "internal.h"
/**
* struct psz_buffer - header of zone to flush to storage
*
* @sig: signature to indicate header (PSZ_SIG xor PSZONE-type value)
* @datalen: length of data in @data
* @start: offset into @data where the beginning of the stored bytes begin
* @data: zone data.
*/
struct psz_buffer {
#define PSZ_SIG (0x43474244) /* DBGC */
uint32_t sig;
atomic_t datalen;
atomic_t start;
uint8_t data[];
};
/**
* struct psz_kmsg_header - kmsg dump-specific header to flush to storage
*
* @magic: magic num for kmsg dump header
* @time: kmsg dump trigger time
* @compressed: whether conpressed
* @counter: kmsg dump counter
* @reason: the kmsg dump reason (e.g. oops, panic, etc)
* @data: pointer to log data
*
* This is a sub-header for a kmsg dump, trailing after &psz_buffer.
*/
struct psz_kmsg_header {
#define PSTORE_KMSG_HEADER_MAGIC 0x4dfc3ae5 /* Just a random number */
uint32_t magic;
struct timespec64 time;
bool compressed;
uint32_t counter;
enum kmsg_dump_reason reason;
uint8_t data[];
};
/**
* struct pstore_zone - single stored buffer
*
* @off: zone offset of storage
* @type: front-end type for this zone
* @name: front-end name for this zone
* @buffer: pointer to data buffer managed by this zone
* @oldbuf: pointer to old data buffer
* @buffer_size: bytes in @buffer->data
* @should_recover: whether this zone should recover from storage
* @dirty: whether the data in @buffer dirty
*
* zone structure in memory.
*/
struct pstore_zone {
loff_t off;
const char *name;
enum pstore_type_id type;
struct psz_buffer *buffer;
struct psz_buffer *oldbuf;
size_t buffer_size;
bool should_recover;
atomic_t dirty;
};
/**
* struct psz_context - all about running state of pstore/zone
*
* @kpszs: kmsg dump storage zones
* @ppsz: pmsg storage zone
* @cpsz: console storage zone
* @fpszs: ftrace storage zones
* @kmsg_max_cnt: max count of @kpszs
* @kmsg_read_cnt: counter of total read kmsg dumps
* @kmsg_write_cnt: counter of total kmsg dump writes
* @pmsg_read_cnt: counter of total read pmsg zone
* @console_read_cnt: counter of total read console zone
* @ftrace_max_cnt: max count of @fpszs
* @ftrace_read_cnt: counter of max read ftrace zone
* @oops_counter: counter of oops dumps
* @panic_counter: counter of panic dumps
* @recovered: whether finished recovering data from storage
* @on_panic: whether panic is happening
* @pstore_zone_info_lock: lock to @pstore_zone_info
* @pstore_zone_info: information from backend
* @pstore: structure for pstore
*/
struct psz_context {
struct pstore_zone **kpszs;
struct pstore_zone *ppsz;
struct pstore_zone *cpsz;
struct pstore_zone **fpszs;
unsigned int kmsg_max_cnt;
unsigned int kmsg_read_cnt;
unsigned int kmsg_write_cnt;
unsigned int pmsg_read_cnt;
unsigned int console_read_cnt;
unsigned int ftrace_max_cnt;
unsigned int ftrace_read_cnt;
/*
* These counters should be calculated during recovery.
* It records the oops/panic times after crashes rather than boots.
*/
unsigned int oops_counter;
unsigned int panic_counter;
atomic_t recovered;
atomic_t on_panic;
/*
* pstore_zone_info_lock protects this entire structure during calls
* to register_pstore_zone()/unregister_pstore_zone().
*/
struct mutex pstore_zone_info_lock;
struct pstore_zone_info *pstore_zone_info;
struct pstore_info pstore;
};
static struct psz_context pstore_zone_cxt;
static void psz_flush_all_dirty_zones(struct work_struct *);
static DECLARE_DELAYED_WORK(psz_cleaner, psz_flush_all_dirty_zones);
/**
* enum psz_flush_mode - flush mode for psz_zone_write()
*
* @FLUSH_NONE: do not flush to storage but update data on memory
* @FLUSH_PART: just flush part of data including meta data to storage
* @FLUSH_META: just flush meta data of zone to storage
* @FLUSH_ALL: flush all of zone
*/
enum psz_flush_mode {
FLUSH_NONE = 0,
FLUSH_PART,
FLUSH_META,
FLUSH_ALL,
};
static inline int buffer_datalen(struct pstore_zone *zone)
{
return atomic_read(&zone->buffer->datalen);
}
static inline int buffer_start(struct pstore_zone *zone)
{
return atomic_read(&zone->buffer->start);
}
static inline bool is_on_panic(void)
{
return atomic_read(&pstore_zone_cxt.on_panic);
}
static ssize_t psz_zone_read_buffer(struct pstore_zone *zone, char *buf,
size_t len, unsigned long off)
{
if (!buf || !zone || !zone->buffer)
return -EINVAL;
if (off > zone->buffer_size)
return -EINVAL;
len = min_t(size_t, len, zone->buffer_size - off);
memcpy(buf, zone->buffer->data + off, len);
return len;
}
static int psz_zone_read_oldbuf(struct pstore_zone *zone, char *buf,
size_t len, unsigned long off)
{
if (!buf || !zone || !zone->oldbuf)
return -EINVAL;
if (off > zone->buffer_size)
return -EINVAL;
len = min_t(size_t, len, zone->buffer_size - off);
memcpy(buf, zone->oldbuf->data + off, len);
return 0;
}
static int psz_zone_write(struct pstore_zone *zone,
enum psz_flush_mode flush_mode, const char *buf,
size_t len, unsigned long off)
{
struct pstore_zone_info *info = pstore_zone_cxt.pstore_zone_info;
ssize_t wcnt = 0;
ssize_t (*writeop)(const char *buf, size_t bytes, loff_t pos);
size_t wlen;
if (off > zone->buffer_size)
return -EINVAL;
wlen = min_t(size_t, len, zone->buffer_size - off);
if (buf && wlen) {
memcpy(zone->buffer->data + off, buf, wlen);
atomic_set(&zone->buffer->datalen, wlen + off);
}
/* avoid to damage old records */
if (!is_on_panic() && !atomic_read(&pstore_zone_cxt.recovered))
goto dirty;
writeop = is_on_panic() ? info->panic_write : info->write;
if (!writeop)
goto dirty;
switch (flush_mode) {
case FLUSH_NONE:
if (unlikely(buf && wlen))
goto dirty;
return 0;
case FLUSH_PART:
wcnt = writeop((const char *)zone->buffer->data + off, wlen,
zone->off + sizeof(*zone->buffer) + off);
if (wcnt != wlen)
goto dirty;
fallthrough;
case FLUSH_META:
wlen = sizeof(struct psz_buffer);
wcnt = writeop((const char *)zone->buffer, wlen, zone->off);
if (wcnt != wlen)
goto dirty;
break;
case FLUSH_ALL:
wlen = zone->buffer_size + sizeof(*zone->buffer);
wcnt = writeop((const char *)zone->buffer, wlen, zone->off);
if (wcnt != wlen)
goto dirty;
break;
}
return 0;
dirty:
/* no need to mark dirty if going to try next zone */
if (wcnt == -ENOMSG)
return -ENOMSG;
atomic_set(&zone->dirty, true);
/* flush dirty zones nicely */
if (wcnt == -EBUSY && !is_on_panic())
schedule_delayed_work(&psz_cleaner, msecs_to_jiffies(500));
return -EBUSY;
}
static int psz_flush_dirty_zone(struct pstore_zone *zone)
{
int ret;
if (unlikely(!zone))
return -EINVAL;
if (unlikely(!atomic_read(&pstore_zone_cxt.recovered)))
return -EBUSY;
if (!atomic_xchg(&zone->dirty, false))
return 0;
ret = psz_zone_write(zone, FLUSH_ALL, NULL, 0, 0);
if (ret)
atomic_set(&zone->dirty, true);
return ret;
}
static int psz_flush_dirty_zones(struct pstore_zone **zones, unsigned int cnt)
{
int i, ret;
struct pstore_zone *zone;
if (!zones)
return -EINVAL;
for (i = 0; i < cnt; i++) {
zone = zones[i];
if (!zone)
return -EINVAL;
ret = psz_flush_dirty_zone(zone);
if (ret)
return ret;
}
return 0;
}
static int psz_move_zone(struct pstore_zone *old, struct pstore_zone *new)
{
const char *data = (const char *)old->buffer->data;
int ret;
ret = psz_zone_write(new, FLUSH_ALL, data, buffer_datalen(old), 0);
if (ret) {
atomic_set(&new->buffer->datalen, 0);
atomic_set(&new->dirty, false);
return ret;
}
atomic_set(&old->buffer->datalen, 0);
return 0;
}
static void psz_flush_all_dirty_zones(struct work_struct *work)
{
struct psz_context *cxt = &pstore_zone_cxt;
int ret = 0;
if (cxt->ppsz)
ret |= psz_flush_dirty_zone(cxt->ppsz);
if (cxt->cpsz)
ret |= psz_flush_dirty_zone(cxt->cpsz);
if (cxt->kpszs)
ret |= psz_flush_dirty_zones(cxt->kpszs, cxt->kmsg_max_cnt);
if (cxt->fpszs)
ret |= psz_flush_dirty_zones(cxt->fpszs, cxt->ftrace_max_cnt);
if (ret && cxt->pstore_zone_info)
schedule_delayed_work(&psz_cleaner, msecs_to_jiffies(1000));
}
static int psz_kmsg_recover_data(struct psz_context *cxt)
{
struct pstore_zone_info *info = cxt->pstore_zone_info;
struct pstore_zone *zone = NULL;
struct psz_buffer *buf;
unsigned long i;
ssize_t rcnt;
if (!info->read)
return -EINVAL;
for (i = 0; i < cxt->kmsg_max_cnt; i++) {
zone = cxt->kpszs[i];
if (unlikely(!zone))
return -EINVAL;
if (atomic_read(&zone->dirty)) {
unsigned int wcnt = cxt->kmsg_write_cnt;
struct pstore_zone *new = cxt->kpszs[wcnt];
int ret;
ret = psz_move_zone(zone, new);
if (ret) {
pr_err("move zone from %lu to %d failed\n",
i, wcnt);
return ret;
}
cxt->kmsg_write_cnt = (wcnt + 1) % cxt->kmsg_max_cnt;
}
if (!zone->should_recover)
continue;
buf = zone->buffer;
rcnt = info->read((char *)buf, zone->buffer_size + sizeof(*buf),
zone->off);
if (rcnt != zone->buffer_size + sizeof(*buf))
return rcnt < 0 ? rcnt : -EIO;
}
return 0;
}
static int psz_kmsg_recover_meta(struct psz_context *cxt)
{
struct pstore_zone_info *info = cxt->pstore_zone_info;
struct pstore_zone *zone;
ssize_t rcnt, len;
struct psz_buffer *buf;
struct psz_kmsg_header *hdr;
struct timespec64 time = { };
unsigned long i;
/*
* Recover may on panic, we can't allocate any memory by kmalloc.
* So, we use local array instead.
*/
char buffer_header[sizeof(*buf) + sizeof(*hdr)] = {0};
if (!info->read)
return -EINVAL;
len = sizeof(*buf) + sizeof(*hdr);
buf = (struct psz_buffer *)buffer_header;
for (i = 0; i < cxt->kmsg_max_cnt; i++) {
zone = cxt->kpszs[i];
if (unlikely(!zone))
return -EINVAL;
rcnt = info->read((char *)buf, len, zone->off);
if (rcnt == -ENOMSG) {
pr_debug("%s with id %lu may be broken, skip\n",
zone->name, i);
continue;
} else if (rcnt != len) {
pr_err("read %s with id %lu failed\n", zone->name, i);
return rcnt < 0 ? rcnt : -EIO;
}
if (buf->sig != zone->buffer->sig) {
pr_debug("no valid data in kmsg dump zone %lu\n", i);
continue;
}
if (zone->buffer_size < atomic_read(&buf->datalen)) {
pr_info("found overtop zone: %s: id %lu, off %lld, size %zu\n",
zone->name, i, zone->off,
zone->buffer_size);
continue;
}
hdr = (struct psz_kmsg_header *)buf->data;
if (hdr->magic != PSTORE_KMSG_HEADER_MAGIC) {
pr_info("found invalid zone: %s: id %lu, off %lld, size %zu\n",
zone->name, i, zone->off,
zone->buffer_size);
continue;
}
/*
* we get the newest zone, and the next one must be the oldest
* or unused zone, because we do write one by one like a circle.
*/
if (hdr->time.tv_sec >= time.tv_sec) {
time.tv_sec = hdr->time.tv_sec;
cxt->kmsg_write_cnt = (i + 1) % cxt->kmsg_max_cnt;
}
if (hdr->reason == KMSG_DUMP_OOPS)
cxt->oops_counter =
max(cxt->oops_counter, hdr->counter);
else if (hdr->reason == KMSG_DUMP_PANIC)
cxt->panic_counter =
max(cxt->panic_counter, hdr->counter);
if (!atomic_read(&buf->datalen)) {
pr_debug("found erased zone: %s: id %lu, off %lld, size %zu, datalen %d\n",
zone->name, i, zone->off,
zone->buffer_size,
atomic_read(&buf->datalen));
continue;
}
if (!is_on_panic())
zone->should_recover = true;
pr_debug("found nice zone: %s: id %lu, off %lld, size %zu, datalen %d\n",
zone->name, i, zone->off,
zone->buffer_size, atomic_read(&buf->datalen));
}
return 0;
}
static int psz_kmsg_recover(struct psz_context *cxt)
{
int ret;
if (!cxt->kpszs)
return 0;
ret = psz_kmsg_recover_meta(cxt);
if (ret)
goto recover_fail;
ret = psz_kmsg_recover_data(cxt);
if (ret)
goto recover_fail;
return 0;
recover_fail:
pr_debug("psz_recover_kmsg failed\n");
return ret;
}
static int psz_recover_zone(struct psz_context *cxt, struct pstore_zone *zone)
{
struct pstore_zone_info *info = cxt->pstore_zone_info;
struct psz_buffer *oldbuf, tmpbuf;
int ret = 0;
char *buf;
ssize_t rcnt, len, start, off;
if (!zone || zone->oldbuf)
return 0;
if (is_on_panic()) {
/* save data as much as possible */
psz_flush_dirty_zone(zone);
return 0;
}
if (unlikely(!info->read))
return -EINVAL;
len = sizeof(struct psz_buffer);
rcnt = info->read((char *)&tmpbuf, len, zone->off);
if (rcnt != len) {
pr_debug("read zone %s failed\n", zone->name);
return rcnt < 0 ? rcnt : -EIO;
}
if (tmpbuf.sig != zone->buffer->sig) {
pr_debug("no valid data in zone %s\n", zone->name);
return 0;
}
if (zone->buffer_size < atomic_read(&tmpbuf.datalen) ||
zone->buffer_size < atomic_read(&tmpbuf.start)) {
pr_info("found overtop zone: %s: off %lld, size %zu\n",
zone->name, zone->off, zone->buffer_size);
/* just keep going */
return 0;
}
if (!atomic_read(&tmpbuf.datalen)) {
pr_debug("found erased zone: %s: off %lld, size %zu, datalen %d\n",
zone->name, zone->off, zone->buffer_size,
atomic_read(&tmpbuf.datalen));
return 0;
}
pr_debug("found nice zone: %s: off %lld, size %zu, datalen %d\n",
zone->name, zone->off, zone->buffer_size,
atomic_read(&tmpbuf.datalen));
len = atomic_read(&tmpbuf.datalen) + sizeof(*oldbuf);
oldbuf = kzalloc(len, GFP_KERNEL);
if (!oldbuf)
return -ENOMEM;
memcpy(oldbuf, &tmpbuf, sizeof(*oldbuf));
buf = (char *)oldbuf + sizeof(*oldbuf);
len = atomic_read(&oldbuf->datalen);
start = atomic_read(&oldbuf->start);
off = zone->off + sizeof(*oldbuf);
/* get part of data */
rcnt = info->read(buf, len - start, off + start);
if (rcnt != len - start) {
pr_err("read zone %s failed\n", zone->name);
ret = rcnt < 0 ? rcnt : -EIO;
goto free_oldbuf;
}
/* get the rest of data */
rcnt = info->read(buf + len - start, start, off);
if (rcnt != start) {
pr_err("read zone %s failed\n", zone->name);
ret = rcnt < 0 ? rcnt : -EIO;
goto free_oldbuf;
}
zone->oldbuf = oldbuf;
psz_flush_dirty_zone(zone);
return 0;
free_oldbuf:
kfree(oldbuf);
return ret;
}
static int psz_recover_zones(struct psz_context *cxt,
struct pstore_zone **zones, unsigned int cnt)
{
int ret;
unsigned int i;
struct pstore_zone *zone;
if (!zones)
return 0;
for (i = 0; i < cnt; i++) {
zone = zones[i];
if (unlikely(!zone))
continue;
ret = psz_recover_zone(cxt, zone);
if (ret)
goto recover_fail;
}
return 0;
recover_fail:
pr_debug("recover %s[%u] failed\n", zone->name, i);
return ret;
}
/**
* psz_recovery() - recover data from storage
* @cxt: the context of pstore/zone
*
* recovery means reading data back from storage after rebooting
*
* Return: 0 on success, others on failure.
*/
static inline int psz_recovery(struct psz_context *cxt)
{
int ret;
if (atomic_read(&cxt->recovered))
return 0;
ret = psz_kmsg_recover(cxt);
if (ret)
goto out;
ret = psz_recover_zone(cxt, cxt->ppsz);
if (ret)
goto out;
ret = psz_recover_zone(cxt, cxt->cpsz);
if (ret)
goto out;
ret = psz_recover_zones(cxt, cxt->fpszs, cxt->ftrace_max_cnt);
out:
if (unlikely(ret))
pr_err("recover failed\n");
else {
pr_debug("recover end!\n");
atomic_set(&cxt->recovered, 1);
}
return ret;
}
static int psz_pstore_open(struct pstore_info *psi)
{
struct psz_context *cxt = psi->data;
cxt->kmsg_read_cnt = 0;
cxt->pmsg_read_cnt = 0;
cxt->console_read_cnt = 0;
cxt->ftrace_read_cnt = 0;
return 0;
}
static inline bool psz_old_ok(struct pstore_zone *zone)
{
if (zone && zone->oldbuf && atomic_read(&zone->oldbuf->datalen))
return true;
return false;
}
static inline bool psz_ok(struct pstore_zone *zone)
{
if (zone && zone->buffer && buffer_datalen(zone))
return true;
return false;
}
static inline int psz_kmsg_erase(struct psz_context *cxt,
struct pstore_zone *zone, struct pstore_record *record)
{
struct psz_buffer *buffer = zone->buffer;
struct psz_kmsg_header *hdr =
(struct psz_kmsg_header *)buffer->data;
size_t size;
if (unlikely(!psz_ok(zone)))
return 0;
/* this zone is already updated, no need to erase */
if (record->count != hdr->counter)
return 0;
size = buffer_datalen(zone) + sizeof(*zone->buffer);
atomic_set(&zone->buffer->datalen, 0);
if (cxt->pstore_zone_info->erase)
return cxt->pstore_zone_info->erase(size, zone->off);
else
return psz_zone_write(zone, FLUSH_META, NULL, 0, 0);
}
static inline int psz_record_erase(struct psz_context *cxt,
struct pstore_zone *zone)
{
if (unlikely(!psz_old_ok(zone)))
return 0;
kfree(zone->oldbuf);
zone->oldbuf = NULL;
/*
* if there are new data in zone buffer, that means the old data
* are already invalid. It is no need to flush 0 (erase) to
* block device.
*/
if (!buffer_datalen(zone))
return psz_zone_write(zone, FLUSH_META, NULL, 0, 0);
psz_flush_dirty_zone(zone);
return 0;
}
static int psz_pstore_erase(struct pstore_record *record)
{
struct psz_context *cxt = record->psi->data;
switch (record->type) {
case PSTORE_TYPE_DMESG:
if (record->id >= cxt->kmsg_max_cnt)
return -EINVAL;
return psz_kmsg_erase(cxt, cxt->kpszs[record->id], record);
case PSTORE_TYPE_PMSG:
return psz_record_erase(cxt, cxt->ppsz);
case PSTORE_TYPE_CONSOLE:
return psz_record_erase(cxt, cxt->cpsz);
case PSTORE_TYPE_FTRACE:
if (record->id >= cxt->ftrace_max_cnt)
return -EINVAL;
return psz_record_erase(cxt, cxt->fpszs[record->id]);
default: return -EINVAL;
}
}
static void psz_write_kmsg_hdr(struct pstore_zone *zone,
struct pstore_record *record)
{
struct psz_context *cxt = record->psi->data;
struct psz_buffer *buffer = zone->buffer;
struct psz_kmsg_header *hdr =
(struct psz_kmsg_header *)buffer->data;
hdr->magic = PSTORE_KMSG_HEADER_MAGIC;
hdr->compressed = record->compressed;
hdr->time.tv_sec = record->time.tv_sec;
hdr->time.tv_nsec = record->time.tv_nsec;
hdr->reason = record->reason;
if (hdr->reason == KMSG_DUMP_OOPS)
hdr->counter = ++cxt->oops_counter;
else if (hdr->reason == KMSG_DUMP_PANIC)
hdr->counter = ++cxt->panic_counter;
else
hdr->counter = 0;
}
/*
* In case zone is broken, which may occur to MTD device, we try each zones,
* start at cxt->kmsg_write_cnt.
*/
static inline int notrace psz_kmsg_write_record(struct psz_context *cxt,
struct pstore_record *record)
{
size_t size, hlen;
struct pstore_zone *zone;
unsigned int i;
for (i = 0; i < cxt->kmsg_max_cnt; i++) {
unsigned int zonenum, len;
int ret;
zonenum = (cxt->kmsg_write_cnt + i) % cxt->kmsg_max_cnt;
zone = cxt->kpszs[zonenum];
if (unlikely(!zone))
return -ENOSPC;
/* avoid destroying old data, allocate a new one */
len = zone->buffer_size + sizeof(*zone->buffer);
zone->oldbuf = zone->buffer;
zone->buffer = kzalloc(len, GFP_ATOMIC);
if (!zone->buffer) {
zone->buffer = zone->oldbuf;
return -ENOMEM;
}
zone->buffer->sig = zone->oldbuf->sig;
pr_debug("write %s to zone id %d\n", zone->name, zonenum);
psz_write_kmsg_hdr(zone, record);
hlen = sizeof(struct psz_kmsg_header);
size = min_t(size_t, record->size, zone->buffer_size - hlen);
ret = psz_zone_write(zone, FLUSH_ALL, record->buf, size, hlen);
if (likely(!ret || ret != -ENOMSG)) {
cxt->kmsg_write_cnt = zonenum + 1;
cxt->kmsg_write_cnt %= cxt->kmsg_max_cnt;
/* no need to try next zone, free last zone buffer */
kfree(zone->oldbuf);
zone->oldbuf = NULL;
return ret;
}
pr_debug("zone %u may be broken, try next dmesg zone\n",
zonenum);
kfree(zone->buffer);
zone->buffer = zone->oldbuf;
zone->oldbuf = NULL;
}
return -EBUSY;
}
static int notrace psz_kmsg_write(struct psz_context *cxt,
struct pstore_record *record)
{
int ret;
/*
* Explicitly only take the first part of any new crash.
* If our buffer is larger than kmsg_bytes, this can never happen,
* and if our buffer is smaller than kmsg_bytes, we don't want the
* report split across multiple records.
*/
if (record->part != 1)
return -ENOSPC;
if (!cxt->kpszs)
return -ENOSPC;
ret = psz_kmsg_write_record(cxt, record);
if (!ret && is_on_panic()) {
/* ensure all data are flushed to storage when panic */
pr_debug("try to flush other dirty zones\n");
psz_flush_all_dirty_zones(NULL);
}
/* always return 0 as we had handled it on buffer */
return 0;
}
static int notrace psz_record_write(struct pstore_zone *zone,
struct pstore_record *record)
{
size_t start, rem;
bool is_full_data = false;
char *buf;
int cnt;
if (!zone || !record)
return -ENOSPC;
if (atomic_read(&zone->buffer->datalen) >= zone->buffer_size)
is_full_data = true;
cnt = record->size;
buf = record->buf;
if (unlikely(cnt > zone->buffer_size)) {
buf += cnt - zone->buffer_size;
cnt = zone->buffer_size;
}
start = buffer_start(zone);
rem = zone->buffer_size - start;
if (unlikely(rem < cnt)) {
psz_zone_write(zone, FLUSH_PART, buf, rem, start);
buf += rem;
cnt -= rem;
start = 0;
is_full_data = true;
}
atomic_set(&zone->buffer->start, cnt + start);
psz_zone_write(zone, FLUSH_PART, buf, cnt, start);
/**
* psz_zone_write will set datalen as start + cnt.
* It work if actual data length lesser than buffer size.
* If data length greater than buffer size, pmsg will rewrite to
* beginning of zone, which make buffer->datalen wrongly.
* So we should reset datalen as buffer size once actual data length
* greater than buffer size.
*/
if (is_full_data) {
atomic_set(&zone->buffer->datalen, zone->buffer_size);
psz_zone_write(zone, FLUSH_META, NULL, 0, 0);
}
return 0;
}
static int notrace psz_pstore_write(struct pstore_record *record)
{
struct psz_context *cxt = record->psi->data;
if (record->type == PSTORE_TYPE_DMESG &&
record->reason == KMSG_DUMP_PANIC)
atomic_set(&cxt->on_panic, 1);
/*
* if on panic, do not write except panic records
* Fix case that panic_write prints log which wakes up console backend.
*/
if (is_on_panic() && record->type != PSTORE_TYPE_DMESG)
return -EBUSY;
switch (record->type) {
case PSTORE_TYPE_DMESG:
return psz_kmsg_write(cxt, record);
case PSTORE_TYPE_CONSOLE:
return psz_record_write(cxt->cpsz, record);
case PSTORE_TYPE_PMSG:
return psz_record_write(cxt->ppsz, record);
case PSTORE_TYPE_FTRACE: {
int zonenum = smp_processor_id();
if (!cxt->fpszs)
return -ENOSPC;
return psz_record_write(cxt->fpszs[zonenum], record);
}
default:
return -EINVAL;
}
}
static struct pstore_zone *psz_read_next_zone(struct psz_context *cxt)
{
struct pstore_zone *zone = NULL;
while (cxt->kmsg_read_cnt < cxt->kmsg_max_cnt) {
zone = cxt->kpszs[cxt->kmsg_read_cnt++];
if (psz_ok(zone))
return zone;
}
if (cxt->ftrace_read_cnt < cxt->ftrace_max_cnt)
/*
* No need psz_old_ok(). Let psz_ftrace_read() do so for
* combination. psz_ftrace_read() should traverse over
* all zones in case of some zone without data.
*/
return cxt->fpszs[cxt->ftrace_read_cnt++];
if (cxt->pmsg_read_cnt == 0) {
cxt->pmsg_read_cnt++;
zone = cxt->ppsz;
if (psz_old_ok(zone))
return zone;
}
if (cxt->console_read_cnt == 0) {
cxt->console_read_cnt++;
zone = cxt->cpsz;
if (psz_old_ok(zone))
return zone;
}
return NULL;
}
static int psz_kmsg_read_hdr(struct pstore_zone *zone,
struct pstore_record *record)
{
struct psz_buffer *buffer = zone->buffer;
struct psz_kmsg_header *hdr =
(struct psz_kmsg_header *)buffer->data;
if (hdr->magic != PSTORE_KMSG_HEADER_MAGIC)
return -EINVAL;
record->compressed = hdr->compressed;
record->time.tv_sec = hdr->time.tv_sec;
record->time.tv_nsec = hdr->time.tv_nsec;
record->reason = hdr->reason;
record->count = hdr->counter;
return 0;
}
static ssize_t psz_kmsg_read(struct pstore_zone *zone,
struct pstore_record *record)
{
ssize_t size, hlen = 0;
size = buffer_datalen(zone);
/* Clear and skip this kmsg dump record if it has no valid header */
if (psz_kmsg_read_hdr(zone, record)) {
atomic_set(&zone->buffer->datalen, 0);
atomic_set(&zone->dirty, 0);
return -ENOMSG;
}
size -= sizeof(struct psz_kmsg_header);
if (!record->compressed) {
char *buf = kasprintf(GFP_KERNEL, "%s: Total %d times\n",
kmsg_dump_reason_str(record->reason),
record->count);
hlen = strlen(buf);
record->buf = krealloc(buf, hlen + size, GFP_KERNEL);
if (!record->buf) {
kfree(buf);
return -ENOMEM;
}
} else {
record->buf = kmalloc(size, GFP_KERNEL);
if (!record->buf)
return -ENOMEM;
}
size = psz_zone_read_buffer(zone, record->buf + hlen, size,
sizeof(struct psz_kmsg_header));
if (unlikely(size < 0)) {
kfree(record->buf);
return -ENOMSG;
}
return size + hlen;
}
/* try to combine all ftrace zones */
static ssize_t psz_ftrace_read(struct pstore_zone *zone,
struct pstore_record *record)
{
struct psz_context *cxt;
struct psz_buffer *buf;
int ret;
if (!zone || !record)
return -ENOSPC;
if (!psz_old_ok(zone))
goto out;
buf = (struct psz_buffer *)zone->oldbuf;
if (!buf)
return -ENOMSG;
ret = pstore_ftrace_combine_log(&record->buf, &record->size,
(char *)buf->data, atomic_read(&buf->datalen));
if (unlikely(ret))
return ret;
out:
cxt = record->psi->data;
if (cxt->ftrace_read_cnt < cxt->ftrace_max_cnt)
/* then, read next ftrace zone */
return -ENOMSG;
record->id = 0;
return record->size ? record->size : -ENOMSG;
}
static ssize_t psz_record_read(struct pstore_zone *zone,
struct pstore_record *record)
{
size_t len;
struct psz_buffer *buf;
if (!zone || !record)
return -ENOSPC;
buf = (struct psz_buffer *)zone->oldbuf;
if (!buf)
return -ENOMSG;
len = atomic_read(&buf->datalen);
record->buf = kmalloc(len, GFP_KERNEL);
if (!record->buf)
return -ENOMEM;
if (unlikely(psz_zone_read_oldbuf(zone, record->buf, len, 0))) {
kfree(record->buf);
return -ENOMSG;
}
return len;
}
static ssize_t psz_pstore_read(struct pstore_record *record)
{
struct psz_context *cxt = record->psi->data;
ssize_t (*readop)(struct pstore_zone *zone,
struct pstore_record *record);
struct pstore_zone *zone;
ssize_t ret;
/* before read, we must recover from storage */
ret = psz_recovery(cxt);
if (ret)
return ret;
next_zone:
zone = psz_read_next_zone(cxt);
if (!zone)
return 0;
record->type = zone->type;
switch (record->type) {
case PSTORE_TYPE_DMESG:
readop = psz_kmsg_read;
record->id = cxt->kmsg_read_cnt - 1;
break;
case PSTORE_TYPE_FTRACE:
readop = psz_ftrace_read;
break;
case PSTORE_TYPE_CONSOLE:
case PSTORE_TYPE_PMSG:
readop = psz_record_read;
break;
default:
goto next_zone;
}
ret = readop(zone, record);
if (ret == -ENOMSG)
goto next_zone;
return ret;
}
static struct psz_context pstore_zone_cxt = {
.pstore_zone_info_lock =
__MUTEX_INITIALIZER(pstore_zone_cxt.pstore_zone_info_lock),
.recovered = ATOMIC_INIT(0),
.on_panic = ATOMIC_INIT(0),
.pstore = {
.owner = THIS_MODULE,
.open = psz_pstore_open,
.read = psz_pstore_read,
.write = psz_pstore_write,
.erase = psz_pstore_erase,
},
};
static void psz_free_zone(struct pstore_zone **pszone)
{
struct pstore_zone *zone = *pszone;
if (!zone)
return;
kfree(zone->buffer);
kfree(zone);
*pszone = NULL;
}
static void psz_free_zones(struct pstore_zone ***pszones, unsigned int *cnt)
{
struct pstore_zone **zones = *pszones;
if (!zones)
return;
while (*cnt > 0) {
(*cnt)--;
psz_free_zone(&(zones[*cnt]));
}
kfree(zones);
*pszones = NULL;
}
static void psz_free_all_zones(struct psz_context *cxt)
{
if (cxt->kpszs)
psz_free_zones(&cxt->kpszs, &cxt->kmsg_max_cnt);
if (cxt->ppsz)
psz_free_zone(&cxt->ppsz);
if (cxt->cpsz)
psz_free_zone(&cxt->cpsz);
if (cxt->fpszs)
psz_free_zones(&cxt->fpszs, &cxt->ftrace_max_cnt);
}
static struct pstore_zone *psz_init_zone(enum pstore_type_id type,
loff_t *off, size_t size)
{
struct pstore_zone_info *info = pstore_zone_cxt.pstore_zone_info;
struct pstore_zone *zone;
const char *name = pstore_type_to_name(type);
if (!size)
return NULL;
if (*off + size > info->total_size) {
pr_err("no room for %s (0x%zx@0x%llx over 0x%lx)\n",
name, size, *off, info->total_size);
return ERR_PTR(-ENOMEM);
}
zone = kzalloc(sizeof(struct pstore_zone), GFP_KERNEL);
if (!zone)
return ERR_PTR(-ENOMEM);
zone->buffer = kmalloc(size, GFP_KERNEL);
if (!zone->buffer) {
kfree(zone);
return ERR_PTR(-ENOMEM);
}
memset(zone->buffer, 0xFF, size);
zone->off = *off;
zone->name = name;
zone->type = type;
zone->buffer_size = size - sizeof(struct psz_buffer);
zone->buffer->sig = type ^ PSZ_SIG;
zone->oldbuf = NULL;
atomic_set(&zone->dirty, 0);
atomic_set(&zone->buffer->datalen, 0);
atomic_set(&zone->buffer->start, 0);
*off += size;
pr_debug("pszone %s: off 0x%llx, %zu header, %zu data\n", zone->name,
zone->off, sizeof(*zone->buffer), zone->buffer_size);
return zone;
}
static struct pstore_zone **psz_init_zones(enum pstore_type_id type,
loff_t *off, size_t total_size, ssize_t record_size,
unsigned int *cnt)
{
struct pstore_zone_info *info = pstore_zone_cxt.pstore_zone_info;
struct pstore_zone **zones, *zone;
const char *name = pstore_type_to_name(type);
int c, i;
*cnt = 0;
if (!total_size || !record_size)
return NULL;
if (*off + total_size > info->total_size) {
pr_err("no room for zones %s (0x%zx@0x%llx over 0x%lx)\n",
name, total_size, *off, info->total_size);
return ERR_PTR(-ENOMEM);
}
c = total_size / record_size;
zones = kcalloc(c, sizeof(*zones), GFP_KERNEL);
if (!zones) {
pr_err("allocate for zones %s failed\n", name);
return ERR_PTR(-ENOMEM);
}
memset(zones, 0, c * sizeof(*zones));
for (i = 0; i < c; i++) {
zone = psz_init_zone(type, off, record_size);
if (!zone || IS_ERR(zone)) {
pr_err("initialize zones %s failed\n", name);
psz_free_zones(&zones, &i);
return (void *)zone;
}
zones[i] = zone;
}
*cnt = c;
return zones;
}
static int psz_alloc_zones(struct psz_context *cxt)
{
struct pstore_zone_info *info = cxt->pstore_zone_info;
loff_t off = 0;
int err;
size_t off_size = 0;
off_size += info->pmsg_size;
cxt->ppsz = psz_init_zone(PSTORE_TYPE_PMSG, &off, info->pmsg_size);
if (IS_ERR(cxt->ppsz)) {
err = PTR_ERR(cxt->ppsz);
cxt->ppsz = NULL;
goto free_out;
}
off_size += info->console_size;
cxt->cpsz = psz_init_zone(PSTORE_TYPE_CONSOLE, &off,
info->console_size);
if (IS_ERR(cxt->cpsz)) {
err = PTR_ERR(cxt->cpsz);
cxt->cpsz = NULL;
goto free_out;
}
off_size += info->ftrace_size;
cxt->fpszs = psz_init_zones(PSTORE_TYPE_FTRACE, &off,
info->ftrace_size,
info->ftrace_size / nr_cpu_ids,
&cxt->ftrace_max_cnt);
if (IS_ERR(cxt->fpszs)) {
err = PTR_ERR(cxt->fpszs);
cxt->fpszs = NULL;
goto free_out;
}
cxt->kpszs = psz_init_zones(PSTORE_TYPE_DMESG, &off,
info->total_size - off_size,
info->kmsg_size, &cxt->kmsg_max_cnt);
if (IS_ERR(cxt->kpszs)) {
err = PTR_ERR(cxt->kpszs);
cxt->kpszs = NULL;
goto free_out;
}
return 0;
free_out:
psz_free_all_zones(cxt);
return err;
}
/**
* register_pstore_zone() - register to pstore/zone
*
* @info: back-end driver information. See &struct pstore_zone_info.
*
* Only one back-end at one time.
*
* Return: 0 on success, others on failure.
*/
int register_pstore_zone(struct pstore_zone_info *info)
{
int err = -EINVAL;
struct psz_context *cxt = &pstore_zone_cxt;
if (info->total_size < 4096) {
pr_warn("total_size must be >= 4096\n");
return -EINVAL;
}
if (info->total_size > SZ_128M) {
pr_warn("capping size to 128MiB\n");
info->total_size = SZ_128M;
}
if (!info->kmsg_size && !info->pmsg_size && !info->console_size &&
!info->ftrace_size) {
pr_warn("at least one record size must be non-zero\n");
return -EINVAL;
}
if (!info->name || !info->name[0])
return -EINVAL;
#define check_size(name, size) { \
if (info->name > 0 && info->name < (size)) { \
pr_err(#name " must be over %d\n", (size)); \
return -EINVAL; \
} \
if (info->name & (size - 1)) { \
pr_err(#name " must be a multiple of %d\n", \
(size)); \
return -EINVAL; \
} \
}
check_size(total_size, 4096);
check_size(kmsg_size, SECTOR_SIZE);
check_size(pmsg_size, SECTOR_SIZE);
check_size(console_size, SECTOR_SIZE);
check_size(ftrace_size, SECTOR_SIZE);
#undef check_size
/*
* the @read and @write must be applied.
* if no @read, pstore may mount failed.
* if no @write, pstore do not support to remove record file.
*/
if (!info->read || !info->write) {
pr_err("no valid general read/write interface\n");
return -EINVAL;
}
mutex_lock(&cxt->pstore_zone_info_lock);
if (cxt->pstore_zone_info) {
pr_warn("'%s' already loaded: ignoring '%s'\n",
cxt->pstore_zone_info->name, info->name);
mutex_unlock(&cxt->pstore_zone_info_lock);
return -EBUSY;
}
cxt->pstore_zone_info = info;
pr_debug("register %s with properties:\n", info->name);
pr_debug("\ttotal size : %ld Bytes\n", info->total_size);
pr_debug("\tkmsg size : %ld Bytes\n", info->kmsg_size);
pr_debug("\tpmsg size : %ld Bytes\n", info->pmsg_size);
pr_debug("\tconsole size : %ld Bytes\n", info->console_size);
pr_debug("\tftrace size : %ld Bytes\n", info->ftrace_size);
err = psz_alloc_zones(cxt);
if (err) {
pr_err("alloc zones failed\n");
goto fail_out;
}
if (info->kmsg_size) {
cxt->pstore.bufsize = cxt->kpszs[0]->buffer_size -
sizeof(struct psz_kmsg_header);
cxt->pstore.buf = kzalloc(cxt->pstore.bufsize, GFP_KERNEL);
if (!cxt->pstore.buf) {
err = -ENOMEM;
goto fail_free;
}
}
cxt->pstore.data = cxt;
pr_info("registered %s as backend for", info->name);
cxt->pstore.max_reason = info->max_reason;
cxt->pstore.name = info->name;
if (info->kmsg_size) {
cxt->pstore.flags |= PSTORE_FLAGS_DMESG;
pr_cont(" kmsg(%s",
kmsg_dump_reason_str(cxt->pstore.max_reason));
if (cxt->pstore_zone_info->panic_write)
pr_cont(",panic_write");
pr_cont(")");
}
if (info->pmsg_size) {
cxt->pstore.flags |= PSTORE_FLAGS_PMSG;
pr_cont(" pmsg");
}
if (info->console_size) {
cxt->pstore.flags |= PSTORE_FLAGS_CONSOLE;
pr_cont(" console");
}
if (info->ftrace_size) {
cxt->pstore.flags |= PSTORE_FLAGS_FTRACE;
pr_cont(" ftrace");
}
pr_cont("\n");
err = pstore_register(&cxt->pstore);
if (err) {
pr_err("registering with pstore failed\n");
goto fail_free;
}
mutex_unlock(&pstore_zone_cxt.pstore_zone_info_lock);
return 0;
fail_free:
kfree(cxt->pstore.buf);
cxt->pstore.buf = NULL;
cxt->pstore.bufsize = 0;
psz_free_all_zones(cxt);
fail_out:
pstore_zone_cxt.pstore_zone_info = NULL;
mutex_unlock(&pstore_zone_cxt.pstore_zone_info_lock);
return err;
}
EXPORT_SYMBOL_GPL(register_pstore_zone);
/**
* unregister_pstore_zone() - unregister to pstore/zone
*
* @info: back-end driver information. See struct pstore_zone_info.
*/
void unregister_pstore_zone(struct pstore_zone_info *info)
{
struct psz_context *cxt = &pstore_zone_cxt;
mutex_lock(&cxt->pstore_zone_info_lock);
if (!cxt->pstore_zone_info) {
mutex_unlock(&cxt->pstore_zone_info_lock);
return;
}
/* Stop incoming writes from pstore. */
pstore_unregister(&cxt->pstore);
/* Flush any pending writes. */
psz_flush_all_dirty_zones(NULL);
flush_delayed_work(&psz_cleaner);
/* Clean up allocations. */
kfree(cxt->pstore.buf);
cxt->pstore.buf = NULL;
cxt->pstore.bufsize = 0;
cxt->pstore_zone_info = NULL;
psz_free_all_zones(cxt);
/* Clear counters and zone state. */
cxt->oops_counter = 0;
cxt->panic_counter = 0;
atomic_set(&cxt->recovered, 0);
atomic_set(&cxt->on_panic, 0);
mutex_unlock(&cxt->pstore_zone_info_lock);
}
EXPORT_SYMBOL_GPL(unregister_pstore_zone);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("WeiXiong Liao <[email protected]>");
MODULE_AUTHOR("Kees Cook <[email protected]>");
MODULE_DESCRIPTION("Storage Manager for pstore/blk");
| linux-master | fs/pstore/zone.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Persistent Storage - ramfs parts.
*
* Copyright (C) 2010 Intel Corporation <[email protected]>
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/fsnotify.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/string.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/ramfs.h>
#include <linux/parser.h>
#include <linux/sched.h>
#include <linux/magic.h>
#include <linux/pstore.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include "internal.h"
#define PSTORE_NAMELEN 64
static DEFINE_MUTEX(records_list_lock);
static LIST_HEAD(records_list);
static DEFINE_MUTEX(pstore_sb_lock);
static struct super_block *pstore_sb;
struct pstore_private {
struct list_head list;
struct dentry *dentry;
struct pstore_record *record;
size_t total_size;
};
struct pstore_ftrace_seq_data {
const void *ptr;
size_t off;
size_t size;
};
#define REC_SIZE sizeof(struct pstore_ftrace_record)
static void free_pstore_private(struct pstore_private *private)
{
if (!private)
return;
if (private->record) {
kvfree(private->record->buf);
kfree(private->record->priv);
kfree(private->record);
}
kfree(private);
}
static void *pstore_ftrace_seq_start(struct seq_file *s, loff_t *pos)
{
struct pstore_private *ps = s->private;
struct pstore_ftrace_seq_data *data;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return NULL;
data->off = ps->total_size % REC_SIZE;
data->off += *pos * REC_SIZE;
if (data->off + REC_SIZE > ps->total_size) {
kfree(data);
return NULL;
}
return data;
}
static void pstore_ftrace_seq_stop(struct seq_file *s, void *v)
{
kfree(v);
}
static void *pstore_ftrace_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
struct pstore_private *ps = s->private;
struct pstore_ftrace_seq_data *data = v;
(*pos)++;
data->off += REC_SIZE;
if (data->off + REC_SIZE > ps->total_size)
return NULL;
return data;
}
static int pstore_ftrace_seq_show(struct seq_file *s, void *v)
{
struct pstore_private *ps = s->private;
struct pstore_ftrace_seq_data *data = v;
struct pstore_ftrace_record *rec;
if (!data)
return 0;
rec = (struct pstore_ftrace_record *)(ps->record->buf + data->off);
seq_printf(s, "CPU:%d ts:%llu %08lx %08lx %ps <- %pS\n",
pstore_ftrace_decode_cpu(rec),
pstore_ftrace_read_timestamp(rec),
rec->ip, rec->parent_ip, (void *)rec->ip,
(void *)rec->parent_ip);
return 0;
}
static const struct seq_operations pstore_ftrace_seq_ops = {
.start = pstore_ftrace_seq_start,
.next = pstore_ftrace_seq_next,
.stop = pstore_ftrace_seq_stop,
.show = pstore_ftrace_seq_show,
};
static ssize_t pstore_file_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct seq_file *sf = file->private_data;
struct pstore_private *ps = sf->private;
if (ps->record->type == PSTORE_TYPE_FTRACE)
return seq_read(file, userbuf, count, ppos);
return simple_read_from_buffer(userbuf, count, ppos,
ps->record->buf, ps->total_size);
}
static int pstore_file_open(struct inode *inode, struct file *file)
{
struct pstore_private *ps = inode->i_private;
struct seq_file *sf;
int err;
const struct seq_operations *sops = NULL;
if (ps->record->type == PSTORE_TYPE_FTRACE)
sops = &pstore_ftrace_seq_ops;
err = seq_open(file, sops);
if (err < 0)
return err;
sf = file->private_data;
sf->private = ps;
return 0;
}
static loff_t pstore_file_llseek(struct file *file, loff_t off, int whence)
{
struct seq_file *sf = file->private_data;
if (sf->op)
return seq_lseek(file, off, whence);
return default_llseek(file, off, whence);
}
static const struct file_operations pstore_file_operations = {
.open = pstore_file_open,
.read = pstore_file_read,
.llseek = pstore_file_llseek,
.release = seq_release,
};
/*
* When a file is unlinked from our file system we call the
* platform driver to erase the record from persistent store.
*/
static int pstore_unlink(struct inode *dir, struct dentry *dentry)
{
struct pstore_private *p = d_inode(dentry)->i_private;
struct pstore_record *record = p->record;
int rc = 0;
if (!record->psi->erase)
return -EPERM;
/* Make sure we can't race while removing this file. */
mutex_lock(&records_list_lock);
if (!list_empty(&p->list))
list_del_init(&p->list);
else
rc = -ENOENT;
p->dentry = NULL;
mutex_unlock(&records_list_lock);
if (rc)
return rc;
mutex_lock(&record->psi->read_mutex);
record->psi->erase(record);
mutex_unlock(&record->psi->read_mutex);
return simple_unlink(dir, dentry);
}
static void pstore_evict_inode(struct inode *inode)
{
struct pstore_private *p = inode->i_private;
clear_inode(inode);
free_pstore_private(p);
}
static const struct inode_operations pstore_dir_inode_operations = {
.lookup = simple_lookup,
.unlink = pstore_unlink,
};
static struct inode *pstore_get_inode(struct super_block *sb)
{
struct inode *inode = new_inode(sb);
if (inode) {
inode->i_ino = get_next_ino();
inode->i_atime = inode->i_mtime = inode_set_ctime_current(inode);
}
return inode;
}
enum {
Opt_kmsg_bytes, Opt_err
};
static const match_table_t tokens = {
{Opt_kmsg_bytes, "kmsg_bytes=%u"},
{Opt_err, NULL}
};
static void parse_options(char *options)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int option;
if (!options)
return;
while ((p = strsep(&options, ",")) != NULL) {
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_kmsg_bytes:
if (!match_int(&args[0], &option))
pstore_set_kmsg_bytes(option);
break;
}
}
}
/*
* Display the mount options in /proc/mounts.
*/
static int pstore_show_options(struct seq_file *m, struct dentry *root)
{
if (kmsg_bytes != CONFIG_PSTORE_DEFAULT_KMSG_BYTES)
seq_printf(m, ",kmsg_bytes=%lu", kmsg_bytes);
return 0;
}
static int pstore_remount(struct super_block *sb, int *flags, char *data)
{
sync_filesystem(sb);
parse_options(data);
return 0;
}
static const struct super_operations pstore_ops = {
.statfs = simple_statfs,
.drop_inode = generic_delete_inode,
.evict_inode = pstore_evict_inode,
.remount_fs = pstore_remount,
.show_options = pstore_show_options,
};
static struct dentry *psinfo_lock_root(void)
{
struct dentry *root;
mutex_lock(&pstore_sb_lock);
/*
* Having no backend is fine -- no records appear.
* Not being mounted is fine -- nothing to do.
*/
if (!psinfo || !pstore_sb) {
mutex_unlock(&pstore_sb_lock);
return NULL;
}
root = pstore_sb->s_root;
inode_lock(d_inode(root));
mutex_unlock(&pstore_sb_lock);
return root;
}
int pstore_put_backend_records(struct pstore_info *psi)
{
struct pstore_private *pos, *tmp;
struct dentry *root;
int rc = 0;
root = psinfo_lock_root();
if (!root)
return 0;
mutex_lock(&records_list_lock);
list_for_each_entry_safe(pos, tmp, &records_list, list) {
if (pos->record->psi == psi) {
list_del_init(&pos->list);
rc = simple_unlink(d_inode(root), pos->dentry);
if (WARN_ON(rc))
break;
d_drop(pos->dentry);
dput(pos->dentry);
pos->dentry = NULL;
}
}
mutex_unlock(&records_list_lock);
inode_unlock(d_inode(root));
return rc;
}
/*
* Make a regular file in the root directory of our file system.
* Load it up with "size" bytes of data from "buf".
* Set the mtime & ctime to the date that this record was originally stored.
*/
int pstore_mkfile(struct dentry *root, struct pstore_record *record)
{
struct dentry *dentry;
struct inode *inode;
int rc = 0;
char name[PSTORE_NAMELEN];
struct pstore_private *private, *pos;
size_t size = record->size + record->ecc_notice_size;
if (WARN_ON(!inode_is_locked(d_inode(root))))
return -EINVAL;
rc = -EEXIST;
/* Skip records that are already present in the filesystem. */
mutex_lock(&records_list_lock);
list_for_each_entry(pos, &records_list, list) {
if (pos->record->type == record->type &&
pos->record->id == record->id &&
pos->record->psi == record->psi)
goto fail;
}
rc = -ENOMEM;
inode = pstore_get_inode(root->d_sb);
if (!inode)
goto fail;
inode->i_mode = S_IFREG | 0444;
inode->i_fop = &pstore_file_operations;
scnprintf(name, sizeof(name), "%s-%s-%llu%s",
pstore_type_to_name(record->type),
record->psi->name, record->id,
record->compressed ? ".enc.z" : "");
private = kzalloc(sizeof(*private), GFP_KERNEL);
if (!private)
goto fail_inode;
dentry = d_alloc_name(root, name);
if (!dentry)
goto fail_private;
private->dentry = dentry;
private->record = record;
inode->i_size = private->total_size = size;
inode->i_private = private;
if (record->time.tv_sec)
inode->i_mtime = inode_set_ctime_to_ts(inode, record->time);
d_add(dentry, inode);
list_add(&private->list, &records_list);
mutex_unlock(&records_list_lock);
return 0;
fail_private:
free_pstore_private(private);
fail_inode:
iput(inode);
fail:
mutex_unlock(&records_list_lock);
return rc;
}
/*
* Read all the records from the persistent store. Create
* files in our filesystem. Don't warn about -EEXIST errors
* when we are re-scanning the backing store looking to add new
* error records.
*/
void pstore_get_records(int quiet)
{
struct dentry *root;
root = psinfo_lock_root();
if (!root)
return;
pstore_get_backend_records(psinfo, root, quiet);
inode_unlock(d_inode(root));
}
static int pstore_fill_super(struct super_block *sb, void *data, int silent)
{
struct inode *inode;
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_blocksize = PAGE_SIZE;
sb->s_blocksize_bits = PAGE_SHIFT;
sb->s_magic = PSTOREFS_MAGIC;
sb->s_op = &pstore_ops;
sb->s_time_gran = 1;
parse_options(data);
inode = pstore_get_inode(sb);
if (inode) {
inode->i_mode = S_IFDIR | 0750;
inode->i_op = &pstore_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
inc_nlink(inode);
}
sb->s_root = d_make_root(inode);
if (!sb->s_root)
return -ENOMEM;
mutex_lock(&pstore_sb_lock);
pstore_sb = sb;
mutex_unlock(&pstore_sb_lock);
pstore_get_records(0);
return 0;
}
static struct dentry *pstore_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_single(fs_type, flags, data, pstore_fill_super);
}
static void pstore_kill_sb(struct super_block *sb)
{
mutex_lock(&pstore_sb_lock);
WARN_ON(pstore_sb && pstore_sb != sb);
kill_litter_super(sb);
pstore_sb = NULL;
mutex_lock(&records_list_lock);
INIT_LIST_HEAD(&records_list);
mutex_unlock(&records_list_lock);
mutex_unlock(&pstore_sb_lock);
}
static struct file_system_type pstore_fs_type = {
.owner = THIS_MODULE,
.name = "pstore",
.mount = pstore_mount,
.kill_sb = pstore_kill_sb,
};
int __init pstore_init_fs(void)
{
int err;
/* Create a convenient mount point for people to access pstore */
err = sysfs_create_mount_point(fs_kobj, "pstore");
if (err)
goto out;
err = register_filesystem(&pstore_fs_type);
if (err < 0)
sysfs_remove_mount_point(fs_kobj, "pstore");
out:
return err;
}
void __exit pstore_exit_fs(void)
{
unregister_filesystem(&pstore_fs_type);
sysfs_remove_mount_point(fs_kobj, "pstore");
}
| linux-master | fs/pstore/inode.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* RAM Oops/Panic logger
*
* Copyright (C) 2010 Marco Stornelli <[email protected]>
* Copyright (C) 2011 Kees Cook <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/pstore.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/compiler.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/mm.h>
#include "internal.h"
#include "ram_internal.h"
#define RAMOOPS_KERNMSG_HDR "===="
#define MIN_MEM_SIZE 4096UL
static ulong record_size = MIN_MEM_SIZE;
module_param(record_size, ulong, 0400);
MODULE_PARM_DESC(record_size,
"size of each dump done on oops/panic");
static ulong ramoops_console_size = MIN_MEM_SIZE;
module_param_named(console_size, ramoops_console_size, ulong, 0400);
MODULE_PARM_DESC(console_size, "size of kernel console log");
static ulong ramoops_ftrace_size = MIN_MEM_SIZE;
module_param_named(ftrace_size, ramoops_ftrace_size, ulong, 0400);
MODULE_PARM_DESC(ftrace_size, "size of ftrace log");
static ulong ramoops_pmsg_size = MIN_MEM_SIZE;
module_param_named(pmsg_size, ramoops_pmsg_size, ulong, 0400);
MODULE_PARM_DESC(pmsg_size, "size of user space message log");
static unsigned long long mem_address;
module_param_hw(mem_address, ullong, other, 0400);
MODULE_PARM_DESC(mem_address,
"start of reserved RAM used to store oops/panic logs");
static ulong mem_size;
module_param(mem_size, ulong, 0400);
MODULE_PARM_DESC(mem_size,
"size of reserved RAM used to store oops/panic logs");
static unsigned int mem_type;
module_param(mem_type, uint, 0400);
MODULE_PARM_DESC(mem_type,
"memory type: 0=write-combined (default), 1=unbuffered, 2=cached");
static int ramoops_max_reason = -1;
module_param_named(max_reason, ramoops_max_reason, int, 0400);
MODULE_PARM_DESC(max_reason,
"maximum reason for kmsg dump (default 2: Oops and Panic) ");
static int ramoops_ecc;
module_param_named(ecc, ramoops_ecc, int, 0400);
MODULE_PARM_DESC(ramoops_ecc,
"if non-zero, the option enables ECC support and specifies "
"ECC buffer size in bytes (1 is a special value, means 16 "
"bytes ECC)");
static int ramoops_dump_oops = -1;
module_param_named(dump_oops, ramoops_dump_oops, int, 0400);
MODULE_PARM_DESC(dump_oops,
"(deprecated: use max_reason instead) set to 1 to dump oopses & panics, 0 to only dump panics");
struct ramoops_context {
struct persistent_ram_zone **dprzs; /* Oops dump zones */
struct persistent_ram_zone *cprz; /* Console zone */
struct persistent_ram_zone **fprzs; /* Ftrace zones */
struct persistent_ram_zone *mprz; /* PMSG zone */
phys_addr_t phys_addr;
unsigned long size;
unsigned int memtype;
size_t record_size;
size_t console_size;
size_t ftrace_size;
size_t pmsg_size;
u32 flags;
struct persistent_ram_ecc_info ecc_info;
unsigned int max_dump_cnt;
unsigned int dump_write_cnt;
/* _read_cnt need clear on ramoops_pstore_open */
unsigned int dump_read_cnt;
unsigned int console_read_cnt;
unsigned int max_ftrace_cnt;
unsigned int ftrace_read_cnt;
unsigned int pmsg_read_cnt;
struct pstore_info pstore;
};
static struct platform_device *dummy;
static int ramoops_pstore_open(struct pstore_info *psi)
{
struct ramoops_context *cxt = psi->data;
cxt->dump_read_cnt = 0;
cxt->console_read_cnt = 0;
cxt->ftrace_read_cnt = 0;
cxt->pmsg_read_cnt = 0;
return 0;
}
static struct persistent_ram_zone *
ramoops_get_next_prz(struct persistent_ram_zone *przs[], int id,
struct pstore_record *record)
{
struct persistent_ram_zone *prz;
/* Give up if we never existed or have hit the end. */
if (!przs)
return NULL;
prz = przs[id];
if (!prz)
return NULL;
/* Update old/shadowed buffer. */
if (prz->type == PSTORE_TYPE_DMESG)
persistent_ram_save_old(prz);
if (!persistent_ram_old_size(prz))
return NULL;
record->type = prz->type;
record->id = id;
return prz;
}
static int ramoops_read_kmsg_hdr(char *buffer, struct timespec64 *time,
bool *compressed)
{
char data_type;
int header_length = 0;
if (sscanf(buffer, RAMOOPS_KERNMSG_HDR "%lld.%lu-%c\n%n",
(time64_t *)&time->tv_sec, &time->tv_nsec, &data_type,
&header_length) == 3) {
time->tv_nsec *= 1000;
if (data_type == 'C')
*compressed = true;
else
*compressed = false;
} else if (sscanf(buffer, RAMOOPS_KERNMSG_HDR "%lld.%lu\n%n",
(time64_t *)&time->tv_sec, &time->tv_nsec,
&header_length) == 2) {
time->tv_nsec *= 1000;
*compressed = false;
} else {
time->tv_sec = 0;
time->tv_nsec = 0;
*compressed = false;
}
return header_length;
}
static bool prz_ok(struct persistent_ram_zone *prz)
{
return !!prz && !!(persistent_ram_old_size(prz) +
persistent_ram_ecc_string(prz, NULL, 0));
}
static ssize_t ramoops_pstore_read(struct pstore_record *record)
{
ssize_t size = 0;
struct ramoops_context *cxt = record->psi->data;
struct persistent_ram_zone *prz = NULL;
int header_length = 0;
bool free_prz = false;
/*
* Ramoops headers provide time stamps for PSTORE_TYPE_DMESG, but
* PSTORE_TYPE_CONSOLE and PSTORE_TYPE_FTRACE don't currently have
* valid time stamps, so it is initialized to zero.
*/
record->time.tv_sec = 0;
record->time.tv_nsec = 0;
record->compressed = false;
/* Find the next valid persistent_ram_zone for DMESG */
while (cxt->dump_read_cnt < cxt->max_dump_cnt && !prz) {
prz = ramoops_get_next_prz(cxt->dprzs, cxt->dump_read_cnt++,
record);
if (!prz_ok(prz))
continue;
header_length = ramoops_read_kmsg_hdr(persistent_ram_old(prz),
&record->time,
&record->compressed);
/* Clear and skip this DMESG record if it has no valid header */
if (!header_length) {
persistent_ram_free_old(prz);
persistent_ram_zap(prz);
prz = NULL;
}
}
if (!prz_ok(prz) && !cxt->console_read_cnt++)
prz = ramoops_get_next_prz(&cxt->cprz, 0 /* single */, record);
if (!prz_ok(prz) && !cxt->pmsg_read_cnt++)
prz = ramoops_get_next_prz(&cxt->mprz, 0 /* single */, record);
/* ftrace is last since it may want to dynamically allocate memory. */
if (!prz_ok(prz)) {
if (!(cxt->flags & RAMOOPS_FLAG_FTRACE_PER_CPU) &&
!cxt->ftrace_read_cnt++) {
prz = ramoops_get_next_prz(cxt->fprzs, 0 /* single */,
record);
} else {
/*
* Build a new dummy record which combines all the
* per-cpu records including metadata and ecc info.
*/
struct persistent_ram_zone *tmp_prz, *prz_next;
tmp_prz = kzalloc(sizeof(struct persistent_ram_zone),
GFP_KERNEL);
if (!tmp_prz)
return -ENOMEM;
prz = tmp_prz;
free_prz = true;
while (cxt->ftrace_read_cnt < cxt->max_ftrace_cnt) {
prz_next = ramoops_get_next_prz(cxt->fprzs,
cxt->ftrace_read_cnt++, record);
if (!prz_ok(prz_next))
continue;
tmp_prz->ecc_info = prz_next->ecc_info;
tmp_prz->corrected_bytes +=
prz_next->corrected_bytes;
tmp_prz->bad_blocks += prz_next->bad_blocks;
size = pstore_ftrace_combine_log(
&tmp_prz->old_log,
&tmp_prz->old_log_size,
prz_next->old_log,
prz_next->old_log_size);
if (size)
goto out;
}
record->id = 0;
}
}
if (!prz_ok(prz)) {
size = 0;
goto out;
}
size = persistent_ram_old_size(prz) - header_length;
/* ECC correction notice */
record->ecc_notice_size = persistent_ram_ecc_string(prz, NULL, 0);
record->buf = kvzalloc(size + record->ecc_notice_size + 1, GFP_KERNEL);
if (record->buf == NULL) {
size = -ENOMEM;
goto out;
}
memcpy(record->buf, (char *)persistent_ram_old(prz) + header_length,
size);
persistent_ram_ecc_string(prz, record->buf + size,
record->ecc_notice_size + 1);
out:
if (free_prz) {
kvfree(prz->old_log);
kfree(prz);
}
return size;
}
static size_t ramoops_write_kmsg_hdr(struct persistent_ram_zone *prz,
struct pstore_record *record)
{
char hdr[36]; /* "===="(4), %lld(20), "."(1), %06lu(6), "-%c\n"(3) */
size_t len;
len = scnprintf(hdr, sizeof(hdr),
RAMOOPS_KERNMSG_HDR "%lld.%06lu-%c\n",
(time64_t)record->time.tv_sec,
record->time.tv_nsec / 1000,
record->compressed ? 'C' : 'D');
persistent_ram_write(prz, hdr, len);
return len;
}
static int notrace ramoops_pstore_write(struct pstore_record *record)
{
struct ramoops_context *cxt = record->psi->data;
struct persistent_ram_zone *prz;
size_t size, hlen;
if (record->type == PSTORE_TYPE_CONSOLE) {
if (!cxt->cprz)
return -ENOMEM;
persistent_ram_write(cxt->cprz, record->buf, record->size);
return 0;
} else if (record->type == PSTORE_TYPE_FTRACE) {
int zonenum;
if (!cxt->fprzs)
return -ENOMEM;
/*
* Choose zone by if we're using per-cpu buffers.
*/
if (cxt->flags & RAMOOPS_FLAG_FTRACE_PER_CPU)
zonenum = smp_processor_id();
else
zonenum = 0;
persistent_ram_write(cxt->fprzs[zonenum], record->buf,
record->size);
return 0;
} else if (record->type == PSTORE_TYPE_PMSG) {
pr_warn_ratelimited("PMSG shouldn't call %s\n", __func__);
return -EINVAL;
}
if (record->type != PSTORE_TYPE_DMESG)
return -EINVAL;
/*
* We could filter on record->reason here if we wanted to (which
* would duplicate what happened before the "max_reason" setting
* was added), but that would defeat the purpose of a system
* changing printk.always_kmsg_dump, so instead log everything that
* the kmsg dumper sends us, since it should be doing the filtering
* based on the combination of printk.always_kmsg_dump and our
* requested "max_reason".
*/
/*
* Explicitly only take the first part of any new crash.
* If our buffer is larger than kmsg_bytes, this can never happen,
* and if our buffer is smaller than kmsg_bytes, we don't want the
* report split across multiple records.
*/
if (record->part != 1)
return -ENOSPC;
if (!cxt->dprzs)
return -ENOSPC;
prz = cxt->dprzs[cxt->dump_write_cnt];
/*
* Since this is a new crash dump, we need to reset the buffer in
* case it still has an old dump present. Without this, the new dump
* will get appended, which would seriously confuse anything trying
* to check dump file contents. Specifically, ramoops_read_kmsg_hdr()
* expects to find a dump header in the beginning of buffer data, so
* we must to reset the buffer values, in order to ensure that the
* header will be written to the beginning of the buffer.
*/
persistent_ram_zap(prz);
/* Build header and append record contents. */
hlen = ramoops_write_kmsg_hdr(prz, record);
if (!hlen)
return -ENOMEM;
size = record->size;
if (size + hlen > prz->buffer_size)
size = prz->buffer_size - hlen;
persistent_ram_write(prz, record->buf, size);
cxt->dump_write_cnt = (cxt->dump_write_cnt + 1) % cxt->max_dump_cnt;
return 0;
}
static int notrace ramoops_pstore_write_user(struct pstore_record *record,
const char __user *buf)
{
if (record->type == PSTORE_TYPE_PMSG) {
struct ramoops_context *cxt = record->psi->data;
if (!cxt->mprz)
return -ENOMEM;
return persistent_ram_write_user(cxt->mprz, buf, record->size);
}
return -EINVAL;
}
static int ramoops_pstore_erase(struct pstore_record *record)
{
struct ramoops_context *cxt = record->psi->data;
struct persistent_ram_zone *prz;
switch (record->type) {
case PSTORE_TYPE_DMESG:
if (record->id >= cxt->max_dump_cnt)
return -EINVAL;
prz = cxt->dprzs[record->id];
break;
case PSTORE_TYPE_CONSOLE:
prz = cxt->cprz;
break;
case PSTORE_TYPE_FTRACE:
if (record->id >= cxt->max_ftrace_cnt)
return -EINVAL;
prz = cxt->fprzs[record->id];
break;
case PSTORE_TYPE_PMSG:
prz = cxt->mprz;
break;
default:
return -EINVAL;
}
persistent_ram_free_old(prz);
persistent_ram_zap(prz);
return 0;
}
static struct ramoops_context oops_cxt = {
.pstore = {
.owner = THIS_MODULE,
.name = "ramoops",
.open = ramoops_pstore_open,
.read = ramoops_pstore_read,
.write = ramoops_pstore_write,
.write_user = ramoops_pstore_write_user,
.erase = ramoops_pstore_erase,
},
};
static void ramoops_free_przs(struct ramoops_context *cxt)
{
int i;
/* Free pmsg PRZ */
persistent_ram_free(&cxt->mprz);
/* Free console PRZ */
persistent_ram_free(&cxt->cprz);
/* Free dump PRZs */
if (cxt->dprzs) {
for (i = 0; i < cxt->max_dump_cnt; i++)
persistent_ram_free(&cxt->dprzs[i]);
kfree(cxt->dprzs);
cxt->dprzs = NULL;
cxt->max_dump_cnt = 0;
}
/* Free ftrace PRZs */
if (cxt->fprzs) {
for (i = 0; i < cxt->max_ftrace_cnt; i++)
persistent_ram_free(&cxt->fprzs[i]);
kfree(cxt->fprzs);
cxt->fprzs = NULL;
cxt->max_ftrace_cnt = 0;
}
}
static int ramoops_init_przs(const char *name,
struct device *dev, struct ramoops_context *cxt,
struct persistent_ram_zone ***przs,
phys_addr_t *paddr, size_t mem_sz,
ssize_t record_size,
unsigned int *cnt, u32 sig, u32 flags)
{
int err = -ENOMEM;
int i;
size_t zone_sz;
struct persistent_ram_zone **prz_ar;
/* Allocate nothing for 0 mem_sz or 0 record_size. */
if (mem_sz == 0 || record_size == 0) {
*cnt = 0;
return 0;
}
/*
* If we have a negative record size, calculate it based on
* mem_sz / *cnt. If we have a positive record size, calculate
* cnt from mem_sz / record_size.
*/
if (record_size < 0) {
if (*cnt == 0)
return 0;
record_size = mem_sz / *cnt;
if (record_size == 0) {
dev_err(dev, "%s record size == 0 (%zu / %u)\n",
name, mem_sz, *cnt);
goto fail;
}
} else {
*cnt = mem_sz / record_size;
if (*cnt == 0) {
dev_err(dev, "%s record count == 0 (%zu / %zu)\n",
name, mem_sz, record_size);
goto fail;
}
}
if (*paddr + mem_sz - cxt->phys_addr > cxt->size) {
dev_err(dev, "no room for %s mem region (0x%zx@0x%llx) in (0x%lx@0x%llx)\n",
name,
mem_sz, (unsigned long long)*paddr,
cxt->size, (unsigned long long)cxt->phys_addr);
goto fail;
}
zone_sz = mem_sz / *cnt;
if (!zone_sz) {
dev_err(dev, "%s zone size == 0\n", name);
goto fail;
}
prz_ar = kcalloc(*cnt, sizeof(**przs), GFP_KERNEL);
if (!prz_ar)
goto fail;
for (i = 0; i < *cnt; i++) {
char *label;
if (*cnt == 1)
label = kasprintf(GFP_KERNEL, "ramoops:%s", name);
else
label = kasprintf(GFP_KERNEL, "ramoops:%s(%d/%d)",
name, i, *cnt - 1);
prz_ar[i] = persistent_ram_new(*paddr, zone_sz, sig,
&cxt->ecc_info,
cxt->memtype, flags, label);
kfree(label);
if (IS_ERR(prz_ar[i])) {
err = PTR_ERR(prz_ar[i]);
dev_err(dev, "failed to request %s mem region (0x%zx@0x%llx): %d\n",
name, record_size,
(unsigned long long)*paddr, err);
while (i > 0) {
i--;
persistent_ram_free(&prz_ar[i]);
}
kfree(prz_ar);
prz_ar = NULL;
goto fail;
}
*paddr += zone_sz;
prz_ar[i]->type = pstore_name_to_type(name);
}
*przs = prz_ar;
return 0;
fail:
*cnt = 0;
return err;
}
static int ramoops_init_prz(const char *name,
struct device *dev, struct ramoops_context *cxt,
struct persistent_ram_zone **prz,
phys_addr_t *paddr, size_t sz, u32 sig)
{
char *label;
if (!sz)
return 0;
if (*paddr + sz - cxt->phys_addr > cxt->size) {
dev_err(dev, "no room for %s mem region (0x%zx@0x%llx) in (0x%lx@0x%llx)\n",
name, sz, (unsigned long long)*paddr,
cxt->size, (unsigned long long)cxt->phys_addr);
return -ENOMEM;
}
label = kasprintf(GFP_KERNEL, "ramoops:%s", name);
*prz = persistent_ram_new(*paddr, sz, sig, &cxt->ecc_info,
cxt->memtype, PRZ_FLAG_ZAP_OLD, label);
kfree(label);
if (IS_ERR(*prz)) {
int err = PTR_ERR(*prz);
dev_err(dev, "failed to request %s mem region (0x%zx@0x%llx): %d\n",
name, sz, (unsigned long long)*paddr, err);
return err;
}
*paddr += sz;
(*prz)->type = pstore_name_to_type(name);
return 0;
}
/* Read a u32 from a dt property and make sure it's safe for an int. */
static int ramoops_parse_dt_u32(struct platform_device *pdev,
const char *propname,
u32 default_value, u32 *value)
{
u32 val32 = 0;
int ret;
ret = of_property_read_u32(pdev->dev.of_node, propname, &val32);
if (ret == -EINVAL) {
/* field is missing, use default value. */
val32 = default_value;
} else if (ret < 0) {
dev_err(&pdev->dev, "failed to parse property %s: %d\n",
propname, ret);
return ret;
}
/* Sanity check our results. */
if (val32 > INT_MAX) {
dev_err(&pdev->dev, "%s %u > INT_MAX\n", propname, val32);
return -EOVERFLOW;
}
*value = val32;
return 0;
}
static int ramoops_parse_dt(struct platform_device *pdev,
struct ramoops_platform_data *pdata)
{
struct device_node *of_node = pdev->dev.of_node;
struct device_node *parent_node;
struct resource *res;
u32 value;
int ret;
dev_dbg(&pdev->dev, "using Device Tree\n");
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev,
"failed to locate DT /reserved-memory resource\n");
return -EINVAL;
}
pdata->mem_size = resource_size(res);
pdata->mem_address = res->start;
/*
* Setting "unbuffered" is deprecated and will be ignored if
* "mem_type" is also specified.
*/
pdata->mem_type = of_property_read_bool(of_node, "unbuffered");
/*
* Setting "no-dump-oops" is deprecated and will be ignored if
* "max_reason" is also specified.
*/
if (of_property_read_bool(of_node, "no-dump-oops"))
pdata->max_reason = KMSG_DUMP_PANIC;
else
pdata->max_reason = KMSG_DUMP_OOPS;
#define parse_u32(name, field, default_value) { \
ret = ramoops_parse_dt_u32(pdev, name, default_value, \
&value); \
if (ret < 0) \
return ret; \
field = value; \
}
parse_u32("mem-type", pdata->mem_type, pdata->mem_type);
parse_u32("record-size", pdata->record_size, 0);
parse_u32("console-size", pdata->console_size, 0);
parse_u32("ftrace-size", pdata->ftrace_size, 0);
parse_u32("pmsg-size", pdata->pmsg_size, 0);
parse_u32("ecc-size", pdata->ecc_info.ecc_size, 0);
parse_u32("flags", pdata->flags, 0);
parse_u32("max-reason", pdata->max_reason, pdata->max_reason);
#undef parse_u32
/*
* Some old Chromebooks relied on the kernel setting the
* console_size and pmsg_size to the record size since that's
* what the downstream kernel did. These same Chromebooks had
* "ramoops" straight under the root node which isn't
* according to the current upstream bindings (though it was
* arguably acceptable under a prior version of the bindings).
* Let's make those old Chromebooks work by detecting that
* we're not a child of "reserved-memory" and mimicking the
* expected behavior.
*/
parent_node = of_get_parent(of_node);
if (!of_node_name_eq(parent_node, "reserved-memory") &&
!pdata->console_size && !pdata->ftrace_size &&
!pdata->pmsg_size && !pdata->ecc_info.ecc_size) {
pdata->console_size = pdata->record_size;
pdata->pmsg_size = pdata->record_size;
}
of_node_put(parent_node);
return 0;
}
static int ramoops_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct ramoops_platform_data *pdata = dev->platform_data;
struct ramoops_platform_data pdata_local;
struct ramoops_context *cxt = &oops_cxt;
size_t dump_mem_sz;
phys_addr_t paddr;
int err = -EINVAL;
/*
* Only a single ramoops area allowed at a time, so fail extra
* probes.
*/
if (cxt->max_dump_cnt) {
pr_err("already initialized\n");
goto fail_out;
}
if (dev_of_node(dev) && !pdata) {
pdata = &pdata_local;
memset(pdata, 0, sizeof(*pdata));
err = ramoops_parse_dt(pdev, pdata);
if (err < 0)
goto fail_out;
}
/* Make sure we didn't get bogus platform data pointer. */
if (!pdata) {
pr_err("NULL platform data\n");
err = -EINVAL;
goto fail_out;
}
if (!pdata->mem_size || (!pdata->record_size && !pdata->console_size &&
!pdata->ftrace_size && !pdata->pmsg_size)) {
pr_err("The memory size and the record/console size must be "
"non-zero\n");
err = -EINVAL;
goto fail_out;
}
if (pdata->record_size && !is_power_of_2(pdata->record_size))
pdata->record_size = rounddown_pow_of_two(pdata->record_size);
if (pdata->console_size && !is_power_of_2(pdata->console_size))
pdata->console_size = rounddown_pow_of_two(pdata->console_size);
if (pdata->ftrace_size && !is_power_of_2(pdata->ftrace_size))
pdata->ftrace_size = rounddown_pow_of_two(pdata->ftrace_size);
if (pdata->pmsg_size && !is_power_of_2(pdata->pmsg_size))
pdata->pmsg_size = rounddown_pow_of_two(pdata->pmsg_size);
cxt->size = pdata->mem_size;
cxt->phys_addr = pdata->mem_address;
cxt->memtype = pdata->mem_type;
cxt->record_size = pdata->record_size;
cxt->console_size = pdata->console_size;
cxt->ftrace_size = pdata->ftrace_size;
cxt->pmsg_size = pdata->pmsg_size;
cxt->flags = pdata->flags;
cxt->ecc_info = pdata->ecc_info;
paddr = cxt->phys_addr;
dump_mem_sz = cxt->size - cxt->console_size - cxt->ftrace_size
- cxt->pmsg_size;
err = ramoops_init_przs("dmesg", dev, cxt, &cxt->dprzs, &paddr,
dump_mem_sz, cxt->record_size,
&cxt->max_dump_cnt, 0, 0);
if (err)
goto fail_init;
err = ramoops_init_prz("console", dev, cxt, &cxt->cprz, &paddr,
cxt->console_size, 0);
if (err)
goto fail_init;
err = ramoops_init_prz("pmsg", dev, cxt, &cxt->mprz, &paddr,
cxt->pmsg_size, 0);
if (err)
goto fail_init;
cxt->max_ftrace_cnt = (cxt->flags & RAMOOPS_FLAG_FTRACE_PER_CPU)
? nr_cpu_ids
: 1;
err = ramoops_init_przs("ftrace", dev, cxt, &cxt->fprzs, &paddr,
cxt->ftrace_size, -1,
&cxt->max_ftrace_cnt, LINUX_VERSION_CODE,
(cxt->flags & RAMOOPS_FLAG_FTRACE_PER_CPU)
? PRZ_FLAG_NO_LOCK : 0);
if (err)
goto fail_init;
cxt->pstore.data = cxt;
/*
* Prepare frontend flags based on which areas are initialized.
* For ramoops_init_przs() cases, the "max count" variable tells
* if there are regions present. For ramoops_init_prz() cases,
* the single region size is how to check.
*/
cxt->pstore.flags = 0;
if (cxt->max_dump_cnt) {
cxt->pstore.flags |= PSTORE_FLAGS_DMESG;
cxt->pstore.max_reason = pdata->max_reason;
}
if (cxt->console_size)
cxt->pstore.flags |= PSTORE_FLAGS_CONSOLE;
if (cxt->max_ftrace_cnt)
cxt->pstore.flags |= PSTORE_FLAGS_FTRACE;
if (cxt->pmsg_size)
cxt->pstore.flags |= PSTORE_FLAGS_PMSG;
/*
* Since bufsize is only used for dmesg crash dumps, it
* must match the size of the dprz record (after PRZ header
* and ECC bytes have been accounted for).
*/
if (cxt->pstore.flags & PSTORE_FLAGS_DMESG) {
cxt->pstore.bufsize = cxt->dprzs[0]->buffer_size;
cxt->pstore.buf = kvzalloc(cxt->pstore.bufsize, GFP_KERNEL);
if (!cxt->pstore.buf) {
pr_err("cannot allocate pstore crash dump buffer\n");
err = -ENOMEM;
goto fail_clear;
}
}
err = pstore_register(&cxt->pstore);
if (err) {
pr_err("registering with pstore failed\n");
goto fail_buf;
}
/*
* Update the module parameter variables as well so they are visible
* through /sys/module/ramoops/parameters/
*/
mem_size = pdata->mem_size;
mem_address = pdata->mem_address;
record_size = pdata->record_size;
ramoops_max_reason = pdata->max_reason;
ramoops_console_size = pdata->console_size;
ramoops_pmsg_size = pdata->pmsg_size;
ramoops_ftrace_size = pdata->ftrace_size;
pr_info("using 0x%lx@0x%llx, ecc: %d\n",
cxt->size, (unsigned long long)cxt->phys_addr,
cxt->ecc_info.ecc_size);
return 0;
fail_buf:
kvfree(cxt->pstore.buf);
fail_clear:
cxt->pstore.bufsize = 0;
fail_init:
ramoops_free_przs(cxt);
fail_out:
return err;
}
static void ramoops_remove(struct platform_device *pdev)
{
struct ramoops_context *cxt = &oops_cxt;
pstore_unregister(&cxt->pstore);
kvfree(cxt->pstore.buf);
cxt->pstore.bufsize = 0;
ramoops_free_przs(cxt);
}
static const struct of_device_id dt_match[] = {
{ .compatible = "ramoops" },
{}
};
static struct platform_driver ramoops_driver = {
.probe = ramoops_probe,
.remove_new = ramoops_remove,
.driver = {
.name = "ramoops",
.of_match_table = dt_match,
},
};
static inline void ramoops_unregister_dummy(void)
{
platform_device_unregister(dummy);
dummy = NULL;
}
static void __init ramoops_register_dummy(void)
{
struct ramoops_platform_data pdata;
/*
* Prepare a dummy platform data structure to carry the module
* parameters. If mem_size isn't set, then there are no module
* parameters, and we can skip this.
*/
if (!mem_size)
return;
pr_info("using module parameters\n");
memset(&pdata, 0, sizeof(pdata));
pdata.mem_size = mem_size;
pdata.mem_address = mem_address;
pdata.mem_type = mem_type;
pdata.record_size = record_size;
pdata.console_size = ramoops_console_size;
pdata.ftrace_size = ramoops_ftrace_size;
pdata.pmsg_size = ramoops_pmsg_size;
/* If "max_reason" is set, its value has priority over "dump_oops". */
if (ramoops_max_reason >= 0)
pdata.max_reason = ramoops_max_reason;
/* Otherwise, if "dump_oops" is set, parse it into "max_reason". */
else if (ramoops_dump_oops != -1)
pdata.max_reason = ramoops_dump_oops ? KMSG_DUMP_OOPS
: KMSG_DUMP_PANIC;
/* And if neither are explicitly set, use the default. */
else
pdata.max_reason = KMSG_DUMP_OOPS;
pdata.flags = RAMOOPS_FLAG_FTRACE_PER_CPU;
/*
* For backwards compatibility ramoops.ecc=1 means 16 bytes ECC
* (using 1 byte for ECC isn't much of use anyway).
*/
pdata.ecc_info.ecc_size = ramoops_ecc == 1 ? 16 : ramoops_ecc;
dummy = platform_device_register_data(NULL, "ramoops", -1,
&pdata, sizeof(pdata));
if (IS_ERR(dummy)) {
pr_info("could not create platform device: %ld\n",
PTR_ERR(dummy));
dummy = NULL;
}
}
static int __init ramoops_init(void)
{
int ret;
ramoops_register_dummy();
ret = platform_driver_register(&ramoops_driver);
if (ret != 0)
ramoops_unregister_dummy();
return ret;
}
postcore_initcall(ramoops_init);
static void __exit ramoops_exit(void)
{
platform_driver_unregister(&ramoops_driver);
ramoops_unregister_dummy();
}
module_exit(ramoops_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marco Stornelli <[email protected]>");
MODULE_DESCRIPTION("RAM Oops/Panic logger/driver");
| linux-master | fs/pstore/ram.c |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.