// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2023 CERN (home.cern)

/*
 * Author: Vaibhav Gupta <vaibhav.gupta@cern.ch>
 *
 * Hardware Monitoring for fd-dev
 */

#include <linux/hwmon.h>
#include "fine-delay.h"

#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,10,0)

static umode_t fd_hwmon_temp_is_visible(const void *_data,
				  enum hwmon_sensor_types type, u32 attr,
				  int channel)
{
	return 0444;
}

static int fd_hwmon_temp_read(struct device *dev, enum hwmon_sensor_types type,
				u32 attr, int channel, long *val)
{
	struct fd_dev *fd = dev_get_drvdata(dev);

	switch(attr) {
		case hwmon_temp_min:
			*val = 0;
			return 0;

		case hwmon_temp_max:
			*val = 60*1000;
			return 0;

		case hwmon_temp_crit:
			*val = 100*1000;
			return 0;
	}

	if (fd->temp_ready) {
		*val = (long)(fd->temp * 1000 / 16);
	} else {
		dev_err(dev, "Could not read temperature: %d", -EIO);
		return -EIO;
	}

	return 0;
}

static int fd_hwmon_temp_sensor_id_read(struct device *dev,
				   enum hwmon_sensor_types type,
				   u32 attr, int channel, const char **str)
{
	struct fd_dev *fd = dev_get_drvdata(dev);

	*str = fd->hwmon_temp_sensor_id;

	return 0;
}

static const struct hwmon_channel_info *fd_hwmon_info[] = {
	HWMON_CHANNEL_INFO(temp, HWMON_T_INPUT | HWMON_T_LABEL | HWMON_T_MIN |
			   HWMON_T_MAX | HWMON_T_CRIT),
	NULL
};

static const struct hwmon_ops fd_hwmon_temp_ops = {
	.is_visible = fd_hwmon_temp_is_visible,
	.read = fd_hwmon_temp_read,
	.read_string = fd_hwmon_temp_sensor_id_read
};

static const struct hwmon_chip_info fd_hwmon_temp_chip_info = {
	.ops = &fd_hwmon_temp_ops,
	.info = fd_hwmon_info,
};

int fd_hwmon_init(struct fd_dev *fd)
{
	struct device *dev = &fd->pdev->dev;

	fd->hwmon_dev = devm_hwmon_device_register_with_info(dev,
							     "FMC_Fine_Delay_1NS_8CHA",
							     fd,
							     &fd_hwmon_temp_chip_info,
							     NULL);
	if(!IS_ERR(fd->hwmon_dev)) {
		fd->hwmon_temp_sensor_id = devm_kasprintf(fd->hwmon_dev,
							  GFP_KERNEL,
							  "Temperature [%s]",
							  dev_name(&fd->slot->dev));
		if(!fd->hwmon_temp_sensor_id) {
			devm_hwmon_device_unregister(dev);
			return -ENOMEM;
		}

		return 0;
	}

	return PTR_ERR(fd->hwmon_dev);
}

#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(5,10,0) */
