#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/io.h>

#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
#include <linux/dma-mapping.h>

#include <plat/regs-spi.h>
#include <plat/regs-dma.h>
#include <mach/dma.h>
#include <plat/dma-plat.h>
#include <mach/spi.h>

struct s3c24xx_spi_dma_devstate {
	unsigned int	hz;
	unsigned int	mode;
	u8		spcon;
	u8		sppre;
};


struct s3c24xx_spi_dma {
	/* bitbang has to be first */
	struct spi_bitbang	 bitbang;
	struct completion	 done;

	void __iomem		*regs;
	int			 dma;
	int			 len;
	int			 count;

	void			(*set_cs)(struct s3c2410_spi_info *spi,
					  int cs, int pol);

	/* data buffers */
	const unsigned char	*tx;
	unsigned char		*rx;

	struct clk		*clk;
	struct resource		*ioarea;
	struct spi_master	*master;
	struct spi_device	*curdev;
	struct device		*dev;
	struct s3c2410_spi_info *pdata;
};

#define SPCON_DEFAULT (/*S3C2410_SPCON_MSTR |*/ S3C2410_SPCON_SMOD_DMA)
#define SPPIN_DEFAULT (S3C2410_SPPIN_KEEP)

static char __initdata banner[] = "S3C24XX SPI driver with DMA\n";

static struct s3c2410_dma_client s3c24xx_spi_dma_dma_client = {
	.name		= "s3c24xx_spi_dma",
};

static inline struct s3c24xx_spi_dma *to_hw(struct spi_device *sdev)
{
	return spi_master_get_devdata(sdev->master);
}

static void s3c24xx_spi_dma_chipsel(struct spi_device *spi, int value)
{
	struct s3c24xx_spi_dma_devstate *cs = spi->controller_state;
	struct s3c24xx_spi_dma *hw = to_hw(spi);
	unsigned int cspol = spi->mode & SPI_CS_HIGH ? 1 : 0;

	/* change the chipselect state and the state of the spi engine clock */

	switch (value) {
	case BITBANG_CS_INACTIVE:
		hw->set_cs(hw->pdata, spi->chip_select, cspol^1);
		writeb(cs->spcon, hw->regs + S3C2410_SPCON);
		break;

	case BITBANG_CS_ACTIVE:
		writeb(cs->spcon | S3C2410_SPCON_ENSCK,
		       hw->regs + S3C2410_SPCON);
		hw->set_cs(hw->pdata, spi->chip_select, cspol);
		break;
	}
}

static void s3c24xx_spi_dma_gpiocs(struct s3c2410_spi_info *spi, int cs, int pol)
{
	/* XXX */
	//gpio_set_value(spi->pin_cs, pol); 
}

static void s3c24xx_spi_dma_initialsetup(struct s3c24xx_spi_dma *hw)
{
	/* for the moment, permanently enable the clock */

	clk_enable(hw->clk);

	/* program defaults into the registers */

	writeb(0xff, hw->regs + S3C2410_SPPRE);
	writeb(SPPIN_DEFAULT, hw->regs + S3C2410_SPPIN);
	writeb(SPCON_DEFAULT, hw->regs + S3C2410_SPCON);

	if (hw->pdata) {
		if (hw->set_cs == s3c24xx_spi_dma_gpiocs)
			//gpio_direction_output(hw->pdata->pin_cs, 1);

		if (hw->pdata->gpio_setup)
			hw->pdata->gpio_setup(hw->pdata, 1);
	}
}

static int s3c24xx_spi_dma_update_state(struct spi_device *spi, struct spi_transfer *t)
{
	struct s3c24xx_spi_dma *hw = to_hw(spi);
	struct s3c24xx_spi_dma_devstate *cs = spi->controller_state;
	unsigned int bpw;
	unsigned int hz;
	unsigned int div;
	unsigned long clk;

	bpw = t ? t->bits_per_word : spi->bits_per_word;
	hz  = t ? t->speed_hz : spi->max_speed_hz;

	if (!bpw)
		bpw = 8;

	if (!hz)
		hz = spi->max_speed_hz;

	if (bpw != 8) {
		dev_err(&spi->dev, "invalid bits-per-word (%d)\n", bpw);
		return -EINVAL;
	}

	if (spi->mode != cs->mode) {
		u8 spcon = SPCON_DEFAULT;

		if (spi->mode & SPI_CPHA)
			spcon |= S3C2410_SPCON_CPHA_FMTB;

		if (spi->mode & SPI_CPOL)
			spcon |= S3C2410_SPCON_CPOL_HIGH;

		cs->mode = spi->mode;
		cs->spcon = spcon;
	}

	if (cs->hz != hz) {
		clk = clk_get_rate(hw->clk);
		printk("CLK is %lu\n", clk);
		div = DIV_ROUND_UP(clk, hz * 2) - 1;

		if (div > 255)
			div = 255;
		printk("Prescaler: %u\n", div);

		dev_dbg(&spi->dev, "pre-scaler=%d (wanted %d, got %ld)\n",
			div, hz, clk / (2 * (div + 1)));

		cs->hz = hz;
		cs->sppre = div;
	}

	return 0;
}

static int s3c24xx_spi_dma_setupxfer(struct spi_device *spi,
				 struct spi_transfer *t)
{
	struct s3c24xx_spi_dma_devstate *cs = spi->controller_state;
	struct s3c24xx_spi_dma *hw = to_hw(spi);
	int ret;

	ret = s3c24xx_spi_dma_update_state(spi, t);
	if (!ret)
		writeb(cs->sppre, hw->regs + S3C2410_SPPRE);

	return ret;
}

static int s3c24xx_spi_dma_setup(struct spi_device *spi)
{
	struct s3c24xx_spi_dma_devstate *cs = spi->controller_state;
	struct s3c24xx_spi_dma *hw = to_hw(spi);
	int ret;

	/* allocate settings on the first call */
	if (!cs) {
		cs = kzalloc(sizeof(struct s3c24xx_spi_dma_devstate), GFP_KERNEL);
		if (!cs) {
			dev_err(&spi->dev, "no memory for controller state\n");
			return -ENOMEM;
		}

		cs->spcon = SPCON_DEFAULT;
		cs->hz = -1;
		spi->controller_state = cs;
	}

	/* initialise the state from the device */
	ret = s3c24xx_spi_dma_update_state(spi, NULL);
	if (ret)
		return ret;

	spin_lock(&hw->bitbang.lock);
	if (!hw->bitbang.busy) {
		hw->bitbang.chipselect(spi, BITBANG_CS_INACTIVE);
		/* need to ndelay for 0.5 clocktick ? */
	}
	spin_unlock(&hw->bitbang.lock);

	return 0;
}

static void s3c24xx_spi_dma_cleanup(struct spi_device *spi)
{
	kfree(spi->controller_state);
}


static int s3c24xx_spi_dma_txrx(struct spi_device *spi, struct spi_transfer *t)
{

	void *buf;
	int result = 0;
	struct s3c24xx_spi_dma *hw;
	dma_addr_t dma_buf;
	if (!t->tx_buf) return t->len;

	buf = (void*)t->tx_buf;
	
	hw = to_hw(spi);

	dev_dbg(&spi->dev, "txrx: tx %p, rx %p, len %d\n",
		t->tx_buf, t->rx_buf, t->len);

	hw->tx = t->tx_buf;
	hw->rx = t->rx_buf;
	hw->len = t->len;
	hw->count = 0;
	
	init_completion(&hw->done);

	dma_buf = dma_map_single(hw->dev, (void*)t->tx_buf, t->len, DMA_TO_DEVICE);
	
	if (dma_mapping_error(hw->dev, dma_buf)) {
		result = -ENOMEM;
		goto out;
	}
	
	s3c2410_dma_devconfig(DMACH_SPI0, S3C2410_DMASRC_MEM, S3C24XX_PA_SPI + S3C2410_SPTDAT);

	result = s3c2410_dma_enqueue(DMACH_SPI0, spi, dma_buf, t->len);
	
	if (result) {
		goto err_enqueue;
	}
	wait_for_completion(&hw->done);
	result = hw->count;

err_enqueue:
	dma_unmap_single(hw->dev, dma_buf, t->len, DMA_TO_DEVICE);
out:
	return result;
}

static void s3c24xx_spi_dma_dma_done(struct s3c2410_dma_chan *dma_ch,
				     void *buf_id, int size,
				     enum s3c2410_dma_buffresult result)
{
	struct spi_device *spi = buf_id;
	struct s3c24xx_spi_dma *hw = to_hw(spi);
	if (result == S3C2410_RES_OK) {
		hw->count = size;
	} else {
		hw->count = -EIO;
	}
	complete(&hw->done);
}

static int __init s3c24xx_spi_dma_probe(struct platform_device *pdev)
{
	struct s3c2410_spi_info *pdata;
	struct s3c24xx_spi_dma *hw;
	struct spi_master *master;
	struct resource *res;
	int err = 0;
	
	printk(banner);

	master = spi_alloc_master(&pdev->dev, sizeof(struct s3c24xx_spi_dma));
	if (master == NULL) {
		dev_err(&pdev->dev, "No memory for spi_master\n");
		err = -ENOMEM;
		goto err_nomem;
	}

	hw = spi_master_get_devdata(master);
	memset(hw, 0, sizeof(struct s3c24xx_spi_dma));

	hw->master = spi_master_get(master);
	hw->pdata = pdata = pdev->dev.platform_data;
	hw->dev = &pdev->dev;

	if (pdata == NULL) {
		dev_err(&pdev->dev, "No platform data supplied\n");
		err = -ENOENT;
		goto err_no_pdata;
	}

	platform_set_drvdata(pdev, hw);
	init_completion(&hw->done);

	/* setup the master state. */

	/* the spi->mode bits understood by this driver: */
	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;

	master->num_chipselect = hw->pdata->num_cs;
	master->bus_num = pdata->bus_num;

	/* setup the state for the bitbang driver */

	hw->bitbang.master         = hw->master;
	hw->bitbang.setup_transfer = s3c24xx_spi_dma_setupxfer;
	hw->bitbang.chipselect     = s3c24xx_spi_dma_chipsel;
	hw->bitbang.txrx_bufs      = s3c24xx_spi_dma_txrx;

	hw->master->setup  = s3c24xx_spi_dma_setup;
	hw->master->cleanup = s3c24xx_spi_dma_cleanup;

	dev_dbg(hw->dev, "bitbang at %p\n", &hw->bitbang);

	/* find and map our resources */

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (res == NULL) {
		dev_err(&pdev->dev, "Cannot get IORESOURCE_MEM\n");
		err = -ENOENT;
		goto err_no_iores;
	}

	hw->ioarea = request_mem_region(res->start, resource_size(res),
					pdev->name);

	if (hw->ioarea == NULL) {
		dev_err(&pdev->dev, "Cannot reserve region\n");
		err = -ENXIO;
		goto err_no_iores;
	}

	hw->regs = ioremap(res->start, resource_size(res));
	if (hw->regs == NULL) {
		dev_err(&pdev->dev, "Cannot map IO\n");
		err = -ENXIO;
		goto err_no_iomap;
	}


	hw->dma = s3c2410_dma_request(DMACH_SPI0, &s3c24xx_spi_dma_dma_client, hw->dev);
	if (hw->dma < 0) {
		dev_err(&pdev->dev, "cannot get DMA channel.\n");
		err = -EBUSY;
		goto err_no_dma;
	}
		
	s3c2410_dma_config(DMACH_SPI0, 1);
	s3c2410_dma_set_buffdone_fn(DMACH_SPI0, s3c24xx_spi_dma_dma_done);
	s3c2410_dma_setflags(DMACH_SPI0, S3C2410_DMAF_AUTOSTART);

	hw->clk = clk_get(&pdev->dev, "spi");
	if (IS_ERR(hw->clk)) {
		dev_err(&pdev->dev, "No clock for device\n");
		err = PTR_ERR(hw->clk);
		goto err_no_clk;
	}

	/* setup any gpio we can */

	if (1 || !pdata->set_cs) { /* XXX always use our CS routine */
		if (pdata->pin_cs < 0) {
			dev_err(&pdev->dev, "No chipselect pin\n");
			goto err_register;
		}

		err = gpio_request(pdata->pin_cs, dev_name(&pdev->dev));
		if (err) {
			dev_err(&pdev->dev, "Failed to get gpio for cs\n");
			goto err_register;
		}

		hw->set_cs = s3c24xx_spi_dma_gpiocs;
		//gpio_direction_output(pdata->pin_cs, 1); /* XXX do not set nSS as output */
	} else {
		hw->set_cs = pdata->set_cs;
	}

	s3c24xx_spi_dma_initialsetup(hw);

	/* register our spi controller */

	err = spi_bitbang_start(&hw->bitbang);
	if (err) {
		dev_err(&pdev->dev, "Failed to register SPI master\n");
		goto err_register;
	}

	return 0;

 err_register:
	if (hw->set_cs == s3c24xx_spi_dma_gpiocs)
		gpio_free(pdata->pin_cs);

	clk_disable(hw->clk);
	clk_put(hw->clk);

 err_no_clk:
	s3c2410_dma_free(DMACH_SPI0, &s3c24xx_spi_dma_dma_client);

 err_no_dma:
	iounmap(hw->regs);

 err_no_iomap:
	release_resource(hw->ioarea);
	kfree(hw->ioarea);

 err_no_iores:
 err_no_pdata:
	spi_master_put(hw->master);

 err_nomem:
	return err;
}


static int __exit s3c24xx_spi_dma_remove(struct platform_device *dev)
{
	struct s3c24xx_spi_dma *hw = platform_get_drvdata(dev);

	platform_set_drvdata(dev, NULL);

	spi_unregister_master(hw->master);

	clk_disable(hw->clk);
	clk_put(hw->clk);

	s3c2410_dma_free(DMACH_SPI0, &s3c24xx_spi_dma_dma_client);
	iounmap(hw->regs);

	if (hw->set_cs == s3c24xx_spi_dma_gpiocs)
		gpio_free(hw->pdata->pin_cs);

	release_resource(hw->ioarea);
	kfree(hw->ioarea);

	spi_master_put(hw->master);
	return 0;
}

MODULE_ALIAS("platform:s3c2410-spi");

static struct platform_driver s3c24xx_spi_dma_driver = {
	.remove		= __exit_p(s3c24xx_spi_dma_remove),
	.driver		= {
		.name	= "s3c2410-spi",
		.owner	= THIS_MODULE,
	},
};

static int __init s3c24xx_spi_dma_init(void)
{
        return platform_driver_probe(&s3c24xx_spi_dma_driver, s3c24xx_spi_dma_probe);
}

static void __exit s3c24xx_spi_dma_exit(void)
{
        platform_driver_unregister(&s3c24xx_spi_dma_driver);
}


module_init(s3c24xx_spi_dma_init);
module_exit(s3c24xx_spi_dma_exit);

MODULE_DESCRIPTION("S3C24XX SPI Driver with DMA");
MODULE_AUTHOR("Andrey Demenev, <demenev@gmail.com>");
MODULE_LICENSE("GPL");

