// SPDX-License-Identifier: GPL-2.0 OR MIT
/*
 * Intel Xe I2C attached Microcontroller Units (MCU)
 *
 * Copyright (C) 2025 Intel Corporation.
 */

#include <drm/drm_print.h>
#include <linux/array_size.h>
#include <linux/container_of.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <linux/regmap.h>
#include <linux/sprintf.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/workqueue.h>

#include <linux/designware_i2c.h>

#include "regs/xe_i2c_regs.h"
#include "regs/xe_irq_regs.h"

#include "xe_amc.h"
#include "xe_device.h"
#include "xe_i2c.h"
#include "xe_mmio.h"
#include "xe_sriov.h"
#include "xe_survivability_mode.h"

/**
 * DOC: Xe I2C devices
 *
 * Register a platform device for the I2C host controller (Synpsys DesignWare
 * I2C) if the registers of that controller are mapped to the MMIO, and also the
 * I2C client device for the Add-In Management Controller (the MCU) attached to
 * the host controller.
 *
 * See drivers/i2c/busses/i2c-designware-* for more information on the I2C host
 * controller.
 */

static const char adapter_name[] = "i2c_designware";

static const struct property_entry xe_i2c_adapter_properties[] = {
	PROPERTY_ENTRY_STRING("compatible", "intel,xe-i2c"),
	PROPERTY_ENTRY_U32("clock-frequency", I2C_MAX_FAST_MODE_PLUS_FREQ),
	{ }
};

static inline void xe_i2c_read_endpoint(struct xe_mmio *mmio, void *ep)
{
	u32 *val = ep;

	val[0] = xe_mmio_read32(mmio, REG_SG_REMAP_ADDR_PREFIX);
	val[1] = xe_mmio_read32(mmio, REG_SG_REMAP_ADDR_POSTFIX);
}

static void xe_i2c_handle_smbus_alert(struct xe_i2c *i2c)
{
	u32 stat;

	stat = xe_mmio_read32(i2c->mmio, I2C_REG(DW_IC_SMBUS_INTR_STAT));
	if (!stat)
		return;

	xe_mmio_write32(i2c->mmio, I2C_REG(DW_IC_CLR_SMBUS_INTR), stat);

	if (stat & DW_IC_SMBUS_INTR_ALERT && i2c->amc)
		xe_amc_handle_alert(i2c);
	else
		xe_mmio_rmw32(i2c->mmio, I2C_CONFIG_CMD, PCI_COMMAND_INTX_DISABLE, 0);
}

static void xe_i2c_client_work(struct work_struct *work)
{
	struct xe_i2c *i2c = container_of(work, struct xe_i2c, work);
	struct i2c_board_info info = {
		.type	= "amc",
		.flags	= I2C_CLIENT_HOST_NOTIFY,
		.addr	= i2c->ep.addr[XE_I2C_CLIENT_AMC],
	};

	i2c->client[XE_I2C_CLIENT_AMC] = i2c_new_client_device(i2c->adapter, &info);
}

static int xe_i2c_notifier(struct notifier_block *nb, unsigned long action, void *data)
{
	struct xe_i2c *i2c = container_of(nb, struct xe_i2c, bus_notifier);
	struct i2c_adapter *adapter = i2c_verify_adapter(data);
	struct device *dev = data;

	if (action == BUS_NOTIFY_ADD_DEVICE &&
	    adapter && dev->parent == &i2c->pdev->dev) {
		i2c->adapter = adapter;
		schedule_work(&i2c->work);
		return NOTIFY_OK;
	}

	return NOTIFY_DONE;
}

static int xe_i2c_register_adapter(struct xe_i2c *i2c)
{
	struct pci_dev *pci = to_pci_dev(i2c->drm_dev);
	struct platform_device *pdev;
	int ret;
	u32 id;

	id = (pci_domain_nr(pci->bus) << 16) | pci_dev_id(pci);

	/*
	 * Not using platform_device_register_full() here because we don't have
	 * a handle to the platform_device before it returns. xe_i2c_notifier()
	 * uses that handle, but it may be called before
	 * platform_device_register_full() is done.
	 */
	pdev = platform_device_alloc(adapter_name, id);
	if (!pdev)
		return -ENOMEM;

	ret = device_create_managed_software_node(&pdev->dev,
						  xe_i2c_adapter_properties,
						  NULL);
	if (ret)
		goto err_pdev_put;

	pdev->dev.parent = i2c->drm_dev;
	i2c->pdev = pdev;

	ret = platform_device_add(pdev);
	if (ret)
		goto err_pdev_put;

	return 0;

err_pdev_put:
	platform_device_put(pdev);

	return ret;
}

static void xe_i2c_unregister_adapter(struct xe_i2c *i2c)
{
	platform_device_unregister(i2c->pdev);
}

/**
 * xe_i2c_present - I2C controller is present and functional
 * @xe: xe device instance
 *
 * Check whether the I2C controller is present and functioning with valid
 * endpoint cookie.
 *
 * Return: %true if present, %false otherwise.
 */
bool xe_i2c_present(struct xe_device *xe)
{
	return xe->i2c && xe->i2c->ep.cookie == XE_I2C_EP_COOKIE_DEVICE;
}

static bool xe_i2c_irq_present(struct xe_device *xe)
{
	return xe->i2c && xe->i2c->ep.capabilities & XE_I2C_EP_CAP_IRQ &&
		!xe_survivability_mode_is_boot_enabled(xe);
}

/**
 * xe_i2c_irq_handler: Handler for I2C interrupts
 * @xe: xe device instance
 * @master_ctl: interrupt register
 *
 * Forward interrupts generated by the I2C host adapter to the I2C host adapter
 * driver.
 */
void xe_i2c_irq_handler(struct xe_device *xe, u32 master_ctl)
{
	if (!(master_ctl & I2C_IRQ) || !xe_i2c_irq_present(xe))
		return;

	xe_i2c_handle_smbus_alert(xe->i2c);
}

void xe_i2c_irq_reset(struct xe_device *xe)
{
	struct xe_mmio *mmio = xe_root_tile_mmio(xe);

	if (!xe_i2c_irq_present(xe))
		return;

	xe_mmio_rmw32(mmio, I2C_CONFIG_CMD, 0, PCI_COMMAND_INTX_DISABLE);
	xe_mmio_rmw32(mmio, I2C_BRIDGE_PCICFGCTL, ACPI_INTR_EN, 0);
}

void xe_i2c_irq_postinstall(struct xe_device *xe)
{
	struct xe_mmio *mmio = xe_root_tile_mmio(xe);

	if (!xe_i2c_irq_present(xe))
		return;

	xe_mmio_rmw32(mmio, I2C_BRIDGE_PCICFGCTL, 0, ACPI_INTR_EN);
	xe_mmio_rmw32(mmio, I2C_CONFIG_CMD, PCI_COMMAND_INTX_DISABLE, 0);
}

/* See "Disabling DW_apb_i2c" in the DesignWare DW_abp_i2c databook. */
static void xe_i2c_disable(struct xe_i2c *i2c)
{
	int timeout = 100;
	u32 status;

	xe_mmio_rmw32(i2c->mmio, I2C_REG(DW_IC_ENABLE), DW_IC_ENABLE_ENABLE, 0);

	do {
		status = xe_mmio_read32(i2c->mmio, I2C_REG(DW_IC_ENABLE_STATUS));
		if (!(status & DW_IC_ENABLE_ENABLE))
			return;
		/* Can't sleep here. */
		udelay(25);
	} while (timeout--);

	dev_warn(i2c->drm_dev, "timeout in disabling i2c adapter\n");
}

static int xe_i2c_read(void *context, unsigned int reg, unsigned int *val)
{
	struct xe_i2c *i2c = context;

	*val = xe_mmio_read32(i2c->mmio, I2C_REG(reg));

	switch (reg) {
	case DW_IC_ENABLE:
	case DW_IC_ENABLE_STATUS:
		FIELD_MODIFY(DW_IC_ENABLE_ENABLE, val,
			     i2c->ic_enable & DW_IC_ENABLE_ENABLE);
		break;
	default:
		break;
	}

	return 0;
}

static int xe_i2c_write(void *context, unsigned int reg, unsigned int val)
{
	struct xe_i2c *i2c = context;

	switch (reg) {
	case DW_IC_CON:
	case DW_IC_TAR:
	case DW_IC_SAR:
		/* Disable the controller. */
		xe_i2c_disable(i2c);

		/* Write the register. */
		xe_mmio_write32(i2c->mmio, I2C_REG(reg), val);

		/* Enable the controller. */
		xe_mmio_rmw32(i2c->mmio, I2C_REG(DW_IC_ENABLE), 0, DW_IC_ENABLE_ENABLE);
		return 0;
	case DW_IC_ENABLE:
		i2c->ic_enable = val;
		/* Other fields can be updated except the enable bit. */
		val |= DW_IC_ENABLE_ENABLE;
		break;
	case DW_IC_SMBUS_INTR_MASK:
		/* Make sure the Alert is never masked. */
		val |= DW_IC_SMBUS_INTR_ALERT;
		break;
	default:
		break;
	}

	xe_mmio_write32(i2c->mmio, I2C_REG(reg), val);
	return 0;
}

static const struct regmap_config i2c_regmap_config = {
	.reg_bits = 32,
	.val_bits = 32,
	.reg_read = xe_i2c_read,
	.reg_write = xe_i2c_write,
	.fast_io = true,
};

void xe_i2c_pm_suspend(struct xe_device *xe)
{
	struct xe_mmio *mmio = xe_root_tile_mmio(xe);

	if (!xe_i2c_present(xe))
		return;

	xe_mmio_rmw32(mmio, I2C_CONFIG_PMCSR, PCI_PM_CTRL_STATE_MASK, (__force u32)PCI_D3hot);
	drm_dbg(&xe->drm, "pmcsr: 0x%08x\n", xe_mmio_read32(mmio, I2C_CONFIG_PMCSR));
}

void xe_i2c_pm_resume(struct xe_device *xe, bool d3cold)
{
	struct xe_mmio *mmio = xe_root_tile_mmio(xe);

	if (!xe_i2c_present(xe))
		return;

	if (d3cold)
		xe_mmio_rmw32(mmio, I2C_CONFIG_CMD, 0, PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);

	xe_mmio_rmw32(mmio, I2C_CONFIG_PMCSR, PCI_PM_CTRL_STATE_MASK, (__force u32)PCI_D0);
	drm_dbg(&xe->drm, "pmcsr: 0x%08x\n", xe_mmio_read32(mmio, I2C_CONFIG_PMCSR));
}

static void xe_i2c_remove(void *data)
{
	struct xe_i2c *i2c = data;
	struct xe_device *xe = tile_to_xe(i2c->mmio->tile);
	unsigned int i;

	xe_i2c_irq_reset(xe);
	xe_amc_exit(i2c);

	/* Stop the notifier from arming the client work before teardown. */
	bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier);
	cancel_work_sync(&i2c->work);

	for (i = 0; i < XE_I2C_MAX_CLIENTS; i++) {
		i2c_unregister_device(i2c->client[i]);
		i2c->client[i] = NULL;
	}

	xe_i2c_unregister_adapter(i2c);
	xe->i2c = NULL;
}

/**
 * xe_i2c_probe: Probe the I2C host adapter and the I2C clients attached to it
 * @xe: xe device instance
 *
 * Register all the I2C devices described in the I2C Endpoint data structure.
 *
 * Return: 0 on success, error code on failure
 */
int xe_i2c_probe(struct xe_device *xe)
{
	struct device *drm_dev = xe->drm.dev;
	struct xe_i2c_endpoint ep;
	struct regmap *regmap;
	struct xe_i2c *i2c;
	int ret;

	if (!xe->info.has_i2c)
		return 0;

	xe_i2c_read_endpoint(xe_root_tile_mmio(xe), &ep);
	if (ep.cookie != XE_I2C_EP_COOKIE_DEVICE)
		return 0;

	i2c = devm_kzalloc_obj(drm_dev, *i2c);
	if (!i2c)
		return -ENOMEM;

	INIT_WORK(&i2c->work, xe_i2c_client_work);
	i2c->mmio = xe_root_tile_mmio(xe);
	i2c->drm_dev = drm_dev;
	i2c->ep = ep;
	xe->i2c = i2c;

	/* PCI PM isn't aware of this device, bring it up and match it with SGUnit state. */
	xe_i2c_pm_resume(xe, true);

	regmap = devm_regmap_init(drm_dev, NULL, i2c, &i2c_regmap_config);
	if (IS_ERR(regmap))
		return PTR_ERR(regmap);

	i2c->bus_notifier.notifier_call = xe_i2c_notifier;
	ret = bus_register_notifier(&i2c_bus_type, &i2c->bus_notifier);
	if (ret)
		return ret;

	ret = xe_i2c_register_adapter(i2c);
	if (ret) {
		bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier);
		return ret;
	}

	ret = xe_amc_init(i2c);
	if (ret) {
		xe_i2c_remove(i2c);
		return ret;
	}

	xe_i2c_irq_postinstall(xe);
	return devm_add_action_or_reset(drm_dev, xe_i2c_remove, i2c);
}