Home | History | Annotate | Line # | Download | only in i2c
      1 /*	$NetBSD: i2c.c,v 1.105 2025/09/23 06:28:20 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2021, 2022, 2025 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * Copyright (c) 2003 Wasabi Systems, Inc.
     31  * All rights reserved.
     32  *
     33  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
     34  *
     35  * Redistribution and use in source and binary forms, with or without
     36  * modification, are permitted provided that the following conditions
     37  * are met:
     38  * 1. Redistributions of source code must retain the above copyright
     39  *    notice, this list of conditions and the following disclaimer.
     40  * 2. Redistributions in binary form must reproduce the above copyright
     41  *    notice, this list of conditions and the following disclaimer in the
     42  *    documentation and/or other materials provided with the distribution.
     43  * 3. All advertising materials mentioning features or use of this software
     44  *    must display the following acknowledgement:
     45  *      This product includes software developed for the NetBSD Project by
     46  *      Wasabi Systems, Inc.
     47  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
     48  *    or promote products derived from this software without specific prior
     49  *    written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     53  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     54  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
     55  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     56  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     57  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     58  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     59  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     60  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     61  * POSSIBILITY OF SUCH DAMAGE.
     62  */
     63 
     64 #ifdef _KERNEL_OPT
     65 #include "opt_i2c.h"
     66 
     67 #include "opt_fdt.h"
     68 #ifdef FDT
     69 #define	I2C_USE_FDT
     70 #endif /* FDT */
     71 
     72 #if defined(__aarch64__) || defined(__amd64__)
     73 #include "acpica.h"
     74 #if NACPICA > 0
     75 #define	I2C_USE_ACPI
     76 #endif /* NACPICA > 0 */
     77 #endif /* __aarch64__ || __amd64__ */
     78 
     79 #endif /* _KERNEL_OPT */
     80 
     81 #include <sys/cdefs.h>
     82 __KERNEL_RCSID(0, "$NetBSD: i2c.c,v 1.105 2025/09/23 06:28:20 thorpej Exp $");
     83 
     84 #include <sys/param.h>
     85 #include <sys/systm.h>
     86 #include <sys/device.h>
     87 #include <sys/event.h>
     88 #include <sys/conf.h>
     89 #include <sys/malloc.h>
     90 #include <sys/kmem.h>
     91 #include <sys/kthread.h>
     92 #include <sys/proc.h>
     93 #include <sys/kernel.h>
     94 #include <sys/fcntl.h>
     95 #include <sys/module.h>
     96 #include <sys/once.h>
     97 #include <sys/mutex.h>
     98 
     99 #ifdef I2C_USE_ACPI
    100 #include <dev/acpi/acpivar.h>
    101 #include <dev/acpi/acpi_i2c.h>
    102 #endif /* I2C_USE_ACPI */
    103 
    104 #ifdef I2C_USE_FDT
    105 #include <dev/fdt/fdtvar.h>
    106 #include <dev/fdt/fdt_i2c.h>
    107 #endif /* I2C_USE_FDT */
    108 
    109 #include <dev/i2c/i2cvar.h>
    110 #include <dev/i2c/i2c_calls.h>
    111 
    112 #include "ioconf.h"
    113 #include "locators.h"
    114 
    115 #ifndef I2C_MAX_ADDR
    116 #define I2C_MAX_ADDR	0x3ff	/* 10-bit address, max */
    117 #endif
    118 
    119 /* Everything projected by iic_softc::sc_device_state_lock */
    120 struct i2c_device {
    121 	LIST_ENTRY(i2c_device)	d_link;
    122 	device_t		d_dev;
    123 	i2c_addr_t		d_addr;
    124 	int			d_flags;
    125 #define	ID_F_DIRECT		__BIT(0)
    126 #define	ID_F_BUSY		__BIT(1)
    127 #define	ID_F_WAIT_BUSY		__BIT(2)
    128 };
    129 
    130 struct iic_softc {
    131 	device_t sc_dev;
    132 	i2c_tag_t sc_tag;
    133 	kmutex_t sc_device_state_lock;
    134 	kcondvar_t sc_device_state_cond;
    135 	LIST_HEAD(, i2c_device) sc_devices;
    136 };
    137 
    138 static dev_type_open(iic_open);
    139 static dev_type_close(iic_close);
    140 static dev_type_ioctl(iic_ioctl);
    141 
    142 int iic_init(void);
    143 
    144 kmutex_t iic_mtx;
    145 int iic_refcnt;
    146 
    147 ONCE_DECL(iic_once);
    148 
    149 const struct cdevsw iic_cdevsw = {
    150 	.d_open = iic_open,
    151 	.d_close = iic_close,
    152 	.d_read = noread,
    153 	.d_write = nowrite,
    154 	.d_ioctl = iic_ioctl,
    155 	.d_stop = nostop,
    156 	.d_tty = notty,
    157 	.d_poll = nopoll,
    158 	.d_mmap = nommap,
    159 	.d_kqfilter = nokqfilter,
    160 	.d_discard = nodiscard,
    161 	.d_flag = D_OTHER
    162 };
    163 
    164 static void
    165 iic_device_wait(struct iic_softc *sc, struct i2c_device *d)
    166 {
    167 	KASSERT(mutex_owned(&sc->sc_device_state_lock));
    168 
    169 	while (d->d_flags & ID_F_BUSY) {
    170 		d->d_flags |= ID_F_WAIT_BUSY;
    171 		cv_wait(&sc->sc_device_state_cond, &sc->sc_device_state_lock);
    172 	}
    173 }
    174 
    175 static struct i2c_device *
    176 iic_device_lookup_addr(struct iic_softc *sc, i2c_addr_t addr, bool wait_busy)
    177 {
    178 	struct i2c_device *d;
    179 
    180 	KASSERT(mutex_owned(&sc->sc_device_state_lock));
    181 
    182 	LIST_FOREACH(d, &sc->sc_devices, d_link) {
    183 		if (d->d_addr == addr) {
    184 			if (wait_busy) {
    185 				iic_device_wait(sc, d);
    186 			}
    187 			return d;
    188 		}
    189 	}
    190 	return NULL;
    191 }
    192 
    193 static struct i2c_device *
    194 iic_device_lookup_dev(struct iic_softc *sc, device_t dev)
    195 {
    196 	struct i2c_device *d;
    197 
    198 	KASSERT(mutex_owned(&sc->sc_device_state_lock));
    199 
    200 	LIST_FOREACH(d, &sc->sc_devices, d_link) {
    201 		if (d->d_dev == dev) {
    202 			iic_device_wait(sc, d);
    203 			return d;
    204 		}
    205 	}
    206 	return NULL;
    207 }
    208 
    209 static struct i2c_device *
    210 iic_device_alloc(i2c_addr_t addr, int flags)
    211 {
    212 	struct i2c_device *d = kmem_zalloc(sizeof(*d), KM_SLEEP);
    213 	d->d_addr = addr;
    214 	d->d_flags = flags;
    215 
    216 	return d;
    217 }
    218 
    219 static inline void
    220 iic_device_free(struct i2c_device *d)
    221 {
    222 	kmem_free(d, sizeof(*d));
    223 }
    224 
    225 #define	ID_F_KEEPALIVE_MASK	(ID_F_DIRECT | ID_F_BUSY | ID_F_WAIT_BUSY)
    226 
    227 static void
    228 iic_device_release_and_unlock(struct iic_softc *sc, struct i2c_device *d)
    229 {
    230 	KASSERT(mutex_owned(&sc->sc_device_state_lock));
    231 
    232 	if (d->d_dev == NULL &&
    233 	    (d->d_flags & ID_F_KEEPALIVE_MASK) == 0) {
    234 		LIST_REMOVE(d, d_link);
    235 	} else {
    236 		if (d->d_flags & ID_F_WAIT_BUSY) {
    237 			d->d_flags &= ~ID_F_WAIT_BUSY;
    238 			cv_broadcast(&sc->sc_device_state_cond);
    239 		}
    240 		d = NULL;
    241 	}
    242 	mutex_exit(&sc->sc_device_state_lock);
    243 
    244 	if (d != NULL) {
    245 		iic_device_free(d);
    246 	}
    247 }
    248 
    249 /*
    250  * iic_addr_reserve --
    251  *	Mark an I2C address as reserved by an attach attempt.
    252  *	This is a short-lived state.
    253  */
    254 static bool
    255 iic_addr_reserve(struct iic_softc *sc, i2c_addr_t addr, int flags)
    256 {
    257 	struct i2c_device *d, *newd;
    258 	bool rv = true;
    259 
    260 	flags = (flags & ID_F_DIRECT) | ID_F_BUSY;
    261 	newd = iic_device_alloc(addr, flags);
    262 
    263 	mutex_enter(&sc->sc_device_state_lock);
    264 	d = iic_device_lookup_addr(sc, addr, true);
    265 	if (d == NULL) {
    266 		LIST_INSERT_HEAD(&sc->sc_devices, newd, d_link);
    267 		newd = NULL;
    268 		mutex_exit(&sc->sc_device_state_lock);
    269 	} else {
    270 		if (d->d_dev != NULL ||
    271 		    ((d->d_flags & ID_F_DIRECT) != 0 &&
    272 		     (     flags & ID_F_DIRECT) == 0)) {
    273 			rv = false;
    274 		} else {
    275 			d->d_flags |= flags;
    276 		}
    277 		iic_device_release_and_unlock(sc, d);
    278 	}
    279 
    280 	if (newd != NULL) {
    281 		kmem_free(newd, sizeof(*newd));
    282 	}
    283 	return rv;
    284 }
    285 
    286 /*
    287  * iic_addr_claim --
    288  *	Claim an I2C address for a device.  The address must already
    289  *	be reserved.
    290  */
    291 static void
    292 iic_addr_claim(struct iic_softc *sc, i2c_addr_t addr, device_t dev)
    293 {
    294 	struct i2c_device *d;
    295 
    296 	mutex_enter(&sc->sc_device_state_lock);
    297 	d = iic_device_lookup_addr(sc, addr, false);
    298 	KASSERT(d != NULL);
    299 	KASSERT(d->d_dev == NULL);
    300 	KASSERT(d->d_flags & ID_F_BUSY);
    301 	d->d_dev = dev;
    302 	d->d_flags &= ~ID_F_BUSY;
    303 	iic_device_release_and_unlock(sc, d);
    304 }
    305 
    306 /*
    307  * iic_addr_release --
    308  *	Release an I2C address.  Address must have been previously
    309  *	reserved but not claimed.
    310  */
    311 static void
    312 iic_addr_release(struct iic_softc *sc, i2c_addr_t addr)
    313 {
    314 	struct i2c_device *d;
    315 
    316 	mutex_enter(&sc->sc_device_state_lock);
    317 	d = iic_device_lookup_addr(sc, addr, false);
    318 	KASSERT(d != NULL);
    319 	KASSERT(d->d_dev == NULL);
    320 	KASSERT(d->d_flags & ID_F_BUSY);
    321 	d->d_flags &= ~ID_F_BUSY;
    322 	iic_device_release_and_unlock(sc, d);
    323 }
    324 
    325 /*
    326  * iic_addr_release_device --
    327  *	Release an I2C address by device.
    328  */
    329 static void
    330 iic_addr_release_device(struct iic_softc *sc, device_t dev)
    331 {
    332 	struct i2c_device *d;
    333 
    334 	mutex_enter(&sc->sc_device_state_lock);
    335 	d = iic_device_lookup_dev(sc, dev);
    336 	KASSERT(d != NULL);
    337 	d->d_dev = NULL;
    338 	iic_device_release_and_unlock(sc, d);
    339 }
    340 
    341 static int
    342 iic_print_direct(void *aux, const char *pnp)
    343 {
    344 	struct i2c_attach_args *ia = aux;
    345 
    346 	if (pnp != NULL) {
    347 		aprint_normal("%s%s%s%s at %s addr 0x%02x",
    348 			      ia->ia_name ? ia->ia_name : "(unknown)",
    349 			      ia->ia_clist ? " (" : "",
    350 			      ia->ia_clist ? ia->ia_clist : "",
    351 			      ia->ia_clist ? ")" : "",
    352 			      pnp, ia->ia_addr);
    353 	} else {
    354 		aprint_normal(" addr 0x%02x", ia->ia_addr);
    355 	}
    356 
    357 	return UNCONF;
    358 }
    359 
    360 static int
    361 iic_print(void *aux, const char *pnp)
    362 {
    363 	struct i2c_attach_args *ia = aux;
    364 
    365 	if (ia->ia_addr != (i2c_addr_t)IICCF_ADDR_DEFAULT)
    366 		aprint_normal(" addr 0x%02x", ia->ia_addr);
    367 
    368 	return UNCONF;
    369 }
    370 
    371 static bool
    372 iic_is_special_address(i2c_addr_t addr)
    373 {
    374 
    375 	/*
    376 	 * See: https://www.i2c-bus.org/addressing/
    377 	 */
    378 
    379 	/* General Call (read) / Start Byte (write) */
    380 	if (addr == 0x00)
    381 		return (true);
    382 
    383 	/* CBUS Addresses */
    384 	if (addr == 0x01)
    385 		return (true);
    386 
    387 	/* Reserved for Different Bus Formats */
    388 	if (addr == 0x02)
    389 		return (true);
    390 
    391 	/* Reserved for future purposes */
    392 	if (addr == 0x03)
    393 		return (true);
    394 
    395 	/* High Speed Master Code */
    396 	if ((addr & 0x7c) == 0x04)
    397 		return (true);
    398 
    399 	/* 10-bit Slave Addressing prefix */
    400 	if ((addr & 0x7c) == 0x78)
    401 		return (true);
    402 
    403 	/* Reserved for future purposes */
    404 	if ((addr & 0x7c) == 0x7c)
    405 		return (true);
    406 
    407 	return (false);
    408 }
    409 
    410 static int
    411 iic_probe_none(struct iic_softc *sc,
    412 	       const struct i2c_attach_args *ia, int flags)
    413 {
    414 
    415 	return (0);
    416 }
    417 
    418 static int
    419 iic_probe_smbus_quick_write(struct iic_softc *sc,
    420 			    const struct i2c_attach_args *ia, int flags)
    421 {
    422 	int error;
    423 
    424 	if ((error = iic_acquire_bus(ia->ia_tag, flags)) == 0) {
    425 		error = iic_smbus_quick_write(ia->ia_tag, ia->ia_addr, flags);
    426 	}
    427 	(void) iic_release_bus(ia->ia_tag, flags);
    428 
    429 	return (error);
    430 }
    431 
    432 static int
    433 iic_probe_smbus_receive_byte(struct iic_softc *sc,
    434 			     const struct i2c_attach_args *ia, int flags)
    435 {
    436 	int error;
    437 
    438 	if ((error = iic_acquire_bus(ia->ia_tag, flags)) == 0) {
    439 		uint8_t dummy;
    440 
    441 		error = iic_smbus_receive_byte(ia->ia_tag, ia->ia_addr,
    442 					       &dummy, flags);
    443 	}
    444 	(void) iic_release_bus(ia->ia_tag, flags);
    445 
    446 	return (error);
    447 }
    448 
    449 static bool
    450 iic_indirect_driver_is_permitted(struct iic_softc *sc, cfdata_t cf)
    451 {
    452 	prop_object_iterator_t iter;
    453 	prop_array_t permitlist;
    454 	prop_string_t pstr;
    455 	prop_type_t ptype;
    456 	bool rv = false;
    457 
    458 	permitlist = prop_dictionary_get(device_properties(sc->sc_dev),
    459 					 I2C_PROP_INDIRECT_DEVICE_PERMITLIST);
    460 	if (permitlist == NULL) {
    461 		/* No permitlist -> everything allowed */
    462 		return (true);
    463 	}
    464 
    465 	if ((ptype = prop_object_type(permitlist)) != PROP_TYPE_ARRAY) {
    466 		aprint_error_dev(sc->sc_dev,
    467 		    "invalid property type (%d) for '%s'; must be array (%d)\n",
    468 		    ptype, I2C_PROP_INDIRECT_DEVICE_PERMITLIST,
    469 		    PROP_TYPE_ARRAY);
    470 		return (false);
    471 	}
    472 
    473 	iter = prop_array_iterator(permitlist);
    474 	while ((pstr = prop_object_iterator_next(iter)) != NULL) {
    475 		if (prop_string_equals_string(pstr, cf->cf_name)) {
    476 			rv = true;
    477 			break;
    478 		}
    479 	}
    480 	prop_object_iterator_release(iter);
    481 
    482 	return (rv);
    483 }
    484 
    485 static int
    486 iic_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
    487 {
    488 	struct iic_softc *sc = device_private(parent);
    489 	int (*probe_func)(struct iic_softc *,
    490 			  const struct i2c_attach_args *, int);
    491 	prop_string_t pstr;
    492 	i2c_addr_t first_addr, last_addr;
    493 
    494 	/*
    495 	 * Before we do any more work, consult the allowed-driver
    496 	 * permit-list for this bus (if any).
    497 	 */
    498 	if (iic_indirect_driver_is_permitted(sc, cf) == false)
    499 		return (0);
    500 
    501 	/* default to "quick write". */
    502 	probe_func = iic_probe_smbus_quick_write;
    503 
    504 	pstr = prop_dictionary_get(device_properties(sc->sc_dev),
    505 				   I2C_PROP_INDIRECT_PROBE_STRATEGY);
    506 	if (pstr == NULL) {
    507 		/* Use the default. */
    508 	} else if (prop_string_equals_string(pstr,
    509 					I2C_PROBE_STRATEGY_QUICK_WRITE)) {
    510 		probe_func = iic_probe_smbus_quick_write;
    511 	} else if (prop_string_equals_string(pstr,
    512 					I2C_PROBE_STRATEGY_RECEIVE_BYTE)) {
    513 		probe_func = iic_probe_smbus_receive_byte;
    514 	} else if (prop_string_equals_string(pstr,
    515 					I2C_PROBE_STRATEGY_NONE)) {
    516 		probe_func = iic_probe_none;
    517 	} else {
    518 		aprint_error_dev(sc->sc_dev,
    519 			"unknown probe strategy '%s'; defaulting to '%s'\n",
    520 			prop_string_value(pstr),
    521 			I2C_PROBE_STRATEGY_QUICK_WRITE);
    522 
    523 		/* Use the default. */
    524 	}
    525 
    526 	struct i2c_attach_args ia = {
    527 		.ia_tag = sc->sc_tag,
    528 	};
    529 
    530 	if (cf->cf_loc[IICCF_ADDR] == IICCF_ADDR_DEFAULT) {
    531 		/*
    532 		 * This particular config directive has
    533 		 * wildcarded the address, so we will
    534 		 * scan the entire bus for it.
    535 		 */
    536 		first_addr = 0;
    537 		last_addr = I2C_MAX_ADDR;
    538 	} else {
    539 		/*
    540 		 * This config directive hard-wires the i2c
    541 		 * bus address for the device, so there is
    542 		 * no need to go poking around at any other
    543 		 * addresses.
    544 		 */
    545 		if (cf->cf_loc[IICCF_ADDR] < 0 ||
    546 		    cf->cf_loc[IICCF_ADDR] > I2C_MAX_ADDR) {
    547 			/* Invalid config directive! */
    548 			return (0);
    549 		}
    550 		first_addr = last_addr = cf->cf_loc[IICCF_ADDR];
    551 	}
    552 
    553 	for (ia.ia_addr = first_addr; ia.ia_addr <= last_addr; ia.ia_addr++) {
    554 		int error, match_result;
    555 		device_t newdev;
    556 
    557 		/*
    558 		 * Skip I2C addresses that are reserved for
    559 		 * special purposes.
    560 		 */
    561 		if (iic_is_special_address(ia.ia_addr))
    562 			continue;
    563 
    564 		/*
    565 		 * Skip addresses where a device is already attached
    566 		 * or that's reserved for direct-configuration.
    567 		 */
    568 		if (! iic_addr_reserve(sc, ia.ia_addr, 0))
    569 			continue;
    570 
    571 		/*
    572 		 * Call the "match" routine for the device.  If that
    573 		 * returns success, then call the probe strategy
    574 		 * function.
    575 		 *
    576 		 * We do it in this order because i2c devices tend
    577 		 * to be found at a small number of possible addresses
    578 		 * (e.g. read-time clocks that are only ever found at
    579 		 * 0x68).  This gives the driver a chance to skip any
    580 		 * address that are not valid for the device, saving
    581 		 * us from having to poke at the bus to see if anything
    582 		 * is there.
    583 		 */
    584 		match_result = config_probe(parent, cf, &ia);/*XXX*/
    585 		if (match_result <= 0) {
    586 			iic_addr_release(sc, ia.ia_addr);
    587 			continue;
    588 		}
    589 
    590 		/*
    591 		 * If the quality of the match by the driver was low
    592 		 * (i.e. matched on being a valid address only, didn't
    593 		 * perform any hardware probe), invoke our probe routine
    594 		 * to see if it looks like something is really there.
    595 		 */
    596 		if (match_result == I2C_MATCH_ADDRESS_ONLY &&
    597 		    (error = (*probe_func)(sc, &ia, 0)) != 0) {
    598 			iic_addr_release(sc, ia.ia_addr);
    599 			continue;
    600 		}
    601 
    602 		newdev = config_attach(parent, cf, &ia, iic_print, CFARGS_NONE);
    603 		if (newdev != NULL) {
    604 			iic_addr_claim(sc, ia.ia_addr, newdev);
    605 		} else {
    606 			iic_addr_release(sc, ia.ia_addr);
    607 		}
    608 	}
    609 
    610 	return 0;
    611 }
    612 
    613 static void
    614 iic_child_detach(device_t parent, device_t child)
    615 {
    616 	struct iic_softc *sc = device_private(parent);
    617 
    618 	iic_addr_release_device(sc, child);
    619 }
    620 
    621 static int
    622 iic_rescan(device_t self, const char *ifattr, const int *locators)
    623 {
    624 	config_search(self, NULL,
    625 	    CFARGS(.search = iic_search,
    626 		   .locators = locators));
    627 	return 0;
    628 }
    629 
    630 static int
    631 iic_match(device_t parent, cfdata_t cf, void *aux)
    632 {
    633 
    634 	return 1;
    635 }
    636 
    637 static void
    638 iic_attach_child_direct(struct iic_softc *sc, struct i2c_attach_args *ia)
    639 {
    640 	device_t newdev;
    641 	int loc[IICCF_NLOCS] = {
    642 		[IICCF_ADDR] = ia->ia_addr,
    643 	};
    644 
    645 	if (ia->ia_addr > I2C_MAX_ADDR) {
    646 		aprint_error_dev(sc->sc_dev,
    647 		    "WARNING: ignoring bad device address @ 0x%x\n",
    648 		    ia->ia_addr);
    649 		return;
    650 	}
    651 
    652 	if (! iic_addr_reserve(sc, ia->ia_addr, ID_F_DIRECT)) {
    653 		return;
    654 	}
    655 
    656 	newdev = config_found(sc->sc_dev, ia, iic_print_direct,
    657 	    CFARGS(.submatch = config_stdsubmatch,
    658 		   .locators = loc,
    659 		   .devhandle = ia->ia_devhandle));
    660 	if (newdev != NULL) {
    661 		iic_addr_claim(sc, ia->ia_addr, newdev);
    662 	} else {
    663 		iic_addr_release(sc, ia->ia_addr);
    664 	}
    665 }
    666 
    667 static bool
    668 i2c_enumerate_devices_callback(device_t self,
    669     struct i2c_enumerate_devices_args *args)
    670 {
    671 	struct iic_softc *sc = device_private(self);
    672 
    673 	iic_attach_child_direct(sc, args->ia);
    674 
    675 	return true;				/* keep enumerating */
    676 }
    677 
    678 static bool
    679 iic_attach_children_direct(struct iic_softc *sc)
    680 {
    681 	device_t parent = device_parent(sc->sc_dev);
    682 	prop_array_t child_devices;
    683 	bool no_indirect_config;
    684 
    685 	child_devices = prop_dictionary_get(device_properties(parent),
    686 					    "i2c-child-devices");
    687 	if (!prop_dictionary_get_bool(device_properties(parent),
    688 				      "i2c-no-indirect-config",
    689 				      &no_indirect_config)) {
    690 		no_indirect_config = false;
    691 	}
    692 
    693 	if (child_devices != NULL) {
    694 		no_indirect_config = true;
    695 	}
    696 
    697 	/*
    698 	 * If no explicit child device array is provided, then attempt
    699 	 * to enumerate i2c devices using the platform device tree.
    700 	 */
    701 	struct i2c_attach_args ia = {
    702 		.ia_tag = sc->sc_tag,
    703 	};
    704 	if (child_devices == NULL) {
    705 		struct i2c_enumerate_devices_args enumargs = {
    706 			.ia = &ia,
    707 			.callback = i2c_enumerate_devices_callback,
    708 		};
    709 		if (device_call(sc->sc_dev,
    710 				I2C_ENUMERATE_DEVICES(&enumargs)) == 0) {
    711 			no_indirect_config = true;
    712 		}
    713 		goto done;
    714 	}
    715 
    716 	/*
    717 	 * We have an explicit child device array to enumerate.
    718 	 */
    719 	prop_object_iterator_t iter = prop_array_iterator(child_devices);
    720 	prop_dictionary_t dev;
    721 
    722 	while ((dev = prop_object_iterator_next(iter)) != NULL) {
    723 		const void *vptr;
    724 		size_t vsize;
    725 
    726 		if (!prop_dictionary_get_uint16(dev, "addr", &ia.ia_addr)) {
    727 			continue;
    728 		}
    729 
    730 		if (!prop_dictionary_get_string(dev, "name", &ia.ia_name)) {
    731 			/* "name" property is optional. */
    732 			ia.ia_name = NULL;
    733 		}
    734 
    735 		if (!prop_dictionary_get_data(dev, "compatible",
    736 					      (const void **)&ia.ia_clist,
    737 					      &ia.ia_clist_size)) {
    738 			ia.ia_clist = NULL;
    739 			ia.ia_clist_size = 0;
    740 		}
    741 
    742 		if (!prop_dictionary_get_data(dev, "devhandle",
    743 					      &vptr, &vsize)) {
    744 			vptr = NULL;
    745 		} else if (vsize != sizeof(ia.ia_devhandle)) {
    746 			vptr = NULL;
    747 		}
    748 		if (vptr != NULL) {
    749 			memcpy(&ia.ia_devhandle, vptr,
    750 			    sizeof(ia.ia_devhandle));
    751 		} else {
    752 			ia.ia_devhandle = devhandle_invalid();
    753 		}
    754 
    755 		if ((ia.ia_name == NULL && ia.ia_clist == NULL) ||
    756 		    ia.ia_addr > I2C_MAX_ADDR) {
    757 			aprint_error_dev(sc->sc_dev,
    758 			    "WARNING: ignoring bad child device entry "
    759 			    "for address 0x%x\n", ia.ia_addr);
    760 			continue;
    761 		}
    762 
    763 		iic_attach_child_direct(sc, &ia);
    764 	}
    765 	prop_object_iterator_release(iter);
    766 
    767  done:
    768 	/*
    769 	 * We return "true" if we want to let indirect configuration
    770 	 * proceed.
    771 	 */
    772 	return !no_indirect_config;
    773 }
    774 
    775 static void
    776 iic_attach(device_t parent, device_t self, void *aux)
    777 {
    778 	struct iic_softc *sc = device_private(self);
    779 	devhandle_t devhandle = device_handle(self);
    780 	struct i2cbus_attach_args *iba = aux;
    781 
    782 	aprint_naive("\n");
    783 	aprint_normal(": I2C bus\n");
    784 
    785 	sc->sc_dev = self;
    786 	sc->sc_tag = iba->iba_tag;
    787 
    788 	LIST_INIT(&sc->sc_devices);
    789 	cv_init(&sc->sc_device_state_cond, "i2cdevst");
    790 	mutex_init(&sc->sc_device_state_lock, MUTEX_DEFAULT, IPL_NONE);
    791 
    792 	if (!pmf_device_register(self, NULL, NULL))
    793 		aprint_error_dev(self, "couldn't establish power handler\n");
    794 
    795 	/* XXX There ought to be a generic way to do this. */
    796 	switch (devhandle_type(devhandle)) {
    797 #ifdef I2C_USE_ACPI
    798 	case DEVHANDLE_TYPE_ACPI:
    799 		acpi_i2c_register(self, sc->sc_tag);
    800 		break;
    801 #endif
    802 #ifdef I2C_USE_FDT
    803 	case DEVHANDLE_TYPE_OF:
    804 		fdtbus_register_i2c_controller(self, sc->sc_tag);
    805 		break;
    806 #endif
    807 	default:
    808 		break;
    809 	}
    810 
    811 	if (iic_attach_children_direct(sc)) {
    812 		/*
    813 		 * Attach all i2c devices described in the kernel
    814 		 * configuration file.
    815 		 */
    816 		iic_rescan(self, "iic", NULL);
    817 	}
    818 }
    819 
    820 static int
    821 iic_detach(device_t self, int flags)
    822 {
    823 	int error;
    824 
    825 	error = config_detach_children(self, flags);
    826 	if (error)
    827 		return error;
    828 
    829 	pmf_device_deregister(self);
    830 
    831 	return 0;
    832 }
    833 
    834 /*
    835  * iic_compatible_match --
    836  *	Match a device's "compatible" property against the list
    837  *	of compatible strings provided by the driver.
    838  */
    839 int
    840 iic_compatible_match(const struct i2c_attach_args *ia,
    841 		     const struct device_compatible_entry *compats)
    842 {
    843 	int match_result;
    844 
    845 	match_result = device_compatible_match_strlist(ia->ia_clist,
    846 	    ia->ia_clist_size, compats);
    847 	if (match_result) {
    848 		match_result =
    849 		    MIN(I2C_MATCH_DIRECT_COMPATIBLE + match_result - 1,
    850 			I2C_MATCH_DIRECT_COMPATIBLE_MAX);
    851 	}
    852 
    853 	return match_result;
    854 }
    855 
    856 /*
    857  * iic_compatible_lookup --
    858  *	Look the compatible entry that matches one of the driver's
    859  *	"compatible" strings.  The first match is returned.
    860  */
    861 const struct device_compatible_entry *
    862 iic_compatible_lookup(const struct i2c_attach_args *ia,
    863 		      const struct device_compatible_entry *compats)
    864 {
    865 	return device_compatible_lookup_strlist(ia->ia_clist,
    866 	    ia->ia_clist_size, compats);
    867 }
    868 
    869 /*
    870  * iic_use_direct_match --
    871  *	Helper for direct-config of i2c.  Returns true if this is
    872  *	a direct-config situation, along with match result.
    873  *	Returns false if the driver should use indirect-config
    874  *	matching logic.
    875  */
    876 bool
    877 iic_use_direct_match(const struct i2c_attach_args *ia, const cfdata_t cf,
    878 		     const struct device_compatible_entry *compats,
    879 		     int *match_resultp)
    880 {
    881 	KASSERT(match_resultp != NULL);
    882 
    883 	if (ia->ia_name != NULL &&
    884 	    strcmp(ia->ia_name, cf->cf_name) == 0) {
    885 		*match_resultp = I2C_MATCH_DIRECT_SPECIFIC;
    886 		return true;
    887 	}
    888 
    889 	if (ia->ia_clist != NULL && ia->ia_clist_size != 0) {
    890 		*match_resultp = iic_compatible_match(ia, compats);
    891 		return true;
    892 	}
    893 
    894 	return false;
    895 }
    896 
    897 static int
    898 iic_open(dev_t dev, int flag, int fmt, lwp_t *l)
    899 {
    900 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
    901 
    902 	mutex_enter(&iic_mtx);
    903 	if (sc == NULL) {
    904 		mutex_exit(&iic_mtx);
    905 		return ENXIO;
    906 	}
    907 	iic_refcnt++;
    908 	mutex_exit(&iic_mtx);
    909 
    910 	return 0;
    911 }
    912 
    913 static int
    914 iic_close(dev_t dev, int flag, int fmt, lwp_t *l)
    915 {
    916 
    917 	mutex_enter(&iic_mtx);
    918 	iic_refcnt--;
    919 	mutex_exit(&iic_mtx);
    920 
    921 	return 0;
    922 }
    923 
    924 static int
    925 iic_ioctl_exec(struct iic_softc *sc, i2c_ioctl_exec_t *iie, int flag)
    926 {
    927 	i2c_tag_t ic = sc->sc_tag;
    928 	uint8_t *buf = NULL;
    929 	void *cmd = NULL;
    930 	int error = 0;
    931 
    932 	/* Validate parameters */
    933 	if (iie->iie_addr > I2C_MAX_ADDR)
    934 		return EINVAL;
    935 	if (iie->iie_cmdlen > I2C_EXEC_MAX_CMDLEN ||
    936 	    iie->iie_buflen > I2C_EXEC_MAX_BUFLEN)
    937 		return EINVAL;
    938 	if (iie->iie_cmd != NULL && iie->iie_cmdlen == 0)
    939 		return EINVAL;
    940 	if (iie->iie_buf != NULL && iie->iie_buflen == 0)
    941 		return EINVAL;
    942 	if (I2C_OP_WRITE_P(iie->iie_op) && (flag & FWRITE) == 0)
    943 		return EBADF;
    944 
    945 #if 0
    946 	/* Disallow userspace access to devices that have drivers attached. */
    947 	/* XXX */
    948 #endif
    949 
    950 	if (iie->iie_cmd != NULL) {
    951 		cmd = kmem_alloc(iie->iie_cmdlen, KM_SLEEP);
    952 		error = copyin(iie->iie_cmd, cmd, iie->iie_cmdlen);
    953 		if (error)
    954 			goto out;
    955 	}
    956 
    957 	if (iie->iie_buf != NULL) {
    958 		buf = kmem_alloc(iie->iie_buflen, KM_SLEEP);
    959 		if (I2C_OP_WRITE_P(iie->iie_op)) {
    960 			error = copyin(iie->iie_buf, buf, iie->iie_buflen);
    961 			if (error)
    962 				goto out;
    963 		}
    964 	}
    965 
    966 	iic_acquire_bus(ic, 0);
    967 	error = iic_exec(ic, iie->iie_op, iie->iie_addr, cmd, iie->iie_cmdlen,
    968 	    buf, iie->iie_buflen, 0);
    969 	iic_release_bus(ic, 0);
    970 
    971 	/*
    972 	 * Some drivers return error codes on failure, and others return -1.
    973 	 */
    974 	if (error < 0)
    975 		error = EIO;
    976 
    977 out:
    978 	if (!error && iie->iie_buf != NULL && I2C_OP_READ_P(iie->iie_op))
    979 		error = copyout(buf, iie->iie_buf, iie->iie_buflen);
    980 
    981 	if (buf)
    982 		kmem_free(buf, iie->iie_buflen);
    983 
    984 	if (cmd)
    985 		kmem_free(cmd, iie->iie_cmdlen);
    986 
    987 	return error;
    988 }
    989 
    990 static int
    991 iic_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
    992 {
    993 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
    994 
    995 	if (sc == NULL)
    996 		return ENXIO;
    997 
    998 	switch (cmd) {
    999 	case I2C_IOCTL_EXEC:
   1000 		return iic_ioctl_exec(sc, (i2c_ioctl_exec_t *)data, flag);
   1001 	default:
   1002 		return ENODEV;
   1003 	}
   1004 }
   1005 
   1006 
   1007 CFATTACH_DECL3_NEW(iic, sizeof(struct iic_softc),
   1008     iic_match, iic_attach, iic_detach, NULL, iic_rescan, iic_child_detach,
   1009     DVF_DETACH_SHUTDOWN);
   1010 
   1011 MODULE(MODULE_CLASS_DRIVER, iic, "i2cexec,i2c_bitbang,i2c_subr");
   1012 
   1013 #ifdef _MODULE
   1014 #include "ioconf.c"
   1015 #endif
   1016 
   1017 int
   1018 iic_init(void)
   1019 {
   1020 
   1021 	mutex_init(&iic_mtx, MUTEX_DEFAULT, IPL_NONE);
   1022 	iic_refcnt = 0;
   1023 	return 0;
   1024 }
   1025 
   1026 static int
   1027 iic_modcmd(modcmd_t cmd, void *opaque)
   1028 {
   1029 #ifdef _MODULE
   1030 	int bmajor, cmajor;
   1031 #endif
   1032 	int error;
   1033 
   1034 	error = 0;
   1035 	switch (cmd) {
   1036 	case MODULE_CMD_INIT:
   1037 		RUN_ONCE(&iic_once, iic_init);
   1038 
   1039 #ifdef _MODULE
   1040 		mutex_enter(&iic_mtx);
   1041 		bmajor = cmajor = -1;
   1042 		error = devsw_attach("iic", NULL, &bmajor,
   1043 		    &iic_cdevsw, &cmajor);
   1044 		if (error != 0) {
   1045 			mutex_exit(&iic_mtx);
   1046 			break;
   1047 		}
   1048 		error = config_init_component(cfdriver_ioconf_iic,
   1049 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
   1050 		if (error) {
   1051 			aprint_error("%s: unable to init component\n",
   1052 			    iic_cd.cd_name);
   1053 			devsw_detach(NULL, &iic_cdevsw);
   1054 		}
   1055 		mutex_exit(&iic_mtx);
   1056 #endif
   1057 		break;
   1058 	case MODULE_CMD_FINI:
   1059 		mutex_enter(&iic_mtx);
   1060 		if (iic_refcnt != 0) {
   1061 			mutex_exit(&iic_mtx);
   1062 			return EBUSY;
   1063 		}
   1064 #ifdef _MODULE
   1065 		error = config_fini_component(cfdriver_ioconf_iic,
   1066 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
   1067 		if (error != 0) {
   1068 			mutex_exit(&iic_mtx);
   1069 			break;
   1070 		}
   1071 		devsw_detach(NULL, &iic_cdevsw);
   1072 #endif
   1073 		mutex_exit(&iic_mtx);
   1074 		break;
   1075 	default:
   1076 		error = ENOTTY;
   1077 	}
   1078 	return error;
   1079 }
   1080