// SPDX-License-Identifier: GPL-2.0
/*
 *  linux/fs/ldiskfs/sysfs.c
 *
 * Copyright (C) 1992, 1993, 1994, 1995
 * Remy Card (card@masi.ibp.fr)
 * Theodore Ts'o (tytso@mit.edu)
 *
 */

#include <linux/time.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>

#include "ldiskfs.h"
#include "ldiskfs_jbd2.h"

typedef enum {
	attr_noop,
	attr_delayed_allocation_blocks,
	attr_mb_c1_threshold,
	attr_mb_c2_threshold,
	attr_mb_c3_threshold,
	attr_session_write_kbytes,
	attr_lifetime_write_kbytes,
	attr_reserved_clusters,
	attr_inode_readahead,
	attr_trigger_test_error,
	attr_first_error_time,
	attr_last_error_time,
	attr_feature,
	attr_pointer_ui,
	attr_pointer_atomic,
	attr_journal_task,
} attr_id_t;

typedef enum {
	ptr_explicit,
	ptr_ldiskfs_sb_info_offset,
	ptr_ldiskfs_super_block_offset,
} attr_ptr_t;

static const char proc_dirname[] = "fs/ldiskfs";
static struct proc_dir_entry *ldiskfs_proc_root;

struct ldiskfs_attr {
	struct attribute attr;
	short attr_id;
	short attr_ptr;
	union {
		int offset;
		void *explicit_ptr;
	} u;
};

static ssize_t session_write_kbytes_show(struct ldiskfs_sb_info *sbi, char *buf)
{
	struct super_block *sb = sbi->s_buddy_cache->i_sb;

	if (!sb->s_bdev->bd_part)
		return snprintf(buf, PAGE_SIZE, "0\n");
	return snprintf(buf, PAGE_SIZE, "%lu\n",
			(part_stat_read(sb->s_bdev->bd_part,
					sectors[STAT_WRITE]) -
			 sbi->s_sectors_written_start) >> 1);
}

static ssize_t lifetime_write_kbytes_show(struct ldiskfs_sb_info *sbi, char *buf)
{
	struct super_block *sb = sbi->s_buddy_cache->i_sb;

	if (!sb->s_bdev->bd_part)
		return snprintf(buf, PAGE_SIZE, "0\n");
	return snprintf(buf, PAGE_SIZE, "%llu\n",
			(unsigned long long)(sbi->s_kbytes_written +
			((part_stat_read(sb->s_bdev->bd_part,
					 sectors[STAT_WRITE]) -
			  LDISKFS_SB(sb)->s_sectors_written_start) >> 1)));
}

static ssize_t inode_readahead_blks_store(struct ldiskfs_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 ldiskfs_sb_info *sbi,
				   const char *buf, size_t count)
{
	unsigned long long val;
	ldiskfs_fsblk_t clusters = (ldiskfs_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 ldiskfs_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)
		ldiskfs_error(sbi->s_sb, "%.*s", len, buf);
	return count;
}

static ssize_t journal_task_show(struct ldiskfs_sb_info *sbi, char *buf)
{
	if (!sbi->s_journal)
		return snprintf(buf, PAGE_SIZE, "<none>\n");
	return snprintf(buf, PAGE_SIZE, "%d\n",
			task_pid_vnr(sbi->s_journal->j_task));
}

int save_threshold_percent(struct ldiskfs_sb_info *sbi, const char *buf,
			   ldiskfs_fsblk_t *blocks)
{
	unsigned long long val;

	int ret;

	ret = kstrtoull(skip_spaces(buf), 0, &val);
	if (ret || val > 100)
		return -EINVAL;

	*blocks = val * ldiskfs_blocks_count(sbi->s_es) / 100;
	return 0;
}

#define THRESHOLD_PERCENT(sbi, blocks)					\
	(((blocks) - 1) * 100 / ldiskfs_blocks_count((sbi)->s_es) + 1)
static ssize_t mb_threshold_store(struct ldiskfs_sb_info *sbi,
				  const char *buf, size_t count,
				  ldiskfs_fsblk_t *blocks)
{
	int ret = save_threshold_percent(sbi, buf, blocks);

	return ret ?: count;
}

#define LDISKFS_ATTR(_name,_mode,_id)					\
static struct ldiskfs_attr ldiskfs_attr_##_name = {				\
	.attr = {.name = __stringify(_name), .mode = _mode },		\
	.attr_id = attr_##_id,						\
}

#define LDISKFS_ATTR_FUNC(_name,_mode)  LDISKFS_ATTR(_name,_mode,_name)

#define LDISKFS_ATTR_FEATURE(_name)   LDISKFS_ATTR(_name, 0444, feature)

#define LDISKFS_ATTR_OFFSET(_name,_mode,_id,_struct,_elname)	\
static struct ldiskfs_attr ldiskfs_attr_##_name = {			\
	.attr = {.name = __stringify(_name), .mode = _mode },	\
	.attr_id = attr_##_id,					\
	.attr_ptr = ptr_##_struct##_offset,			\
	.u = {							\
		.offset = offsetof(struct _struct, _elname),\
	},							\
}

#define LDISKFS_RO_ATTR_ES_UI(_name,_elname)				\
	LDISKFS_ATTR_OFFSET(_name, 0444, pointer_ui, ldiskfs_super_block, _elname)

#define LDISKFS_RW_ATTR_SBI_UI(_name,_elname)	\
	LDISKFS_ATTR_OFFSET(_name, 0644, pointer_ui, ldiskfs_sb_info, _elname)

#define LDISKFS_ATTR_PTR(_name,_mode,_id,_ptr) \
static struct ldiskfs_attr ldiskfs_attr_##_name = {			\
	.attr = {.name = __stringify(_name), .mode = _mode },	\
	.attr_id = attr_##_id,					\
	.attr_ptr = ptr_explicit,				\
	.u = {							\
		.explicit_ptr = _ptr,				\
	},							\
}

#define ATTR_LIST(name) &ldiskfs_attr_##name.attr

LDISKFS_ATTR_FUNC(delayed_allocation_blocks, 0444);
LDISKFS_ATTR_FUNC(session_write_kbytes, 0444);
LDISKFS_ATTR_FUNC(lifetime_write_kbytes, 0444);
LDISKFS_ATTR_FUNC(reserved_clusters, 0644);
LDISKFS_ATTR_FUNC(mb_c1_threshold, 0644);
LDISKFS_ATTR_FUNC(mb_c2_threshold, 0644);
LDISKFS_ATTR_FUNC(mb_c3_threshold, 0644);

LDISKFS_ATTR_OFFSET(inode_readahead_blks, 0644, inode_readahead,
		 ldiskfs_sb_info, s_inode_readahead_blks);
LDISKFS_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
LDISKFS_RW_ATTR_SBI_UI(max_dir_size, s_max_dir_size_kb);
LDISKFS_RW_ATTR_SBI_UI(max_dir_size_kb, s_max_dir_size_kb);
LDISKFS_RW_ATTR_SBI_UI(warning_dir_size, s_warning_dir_size);
LDISKFS_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
LDISKFS_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
LDISKFS_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
LDISKFS_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs);
LDISKFS_RW_ATTR_SBI_UI(mb_small_req, s_mb_small_req);
LDISKFS_RW_ATTR_SBI_UI(mb_large_req, s_mb_large_req);
LDISKFS_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc);
LDISKFS_RW_ATTR_SBI_UI(extent_max_zeroout_kb, s_extent_max_zeroout_kb);
LDISKFS_ATTR(trigger_fs_error, 0200, trigger_test_error);
LDISKFS_RW_ATTR_SBI_UI(err_ratelimit_interval_ms, s_err_ratelimit_state.interval);
LDISKFS_RW_ATTR_SBI_UI(err_ratelimit_burst, s_err_ratelimit_state.burst);
LDISKFS_RW_ATTR_SBI_UI(warning_ratelimit_interval_ms, s_warning_ratelimit_state.interval);
LDISKFS_RW_ATTR_SBI_UI(warning_ratelimit_burst, s_warning_ratelimit_state.burst);
LDISKFS_RW_ATTR_SBI_UI(msg_ratelimit_interval_ms, s_msg_ratelimit_state.interval);
LDISKFS_RW_ATTR_SBI_UI(msg_ratelimit_burst, s_msg_ratelimit_state.burst);
LDISKFS_RO_ATTR_ES_UI(errors_count, s_error_count);
LDISKFS_ATTR(first_error_time, 0444, first_error_time);
LDISKFS_ATTR(last_error_time, 0444, last_error_time);
LDISKFS_ATTR(journal_task, 0444, journal_task);
LDISKFS_RW_ATTR_SBI_UI(mb_prefetch, s_mb_prefetch);
LDISKFS_RW_ATTR_SBI_UI(mb_prefetch_limit, s_mb_prefetch_limit);

static unsigned int old_bump_val = 128;
LDISKFS_ATTR_PTR(max_writeback_mb_bump, 0444, pointer_ui, &old_bump_val);

static struct attribute *ldiskfs_attrs[] = {
	ATTR_LIST(delayed_allocation_blocks),
	ATTR_LIST(session_write_kbytes),
	ATTR_LIST(lifetime_write_kbytes),
	ATTR_LIST(reserved_clusters),
	ATTR_LIST(mb_c1_threshold),
	ATTR_LIST(mb_c2_threshold),
	ATTR_LIST(mb_c3_threshold),
	ATTR_LIST(inode_readahead_blks),
	ATTR_LIST(inode_goal),
	ATTR_LIST(max_dir_size),
	ATTR_LIST(max_dir_size_kb),
	ATTR_LIST(warning_dir_size),
	ATTR_LIST(mb_stats),
	ATTR_LIST(mb_max_to_scan),
	ATTR_LIST(mb_min_to_scan),
	ATTR_LIST(mb_order2_req),
	ATTR_LIST(mb_small_req),
	ATTR_LIST(mb_large_req),
	ATTR_LIST(mb_group_prealloc),
	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(errors_count),
	ATTR_LIST(first_error_time),
	ATTR_LIST(last_error_time),
	ATTR_LIST(journal_task),
	ATTR_LIST(mb_prefetch),
	ATTR_LIST(mb_prefetch_limit),
	NULL,
};

/* Features this copy of ldiskfs supports */
LDISKFS_ATTR_FEATURE(lazy_itable_init);
LDISKFS_ATTR_FEATURE(batched_discard);
LDISKFS_ATTR_FEATURE(meta_bg_resize);
#ifdef CONFIG_LDISKFS_FS_ENCRYPTION
LDISKFS_ATTR_FEATURE(encryption);
#endif
LDISKFS_ATTR_FEATURE(metadata_csum_seed);

static struct attribute *ldiskfs_feat_attrs[] = {
	ATTR_LIST(lazy_itable_init),
	ATTR_LIST(batched_discard),
	ATTR_LIST(meta_bg_resize),
#ifdef CONFIG_LDISKFS_FS_ENCRYPTION
	ATTR_LIST(encryption),
#endif
	ATTR_LIST(metadata_csum_seed),
	NULL,
};

static void *calc_ptr(struct ldiskfs_attr *a, struct ldiskfs_sb_info *sbi)
{
	switch (a->attr_ptr) {
	case ptr_explicit:
		return a->u.explicit_ptr;
	case ptr_ldiskfs_sb_info_offset:
		return (void *) (((char *) sbi) + a->u.offset);
	case ptr_ldiskfs_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 snprintf(buf, PAGE_SIZE, "%lld",
			((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 ldiskfs_attr_show(struct kobject *kobj,
			      struct attribute *attr, char *buf)
{
	struct ldiskfs_sb_info *sbi = container_of(kobj, struct ldiskfs_sb_info,
						s_kobj);
	struct ldiskfs_attr *a = container_of(attr, struct ldiskfs_attr, attr);
	void *ptr = calc_ptr(a, sbi);

	switch (a->attr_id) {
	case attr_delayed_allocation_blocks:
		return snprintf(buf, PAGE_SIZE, "%llu\n",
				(s64) LDISKFS_C2B(sbi,
		       percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
	case attr_mb_c1_threshold:
		return scnprintf(buf, PAGE_SIZE, "%llu\n",
				 THRESHOLD_PERCENT(sbi, sbi->s_mb_c1_blocks));
	case attr_mb_c2_threshold:
		return scnprintf(buf, PAGE_SIZE, "%llu\n",
				 THRESHOLD_PERCENT(sbi, sbi->s_mb_c2_blocks));
	case attr_mb_c3_threshold:
		return scnprintf(buf, PAGE_SIZE, "%llu\n",
				 THRESHOLD_PERCENT(sbi, sbi->s_mb_c3_blocks));
	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 snprintf(buf, PAGE_SIZE, "%llu\n",
				(unsigned long long)
				atomic64_read(&sbi->s_resv_clusters));
	case attr_inode_readahead:
	case attr_pointer_ui:
		if (!ptr)
			return 0;
		if (a->attr_ptr == ptr_ldiskfs_super_block_offset)
			return snprintf(buf, PAGE_SIZE, "%u\n",
					le32_to_cpup(ptr));
		else
			return snprintf(buf, PAGE_SIZE, "%u\n",
					strcmp("max_dir_size", a->attr.name) ?
					*((unsigned int *) ptr) :
					(*((unsigned int *) ptr)) << 10);
	case attr_pointer_atomic:
		if (!ptr)
			return 0;
		return snprintf(buf, PAGE_SIZE, "%d\n",
				atomic_read((atomic_t *) ptr));
	case attr_feature:
		return snprintf(buf, PAGE_SIZE, "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 ldiskfs_attr_store(struct kobject *kobj,
			       struct attribute *attr,
			       const char *buf, size_t len)
{
	struct ldiskfs_sb_info *sbi = container_of(kobj, struct ldiskfs_sb_info,
						s_kobj);
	struct ldiskfs_attr *a = container_of(attr, struct ldiskfs_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 (strcmp("max_dir_size", a->attr.name) == 0)
			t >>= 10;
		if (a->attr_ptr == ptr_ldiskfs_super_block_offset)
			*((__le32 *) ptr) = cpu_to_le32(t);
		else
			*((unsigned int *) 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);
	case attr_mb_c1_threshold:
		return mb_threshold_store(sbi, buf, len, &sbi->s_mb_c1_blocks);
	case attr_mb_c2_threshold:
		return mb_threshold_store(sbi, buf, len, &sbi->s_mb_c2_blocks);
	case attr_mb_c3_threshold:
		return mb_threshold_store(sbi, buf, len, &sbi->s_mb_c3_blocks);
	}
	return 0;
}

static void ldiskfs_sb_release(struct kobject *kobj)
{
	struct ldiskfs_sb_info *sbi = container_of(kobj, struct ldiskfs_sb_info,
						s_kobj);
	complete(&sbi->s_kobj_unregister);
}

static const struct sysfs_ops ldiskfs_attr_ops = {
	.show	= ldiskfs_attr_show,
	.store	= ldiskfs_attr_store,
};

static struct kobj_type ldiskfs_sb_ktype = {
	.default_attrs	= ldiskfs_attrs,
	.sysfs_ops	= &ldiskfs_attr_ops,
	.release	= ldiskfs_sb_release,
};

static struct kobj_type ldiskfs_feat_ktype = {
	.default_attrs	= ldiskfs_feat_attrs,
	.sysfs_ops	= &ldiskfs_attr_ops,
	.release	= (void (*)(struct kobject *))kfree,
};

static struct kobject *ldiskfs_root;

static struct kobject *ldiskfs_feat;

int ldiskfs_register_sysfs(struct super_block *sb)
{
	struct ldiskfs_sb_info *sbi = LDISKFS_SB(sb);
	int err;

	init_completion(&sbi->s_kobj_unregister);
	err = kobject_init_and_add(&sbi->s_kobj, &ldiskfs_sb_ktype, ldiskfs_root,
				   "%s", sb->s_id);
	if (err) {
		kobject_put(&sbi->s_kobj);
		wait_for_completion(&sbi->s_kobj_unregister);
		return err;
	}

	if (ldiskfs_proc_root)
		sbi->s_proc = proc_mkdir(sb->s_id, ldiskfs_proc_root);
	if (sbi->s_proc) {
		proc_create_single_data("options", S_IRUGO, sbi->s_proc,
				ldiskfs_seq_options_show, sb);
		proc_create_single_data("es_shrinker_info", S_IRUGO,
				sbi->s_proc, ldiskfs_seq_es_shrinker_info_show,
				sb);
		proc_create_seq_data("mb_groups", S_IRUGO, sbi->s_proc,
				&ldiskfs_mb_seq_groups_ops, sb);
		proc_create_data("prealloc_table", S_IRUGO, sbi->s_proc,
				&ldiskfs_seq_prealloc_table_fops, sb);
		proc_create_data("mb_last_group", S_IRUGO, sbi->s_proc,
				&ldiskfs_seq_mb_last_group_fops, sb);
		proc_create_single_data("mb_last_start", S_IRUGO, sbi->s_proc,
				ldiskfs_mb_seq_last_start_seq_show, sb);
		proc_create_data("mb_alloc_stats", S_IFREG | S_IRUGO | S_IWUSR,
				 sbi->s_proc, &ldiskfs_mb_seq_alloc_fops, sb);
	}
	return 0;
}

void ldiskfs_unregister_sysfs(struct super_block *sb)
{
	struct ldiskfs_sb_info *sbi = LDISKFS_SB(sb);

	if (sbi->s_proc)
		remove_proc_subtree(sb->s_id, ldiskfs_proc_root);
	kobject_del(&sbi->s_kobj);
}

int __init ldiskfs_init_sysfs(void)
{
	int ret;

	ldiskfs_root = kobject_create_and_add("ldiskfs", fs_kobj);
	if (!ldiskfs_root)
		return -ENOMEM;

	ldiskfs_feat = kzalloc(sizeof(*ldiskfs_feat), GFP_KERNEL);
	if (!ldiskfs_feat) {
		ret = -ENOMEM;
		goto root_err;
	}

	ret = kobject_init_and_add(ldiskfs_feat, &ldiskfs_feat_ktype,
				   ldiskfs_root, "features");
	if (ret)
		goto feat_err;

	ldiskfs_proc_root = proc_mkdir(proc_dirname, NULL);
	return ret;

feat_err:
	kobject_put(ldiskfs_feat);
	ldiskfs_feat = NULL;
root_err:
	kobject_put(ldiskfs_root);
	ldiskfs_root = NULL;
	return ret;
}

void ldiskfs_exit_sysfs(void)
{
	kobject_put(ldiskfs_feat);
	ldiskfs_feat = NULL;
	kobject_put(ldiskfs_root);
	ldiskfs_root = NULL;
	remove_proc_entry(proc_dirname, NULL);
	ldiskfs_proc_root = NULL;
}

