/* SPDX-License-Identifier: GPL-2.0 */

#ifndef __LINUX_GPIO_GENERIC_H
#define __LINUX_GPIO_GENERIC_H

#include <linux/cleanup.h>
#include <linux/gpio/driver.h>
#include <linux/spinlock.h>

struct device;

#define GPIO_GENERIC_BIG_ENDIAN			BIT(0)
#define GPIO_GENERIC_UNREADABLE_REG_SET		BIT(1) 
#define GPIO_GENERIC_UNREADABLE_REG_DIR		BIT(2) 
#define GPIO_GENERIC_BIG_ENDIAN_BYTE_ORDER	BIT(3)
#define GPIO_GENERIC_READ_OUTPUT_REG_SET	BIT(4) 
#define GPIO_GENERIC_NO_OUTPUT			BIT(5) 
#define GPIO_GENERIC_NO_SET_ON_INPUT		BIT(6)
#define GPIO_GENERIC_PINCTRL_BACKEND		BIT(7) 
#define GPIO_GENERIC_NO_INPUT			BIT(8) 


struct gpio_generic_chip_config {
	struct device *dev;
	unsigned long sz;
	void __iomem *dat;
	void __iomem *set;
	void __iomem *clr;
	void __iomem *dirout;
	void __iomem *dirin;
	unsigned long flags;
};


struct gpio_generic_chip {
	struct gpio_chip gc;
	unsigned long (*read_reg)(void __iomem *reg);
	void (*write_reg)(void __iomem *reg, unsigned long data);
	bool be_bits;
	void __iomem *reg_dat;
	void __iomem *reg_set;
	void __iomem *reg_clr;
	void __iomem *reg_dir_out;
	void __iomem *reg_dir_in;
	bool dir_unreadable;
	bool pinctrl;
	int bits;
	raw_spinlock_t lock;
	unsigned long sdata;
	unsigned long sdir;
};

static inline struct gpio_generic_chip *
to_gpio_generic_chip(struct gpio_chip *gc)
{
	return container_of(gc, struct gpio_generic_chip, gc);
}

int gpio_generic_chip_init(struct gpio_generic_chip *chip,
			   const struct gpio_generic_chip_config *cfg);


static inline int
gpio_generic_chip_set(struct gpio_generic_chip *chip, unsigned int offset,
		      int value)
{
	if (WARN_ON(!chip->gc.set))
		return -EOPNOTSUPP;

	return chip->gc.set(&chip->gc, offset, value);
}


static inline unsigned long
gpio_generic_read_reg(struct gpio_generic_chip *chip, void __iomem *reg)
{
	if (WARN_ON(!chip->read_reg))
		return 0;

	return chip->read_reg(reg);
}


static inline void gpio_generic_write_reg(struct gpio_generic_chip *chip,
					  void __iomem *reg, unsigned long val)
{
	if (WARN_ON(!chip->write_reg))
		return;

	chip->write_reg(reg, val);
}

#define gpio_generic_chip_lock(gen_gc) \
	raw_spin_lock(&(gen_gc)->lock)

#define gpio_generic_chip_unlock(gen_gc) \
	raw_spin_unlock(&(gen_gc)->lock)

#define gpio_generic_chip_lock_irqsave(gen_gc, flags) \
	raw_spin_lock_irqsave(&(gen_gc)->lock, flags)

#define gpio_generic_chip_unlock_irqrestore(gen_gc, flags) \
	raw_spin_unlock_irqrestore(&(gen_gc)->lock, flags)

DEFINE_LOCK_GUARD_1(gpio_generic_lock,
		    struct gpio_generic_chip,
		    gpio_generic_chip_lock(_T->lock),
		    gpio_generic_chip_unlock(_T->lock))

DEFINE_LOCK_GUARD_1(gpio_generic_lock_irqsave,
		    struct gpio_generic_chip,
		    gpio_generic_chip_lock_irqsave(_T->lock, _T->flags),
		    gpio_generic_chip_unlock_irqrestore(_T->lock, _T->flags),
		    unsigned long flags)

#endif 
