/* Shared Code for OmniVision Camera Chip Drivers
 *
 * Copyright (c) 2003 Mark McClelland <mark@alpha.dyndns.org>
 * http://alpha.dyndns.org/ov511/
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 */

#include <linux/config.h>
#include <linux/version.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "ovsensor.h"

#define DRIVER_VERSION "v2.22"
#define DRIVER_AUTHOR "Mark McClelland <mark@alpha.dyndns.org>"
#define DRIVER_DESC "OV camera chip I2C driver"

static int debug;
MODULE_PARM(debug, "i");
MODULE_PARM_DESC(debug,
  "Debug level: 0=none, 1=inits, 2=warning, 3=config, 4=functions, 5=max");

static int mono;
MODULE_PARM(mono, "i");
MODULE_PARM_DESC(mono,
  "Treat sensor as a monochrome (OVx1xx) device");

MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
#if defined(MODULE_LICENSE)	/* Introduced in ~2.4.10 */
MODULE_LICENSE("GPL");
#endif

/* Registers common to all sensors, that are needed for detection */
#define GENERIC_REG_ID_HIGH       0x1C	/* manufacturer ID MSB */
#define GENERIC_REG_ID_LOW        0x1D	/* manufacturer ID LSB */
#define GENERIC_REG_COM_I         0x29	/* misc settings */

extern struct ovsensor_ops ov6x20_ops;
extern struct ovsensor_ops ov6x30_ops;
extern struct ovsensor_ops ov7x10_ops;
extern struct ovsensor_ops ov7x20_ops;
extern struct ovsensor_ops ov76be_ops;

static char *sen_names[NUM_SEN_TYPES] = {
	[SEN_UNKNOWN]	= "Unknown sensor",
	[SEN_OV76BE]	= "OV76BE",
	[SEN_OV7610]	= "OV7610",
	[SEN_OV7620]	= "OV7620",
	[SEN_OV7620AE]	= "OV7620AE",
	[SEN_OV6620]	= "OV6620",
	[SEN_OV6630]	= "OV6630",
	[SEN_OV6630AE]	= "OV6630AE",
	[SEN_OV6630AF]	= "OV6630AF",
};

/* Prototypes */
static struct i2c_driver driver;
static struct i2c_client client_template;

/* ----------------------------------------------------------------------- */

int
ov_write_regvals(struct i2c_client *client, struct ovsensor_regvals *rvals)
{
	int rc;

	while (rvals->reg != 0xff) {
		rc = ov_write(client, rvals->reg, rvals->val);
		if (rc < 0)
			return rc;
		rvals++;
	}

	return 0;
}

/* Writes bits at positions specified by mask to an I2C reg. Bits that are in
 * the same position as 1's in "mask" are cleared and set to "value". Bits
 * that are in the same position as 0's in "mask" are preserved, regardless
 * of their respective state in "value".
 */
int
ov_write_mask(struct i2c_client *client,
	      unsigned char reg,
	      unsigned char value,
	      unsigned char mask)
{
	int rc;
	unsigned char oldval, newval;

	if (mask == 0xff) {
		newval = value;
	} else {
		rc = ov_read(client, reg, &oldval);
		if (rc < 0)
			return rc;

		oldval &= (~mask);		/* Clear the masked bits */
		value &= mask;			/* Enforce mask on value */
		newval = oldval | value;	/* Set the desired bits */
	}

	return ov_write(client, reg, newval);
}

/* ----------------------------------------------------------------------- */

/* Reset the sensor and ensure that I2C is synchronized. Returns <0 if failure.
 */
int
init_ov_sensor(struct i2c_client *client)
{
	int i, success;
	unsigned char high, low;

	/* Reset the sensor */
	ov_write(client, 0x12, 0x80);

	/* Wait for it to initialize */
	set_current_state(TASK_UNINTERRUPTIBLE);
	schedule_timeout(1 + 150 * HZ / 1000);

	for (i = 0, success = 0; i < I2C_DETECT_RETRIES && !success; i++) {
		if (ov_read(client, GENERIC_REG_ID_HIGH, &high) >= 0) {
			if (ov_read(client, GENERIC_REG_ID_LOW, &low) >= 0) {
				if (high == 0x7F && low == 0xA2) {
					success = 1;
					continue;
				}
			}
		}

		/* Reset the sensor */
		ov_write(client, 0x12, 0x80);

		/* Wait for it to initialize */
		set_current_state(TASK_UNINTERRUPTIBLE);
		schedule_timeout(1 + 150 * HZ / 1000);

		/* Dummy read to sync I2C */
		ov_read(client, 0x00, &low);
	}

	if (!success)
		return -EIO;

	PDEBUG(1, "I2C synced in %d attempt(s)", i);

	return 0;
}

/* This detect the OV7610, OV7620, or OV76BE sensor. */
static int
ov7xx0_detect(struct i2c_client *c)
{
	struct ovsensor *ov = c->data;
	int rc;
	unsigned char val;

	PDEBUG(4, "");

	/* Detect sensor (sub)type */
	rc = ov_read(c, GENERIC_REG_COM_I, &val);
	if (rc < 0) {
		err("Error detecting sensor type");
		return rc;
	} 

	if ((val & 3) == 3) {
		info("Sensor is an OV7610");
		ov->subtype = SEN_OV7610;
	} else if ((val & 3) == 1) {
		rc = ov_read(c, 0x15, &val);
		if (rc < 0) {
			err("Error detecting sensor type");
			return rc;
		} 

		if (val & 1) {
			info("Sensor is an OV7620AE");
			/* OV7620 is a close enough match for now. There are
			 * some definite differences though, so this should be
			 * fixed */
			ov->subtype = SEN_OV7620;
		} else {
			info("Sensor is an OV76BE");
			ov->subtype = SEN_OV76BE;
		}
	} else if ((val & 3) == 0) {
		info("Sensor is an OV7620");
		ov->subtype = SEN_OV7620;
	} else {
		err("Unknown image sensor version: %d", val & 3);
		return -1;
	}

	if (ov->mono && ov->subtype != SEN_OV7620)
		warn("Warning: monochrome mode not supported with this sensor");

	if (ov->subtype == SEN_OV76BE)
		ov->sops = &ov76be_ops;
	else if (ov->subtype == SEN_OV7620)
		ov->sops = &ov7x20_ops;
	else
		ov->sops = &ov7x10_ops;

	return 0;
}

/* This detects the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
static int
ov6xx0_detect(struct i2c_client *c)
{
	struct ovsensor *ov = c->data;
	int rc;
	unsigned char val;

	PDEBUG(4, "");

	/* Detect sensor (sub)type */
	rc = ov_read(c, GENERIC_REG_COM_I, &val);
	if (rc < 0) {
		err("Error detecting sensor type");
		return -1;
	}

	if ((val & 3) == 0) {
		ov->subtype = SEN_OV6630;
		info("Sensor is an OV6630");
	} else if ((val & 3) == 1) {
		ov->subtype = SEN_OV6620;
		info("Sensor is an OV6620");
	} else if ((val & 3) == 2) {
		ov->subtype = SEN_OV6630;
		info("Sensor is an OV6630AE");
	} else if ((val & 3) == 3) {
		ov->subtype = SEN_OV6630;
		info("Sensor is an OV6630AF");
	}

	/* None of the subtypes supports monochrome mode yet */
	if (ov->mono)
		warn("Warning: monochrome mode not supported with this sensor");

	if (ov->subtype == SEN_OV6620)
		ov->sops = &ov6x20_ops;
	else
		ov->sops = &ov6x30_ops;

	return 0;
}

/* This will be moved to ovsensor.c soon */
static int
ovsensor_detect(struct i2c_client *c)
{
	/* Ideally we would just try a single register write and see if it NAKs.
	 * That isn't possible since the OV518 can't report I2C transaction
	 * failures. So, we have to try to initialize the sensor (i.e. reset it
	 * and check the ID registers) to detect its presence. */

	/* Test for 7xx0 */
	PDEBUG(3, "Testing for 0V7xx0");
	c->addr = OV7xx0_SID;
	if (init_ov_sensor(c) < 0) {
		/* Test for 6xx0 */
		PDEBUG(3, "Testing for 0V6xx0");
		c->addr = OV6xx0_SID;
		if (init_ov_sensor(c) < 0) {
 				return -ENODEV;
		} else {
			if (ov6xx0_detect(c) < 0) {
				err("Failed to init OV6xx0");
 				return -EIO;
			}
		}
	} else {
		if (ov7xx0_detect(c) < 0) {
			err("Failed to init OV7xx0");
 			return -EIO;
		}
	}

	return 0;
}

static int ovsensor_attach(struct i2c_adapter *adap)
{
	int rc = 0;
	struct ovsensor *ov;
	struct i2c_client *client;

	/* I2C is not a PnP bus, so we can never be certain that we're talking
	 * to the right chip. To prevent damage to EEPROMS and such, only
	 * attach to adapters that are known to contain OV camera chips. */

	switch (adap->id) {
	case (I2C_ALGO_SMBUS | I2C_HW_SMBUS_OV511):
	case (I2C_ALGO_SMBUS | I2C_HW_SMBUS_OV518):
	case (I2C_ALGO_SMBUS | I2C_HW_SMBUS_OVFX2):
		PDEBUG(1, "Adapter ID 0x%06x accepted", adap->id);
		break;
	default:
		PDEBUG(1, "Adapter ID 0x%06x rejected", adap->id);
		return -ENODEV;
	}

	client = kmalloc(sizeof *client, GFP_KERNEL);
	if (!client) {
		rc = -ENOMEM;
		goto no_client;
	}
	
	memcpy(client, &client_template, sizeof *client);
	client->adapter = adap;
	strcpy(client->name, "OV????");

	client->data = ov = kmalloc(sizeof *ov, GFP_KERNEL);
	if (!ov) {
		rc = -ENOMEM;
		goto no_ov;
	}

	memset(ov, 0, sizeof *ov);
	ov->mono = mono;

	rc = ovsensor_detect(client);
	if (rc < 0)
		goto error;

	strcpy(client->name, sen_names[ov->subtype]);

	/* Do the subtype's register init and allocate its memory */
	rc = ov->sops->configure(client);
	if (rc < 0)
		goto error;

	MOD_INC_USE_COUNT;

	PDEBUG(1, "initialized");

	i2c_attach_client(client);

	return rc;
error:
	kfree(ov);
no_ov:
	kfree(client);
no_client:
	PDEBUG(1, "returning %d", rc);
	return rc;
}

static int ovsensor_detach(struct i2c_client *client)
{
	struct ovsensor *ov = client->data;
	int rc;

	rc = ov->sops->unconfigure(client);
	if (rc < 0)
		return rc;

	i2c_detach_client(client);

	kfree(ov);
	kfree(client);
	MOD_DEC_USE_COUNT;
	return 0;
}

static int ovsensor_command(struct i2c_client *client,
			    unsigned int cmd, void *arg)
{
	struct ovsensor *ov = client->data;

	switch (cmd) {
	case OVSENSOR_CMD_Q_SUBTYPE:
		*(int *)arg = ov->subtype;
		return 0;
	default:
		return ov->sops->command(client, cmd, arg);
	}
}

/* ----------------------------------------------------------------------- */

static struct i2c_driver driver = {
	.name =			"ovsensor",
	.id =			I2C_DRIVERID_OVSENSOR,
	.flags =		I2C_DF_NOTIFY,
	.attach_adapter =	ovsensor_attach,
	.detach_client =	ovsensor_detach,
	.command =		ovsensor_command,
};

static struct i2c_client client_template = {
	.name =		"(unset)",
	.id =		-1,
	.driver =	&driver
};

EXPORT_NO_SYMBOLS;

static int __init
ovsensor_init(void)
{
	info(DRIVER_VERSION " : " DRIVER_DESC);
	return i2c_add_driver(&driver);
}

static void __exit
ovsensor_exit(void)
{
	i2c_del_driver(&driver);
}

module_init(ovsensor_init);
module_exit(ovsensor_exit);
