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