/*-
 * Copyright (c) 1998, 2001 Nicolas Souchu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: src/sys/dev/iicbus/iicbus.c,v 1.29 2009/02/10 22:50:23 imp Exp $
 */

/*
 * Autoconfiguration and support routines for the Philips serial I2C bus
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/bus.h>

#include <bus/iicbus/iiconf.h>
#include <bus/iicbus/iicbus.h>

#include "iicbus_if.h"

/* DEVTOIICBUS removed: it referenced struct iicbus_device, which no
 * longer exists anywhere in the tree (dead macro since the ivar rework) */

devclass_t iicbus_devclass;

/* See comments below for why auto-scanning is a bad idea. */
#define SCAN_IICBUS 0

/*
 * Device methods
 */
static int iicbus_probe(device_t);
static int iicbus_attach(device_t);
static int iicbus_detach(device_t);
static device_t iicbus_add_child(device_t bus, device_t parent, int order,
		   const char *name, int unit);
static void iicbus_child_detached(device_t bus, device_t child);
static int iicbus_read_ivar(device_t, device_t, int, uintptr_t *);
static int iicbus_write_ivar(device_t, device_t, int, uintptr_t);

static device_method_t iicbus_methods[] = {
        /* device interface */
        DEVMETHOD(device_probe,         iicbus_probe),
        DEVMETHOD(device_attach,        iicbus_attach),
        DEVMETHOD(device_detach,        iicbus_detach),

        /* bus interface */
        DEVMETHOD(bus_add_child,	iicbus_add_child),
	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
        DEVMETHOD(bus_print_child,      bus_generic_print_child),
        DEVMETHOD(bus_child_detached,   iicbus_child_detached),
        DEVMETHOD(bus_read_ivar,        iicbus_read_ivar),
        DEVMETHOD(bus_write_ivar,       iicbus_write_ivar),

	DEVMETHOD(iicbus_transfer,	iicbus_transfer_gen),

        DEVMETHOD_END
};

driver_t iicbus_driver = {
        "iicbus",
        iicbus_methods,
        sizeof(struct iicbus_softc),
};

static int
iicbus_probe(device_t dev)
{

	device_set_desc(dev, "Philips I2C bus");

	/* Allow other subclasses to override this driver. */
	return (BUS_PROBE_GENERIC);
}

#if SCAN_IICBUS
static int
iic_probe_device(device_t dev, u_char addr)
{
	int count;
	char byte;

	if ((addr & 1) == 0) {
		/* is device writable? */
		if (!iicbus_start(dev, addr, 0)) {
			iicbus_stop(dev);
			return (1);
		}
	} else {
		/* is device readable? */
		if (!iicbus_block_read(dev, addr, &byte, 1, &count))
			return (1);
	}

	return (0);
}
#endif

/*
 * We add all the devices which we know about.
 * The generic attach routine will attach them if they are alive.
 */
static int
iicbus_attach(device_t dev)
{
	int error;
#if SCAN_IICBUS
	unsigned char addr;
#endif

	error = iicbus_reset(dev, IIC_FASTEST, 0, NULL);
	if (error)
		return (error);

	/* device probing is meaningless since the bus is supposed to be
	 * hot-plug. Moreover, some I2C chips do not appreciate random
	 * accesses like stop after start to fast, reads for less than
	 * x bytes...
	 */
#if SCAN_IICBUS
	kprintf("Probing for devices on iicbus%d:", device_get_unit(dev));

	/* probe any devices */
	for (addr = 16; addr < 240; addr++) {
		if (iic_probe_device(dev, (u_char)addr)) {
			kprintf(" <%x>", addr);
		}
	}
	kprintf("\n");
#endif

	/*
	 * Create the well-known rendezvous children, GUARDED: children
	 * survive driver detach (devclass_delete_driver() only detaches
	 * them), so an unguarded re-attach leaks a struct bsd_device
	 * trio per unload/reload cycle and mints duplicate iicN/iicsmbN
	 * units (duplicate /dev/iicN nodes on one physical bus).
	 * Route through our own bus_add_child so ivars are allocated.
	 */
	if (device_find_child(dev, "ic", -1) == NULL)
		BUS_ADD_CHILD(dev, dev, 0, "ic", -1);
	if (device_find_child(dev, "iic", -1) == NULL)
		BUS_ADD_CHILD(dev, dev, 0, "iic", -1);
	if (device_find_child(dev, "iicsmb", -1) == NULL)
		BUS_ADD_CHILD(dev, dev, 0, "iicsmb", -1);
#if 0
	/* attach any known device */
	device_add_child(dev, "iic", -1);
#endif
	bus_generic_attach(dev);
         
        return (0);
}

static int
iicbus_detach(device_t dev)
{
	int error;

	/*
	 * DF-5635: a failing child detach must fail OUR detach, else the
	 * bus is left marked detached + driverless with its softc freed
	 * (device_set_driver(NULL) kfrees dev->softc) while the child is
	 * still attached -- the child then derefs
	 * device_get_softc(bus) == NULL in iicbus_request_bus().
	 *
	 * DF-5563 note: the waiter wake/drain this detach also owes
	 * (dying flag + wakeup(sc) + drain loop) is carried by that
	 * finding's fix; both patches compose trivially here.
	 */
	error = iicbus_reset(dev, IIC_FASTEST, 0, NULL);
	if (error)
		return (error);
	error = bus_generic_detach(dev);
	return (error);
}

/*
 * DF-5632: DragonFly's bus_add_child interface is
 *	device_t add_child(device_t bus, device_t parent, int order,
 *			   const char *name, int unit)
 * (sys/kern/bus_if.m:128-134).  The old 4-arg/int-registered prototype
 * made every dispatch misread its arguments (order <- child pointer,
 * name <- order int, unit <- name pointer) and return NULL to callers
 * expecting the new device.  DF-5634: allocate the ivar the generated
 * accessors (iicbus.h:53-56) read/write; free it in child_detached.
 */
static device_t
iicbus_add_child(device_t bus, device_t parent, int order,
		  const char *name, int unit)
{
	struct iicbus_ivar *ivar;
	device_t child;

	child = device_add_child_ordered(parent, order, name, unit);
	if (child == NULL)
		return (NULL);
	ivar = kmalloc(sizeof(*ivar), M_DEVBUF, M_INTWAIT | M_ZERO);
	if (ivar == NULL) {
		device_delete_child(bus, child);
		return (NULL);
	}
	device_set_ivars(child, ivar);
	return (child);
}

static void
iicbus_child_detached(device_t bus, device_t child)
{
	struct iicbus_ivar *ivar = IICBUS_IVAR(child);

	if (ivar != NULL) {
		device_set_ivars(child, NULL);
		kfree(ivar, M_DEVBUF);
	}
}

static int
iicbus_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
{
	struct iicbus_ivar *ivar = IICBUS_IVAR(child);

	switch (index) {
	case IICBUS_IVAR_ADDR:
		*result = (ivar != NULL) ? ivar->addr : 0;
		return (0);
	default:
		return (ENOENT);
	}
}

static int
iicbus_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
{
	struct iicbus_ivar *ivar = IICBUS_IVAR(child);

	switch (index) {
	case IICBUS_IVAR_ADDR:
		if (ivar != NULL)
			ivar->addr = (uint32_t)value;
		return (0);
	default:
		return (ENOENT);
	}
}

int
iicbus_generic_intr(device_t dev, int event, char *buf)
{

	return (0);
}

int
iicbus_null_callback(device_t dev, int index, caddr_t data)
{

	return (0);
}

int
iicbus_null_repeated_start(device_t dev, u_char addr)
{

	return (IIC_ENOTSUPP);
}

DRIVER_MODULE(iicbus, iicbb, iicbus_driver, iicbus_devclass, NULL, NULL);
MODULE_VERSION(iicbus, IICBUS_MODVER);
