xref: /netbsd-src/sys/dev/i2c/i2c.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: i2c.c,v 1.66 2018/06/26 06:34:55 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.66 2018/06/26 06:34:55 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 	int sc_type;
73 	device_t sc_devices[I2C_MAX_ADDR + 1];
74 };
75 
76 static dev_type_open(iic_open);
77 static dev_type_close(iic_close);
78 static dev_type_ioctl(iic_ioctl);
79 
80 int iic_init(void);
81 
82 kmutex_t iic_mtx;
83 int iic_refcnt;
84 
85 ONCE_DECL(iic_once);
86 
87 const struct cdevsw iic_cdevsw = {
88 	.d_open = iic_open,
89 	.d_close = iic_close,
90 	.d_read = noread,
91 	.d_write = nowrite,
92 	.d_ioctl = iic_ioctl,
93 	.d_stop = nostop,
94 	.d_tty = notty,
95 	.d_poll = nopoll,
96 	.d_mmap = nommap,
97 	.d_kqfilter = nokqfilter,
98 	.d_discard = nodiscard,
99 	.d_flag = D_OTHER
100 };
101 
102 static void	iic_smbus_intr_thread(void *);
103 static void	iic_fill_compat(struct i2c_attach_args*, const char*,
104 			size_t, char **);
105 
106 static int
107 iic_print_direct(void *aux, const char *pnp)
108 {
109 	struct i2c_attach_args *ia = aux;
110 
111 	if (pnp != NULL)
112 		aprint_normal("%s at %s addr 0x%02x",
113 			      ia->ia_name ? ia->ia_name : "(unknown)",
114 			      pnp, ia->ia_addr);
115 	else
116 		aprint_normal(" addr 0x%02x", ia->ia_addr);
117 
118 	return UNCONF;
119 }
120 
121 static int
122 iic_print(void *aux, const char *pnp)
123 {
124 	struct i2c_attach_args *ia = aux;
125 
126 	if (ia->ia_addr != (i2c_addr_t)IICCF_ADDR_DEFAULT)
127 		aprint_normal(" addr 0x%x", ia->ia_addr);
128 
129 	return UNCONF;
130 }
131 
132 static bool
133 iic_is_special_address(i2c_addr_t addr)
134 {
135 
136 	/*
137 	 * See: https://www.i2c-bus.org/addressing/
138 	 */
139 
140 	/* General Call (read) / Start Byte (write) */
141 	if (addr == 0x00)
142 		return (true);
143 
144 	/* CBUS Addresses */
145 	if (addr == 0x01)
146 		return (true);
147 
148 	/* Reserved for Different Bus Formats */
149 	if (addr == 0x02)
150 		return (true);
151 
152 	/* Reserved for future purposes */
153 	if (addr == 0x03)
154 		return (true);
155 
156 	/* High Speed Master Code */
157 	if ((addr & 0x7c) == 0x04)
158 		return (true);
159 
160 	/* 10-bit Slave Addressing prefix */
161 	if ((addr & 0x7c) == 0x78)
162 		return (true);
163 
164 	/* Reserved for future purposes */
165 	if ((addr & 0x7c) == 0x7c)
166 		return (true);
167 
168 	return (false);
169 }
170 
171 static int
172 iic_probe_none(struct iic_softc *sc,
173 	       const struct i2c_attach_args *ia, int flags)
174 {
175 
176 	return (0);
177 }
178 
179 static int
180 iic_probe_smbus_quick_write(struct iic_softc *sc,
181 			    const struct i2c_attach_args *ia, int flags)
182 {
183 	int error;
184 
185 	if ((error = iic_acquire_bus(ia->ia_tag, flags)) == 0) {
186 		error = iic_smbus_quick_write(ia->ia_tag, ia->ia_addr, flags);
187 	}
188 	(void) iic_release_bus(ia->ia_tag, flags);
189 
190 	return (error);
191 }
192 
193 static int
194 iic_probe_smbus_receive_byte(struct iic_softc *sc,
195 			     const struct i2c_attach_args *ia, int flags)
196 {
197 	int error;
198 
199 	if ((error = iic_acquire_bus(ia->ia_tag, flags)) == 0) {
200 		uint8_t dummy;
201 
202 		error = iic_smbus_receive_byte(ia->ia_tag, ia->ia_addr,
203 					       &dummy, flags);
204 	}
205 	(void) iic_release_bus(ia->ia_tag, flags);
206 
207 	return (error);
208 }
209 
210 static bool
211 iic_indirect_driver_is_whitelisted(struct iic_softc *sc, cfdata_t cf)
212 {
213 	prop_object_iterator_t iter;
214 	prop_array_t whitelist;
215 	prop_string_t pstr;
216 	prop_type_t ptype;
217 	bool rv = false;
218 
219 	whitelist = prop_dictionary_get(device_properties(sc->sc_dev),
220 					I2C_PROP_INDIRECT_DEVICE_WHITELIST);
221 	if (whitelist == NULL) {
222 		/* No whitelist -> everything allowed */
223 		return (true);
224 	}
225 
226 	if ((ptype = prop_object_type(whitelist)) != PROP_TYPE_ARRAY) {
227 		aprint_error_dev(sc->sc_dev,
228 		    "invalid property type (%d) for '%s'; must be array (%d)\n",
229 		    ptype, I2C_PROP_INDIRECT_DEVICE_WHITELIST, PROP_TYPE_ARRAY);
230 		return (false);
231 	}
232 
233 	iter = prop_array_iterator(whitelist);
234 	while ((pstr = prop_object_iterator_next(iter)) != NULL) {
235 		if (prop_string_equals_cstring(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 	 * white-list for this bus (if any).
258 	 */
259 	if (iic_indirect_driver_is_whitelisted(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_cstring(pstr,
270 					I2C_PROBE_STRATEGY_QUICK_WRITE)) {
271 		probe_func = iic_probe_smbus_quick_write;
272 	} else if (prop_string_equals_cstring(pstr,
273 					I2C_PROBE_STRATEGY_RECEIVE_BYTE)) {
274 		probe_func = iic_probe_smbus_receive_byte;
275 	} else if (prop_string_equals_cstring(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_cstring_nocopy(pstr),
282 			I2C_PROBE_STRATEGY_QUICK_WRITE);
283 
284 		/* Use the default. */
285 	}
286 
287 	ia.ia_tag = sc->sc_tag;
288 	ia.ia_type = sc->sc_type;
289 
290 	ia.ia_name = NULL;
291 	ia.ia_ncompat = 0;
292 	ia.ia_compat = NULL;
293 	ia.ia_prop = NULL;
294 
295 	if (cf->cf_loc[IICCF_ADDR] == IICCF_ADDR_DEFAULT) {
296 		/*
297 		 * This particular config directive has
298 		 * wildcarded the address, so we will
299 		 * scan the entire bus for it.
300 		 */
301 		first_addr = 0;
302 		last_addr = I2C_MAX_ADDR;
303 	} else {
304 		/*
305 		 * This config directive hard-wires the i2c
306 		 * bus address for the device, so there is
307 		 * no need to go poking around at any other
308 		 * addresses.
309 		 */
310 		if (cf->cf_loc[IICCF_ADDR] < 0 ||
311 		    cf->cf_loc[IICCF_ADDR] > I2C_MAX_ADDR) {
312 			/* Invalid config directive! */
313 			return (0);
314 		}
315 		first_addr = last_addr = cf->cf_loc[IICCF_ADDR];
316 	}
317 
318 	for (ia.ia_addr = first_addr; ia.ia_addr <= last_addr; ia.ia_addr++) {
319 		int error, match_result;
320 
321 		/*
322 		 * Skip I2C addresses that are reserved for
323 		 * special purposes.
324 		 */
325 		if (iic_is_special_address(ia.ia_addr))
326 			continue;
327 
328 		/*
329 		 * Skip addresses where a device is already attached.
330 		 */
331 		if (sc->sc_devices[ia.ia_addr] != NULL)
332 			continue;
333 
334 		/*
335 		 * Call the "match" routine for the device.  If that
336 		 * returns success, then call the probe strategy
337 		 * function.
338 		 *
339 		 * We do it in this order because i2c devices tend
340 		 * to be found at a small number of possible addresses
341 		 * (e.g. read-time clocks that are only ever found at
342 		 * 0x68).  This gives the driver a chance to skip any
343 		 * address that are not valid for the device, saving
344 		 * us from having to poke at the bus to see if anything
345 		 * is there.
346 		 */
347 		match_result = config_match(parent, cf, &ia);
348 		if (match_result <= 0)
349 			continue;
350 
351 		/*
352 		 * If the quality of the match by the driver was low
353 		 * (i.e. matched on being a valid address only, didn't
354 		 * perform any hardware probe), invoke our probe routine
355 		 * to see if it looks like something is really there.
356 		 */
357 		if (match_result == I2C_MATCH_ADDRESS_ONLY &&
358 		    (error = (*probe_func)(sc, &ia, I2C_F_POLL)) != 0)
359 			continue;
360 
361 		sc->sc_devices[ia.ia_addr] =
362 		    config_attach(parent, cf, &ia, iic_print);
363 	}
364 
365 	return 0;
366 }
367 
368 static void
369 iic_child_detach(device_t parent, device_t child)
370 {
371 	struct iic_softc *sc = device_private(parent);
372 	int i;
373 
374 	for (i = 0; i <= I2C_MAX_ADDR; i++)
375 		if (sc->sc_devices[i] == child) {
376 			sc->sc_devices[i] = NULL;
377 			break;
378 		}
379 }
380 
381 static int
382 iic_rescan(device_t self, const char *ifattr, const int *locators)
383 {
384 	config_search_ia(iic_search, self, ifattr, NULL);
385 	return 0;
386 }
387 
388 static int
389 iic_match(device_t parent, cfdata_t cf, void *aux)
390 {
391 
392 	return 1;
393 }
394 
395 static void
396 iic_attach(device_t parent, device_t self, void *aux)
397 {
398 	struct iic_softc *sc = device_private(self);
399 	struct i2cbus_attach_args *iba = aux;
400 	prop_array_t child_devices;
401 	prop_dictionary_t props;
402 	char *buf;
403 	i2c_tag_t ic;
404 	int rv;
405 	bool indirect_config;
406 
407 	aprint_naive("\n");
408 	aprint_normal(": I2C bus\n");
409 
410 	sc->sc_dev = self;
411 	sc->sc_tag = iba->iba_tag;
412 	sc->sc_type = iba->iba_type;
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 		indirect_config = false;
431 	} else {
432 		props = device_properties(parent);
433 		if (!prop_dictionary_get_bool(props, "i2c-indirect-config",
434 		    &indirect_config))
435 			indirect_config = true;
436 		child_devices = prop_dictionary_get(props, "i2c-child-devices");
437 	}
438 
439 	if (child_devices) {
440 		unsigned int i, count;
441 		prop_dictionary_t dev;
442 		prop_data_t cdata;
443 		uint32_t addr;
444 		uint64_t cookie;
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_cstring_nocopy(
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 			loc[IICCF_ADDR] = addr;
464 
465 			memset(&ia, 0, sizeof ia);
466 			ia.ia_addr = addr;
467 			ia.ia_type = sc->sc_type;
468 			ia.ia_tag = ic;
469 			ia.ia_name = name;
470 			ia.ia_cookie = cookie;
471 			ia.ia_prop = dev;
472 
473 			buf = NULL;
474 			cdata = prop_dictionary_get(dev, "compatible");
475 			if (cdata)
476 				iic_fill_compat(&ia,
477 				    prop_data_data_nocopy(cdata),
478 				    prop_data_size(cdata), &buf);
479 
480 			if (name == NULL && cdata == NULL) {
481 				aprint_error_dev(self,
482 				    "WARNING: ignoring bad child device entry "
483 				    "for address 0x%02x\n", addr);
484 			} else {
485 				if (addr > I2C_MAX_ADDR) {
486 					aprint_error_dev(self,
487 					    "WARNING: ignoring bad device "
488 					    "address @ 0x%02x\n", addr);
489 				} else if (sc->sc_devices[addr] == NULL) {
490 					sc->sc_devices[addr] =
491 					    config_found_sm_loc(self, "iic",
492 					        loc, &ia, iic_print_direct,
493 						NULL);
494 				}
495 			}
496 
497 			if (ia.ia_compat)
498 				free(ia.ia_compat, M_TEMP);
499 			if (buf)
500 				free(buf, M_TEMP);
501 		}
502 	} else if (indirect_config) {
503 		/*
504 		 * Attach all i2c devices described in the kernel
505 		 * configuration file.
506 		 */
507 		iic_rescan(self, "iic", NULL);
508 	}
509 }
510 
511 static int
512 iic_detach(device_t self, int flags)
513 {
514 	struct iic_softc *sc = device_private(self);
515 	i2c_tag_t ic = sc->sc_tag;
516 	int i, error;
517 	void *hdl;
518 
519 	for (i = 0; i <= I2C_MAX_ADDR; i++) {
520 		if (sc->sc_devices[i]) {
521 			error = config_detach(sc->sc_devices[i], flags);
522 			if (error)
523 				return error;
524 		}
525 	}
526 
527 	if (ic->ic_running) {
528 		ic->ic_running = 0;
529 		wakeup(ic);
530 		kthread_join(ic->ic_intr_thread);
531 	}
532 
533 	if (!LIST_EMPTY(&ic->ic_list)) {
534 		device_printf(self, "WARNING: intr handler list not empty\n");
535 		while (!LIST_EMPTY(&ic->ic_list)) {
536 			hdl = LIST_FIRST(&ic->ic_list);
537 			iic_smbus_intr_disestablish(ic, hdl);
538 		}
539 	}
540 	if (!LIST_EMPTY(&ic->ic_proc_list)) {
541 		device_printf(self, "WARNING: proc handler list not empty\n");
542 		while (!LIST_EMPTY(&ic->ic_proc_list)) {
543 			hdl = LIST_FIRST(&ic->ic_proc_list);
544 			iic_smbus_intr_disestablish_proc(ic, hdl);
545 		}
546 	}
547 
548 	pmf_device_deregister(self);
549 
550 	return 0;
551 }
552 
553 static void
554 iic_smbus_intr_thread(void *aux)
555 {
556 	i2c_tag_t ic;
557 	struct ic_intr_list *il;
558 
559 	ic = (i2c_tag_t)aux;
560 	ic->ic_running = 1;
561 	ic->ic_pending = 0;
562 
563 	while (ic->ic_running) {
564 		if (ic->ic_pending == 0)
565 			tsleep(ic, PZERO, "iicintr", hz);
566 		if (ic->ic_pending > 0) {
567 			LIST_FOREACH(il, &(ic->ic_proc_list), il_next) {
568 				(*il->il_intr)(il->il_intrarg);
569 			}
570 			ic->ic_pending--;
571 		}
572 	}
573 
574 	kthread_exit(0);
575 }
576 
577 void *
578 iic_smbus_intr_establish(i2c_tag_t ic, int (*intr)(void *), void *intrarg)
579 {
580 	struct ic_intr_list *il;
581 
582 	il = malloc(sizeof(struct ic_intr_list), M_DEVBUF, M_WAITOK);
583 	if (il == NULL)
584 		return NULL;
585 
586 	il->il_intr = intr;
587 	il->il_intrarg = intrarg;
588 
589 	LIST_INSERT_HEAD(&(ic->ic_list), il, il_next);
590 
591 	return il;
592 }
593 
594 void
595 iic_smbus_intr_disestablish(i2c_tag_t ic, void *hdl)
596 {
597 	struct ic_intr_list *il;
598 
599 	il = (struct ic_intr_list *)hdl;
600 
601 	LIST_REMOVE(il, il_next);
602 	free(il, M_DEVBUF);
603 
604 	return;
605 }
606 
607 void *
608 iic_smbus_intr_establish_proc(i2c_tag_t ic, int (*intr)(void *), void *intrarg)
609 {
610 	struct ic_intr_list *il;
611 
612 	il = malloc(sizeof(struct ic_intr_list), M_DEVBUF, M_WAITOK);
613 	if (il == NULL)
614 		return NULL;
615 
616 	il->il_intr = intr;
617 	il->il_intrarg = intrarg;
618 
619 	LIST_INSERT_HEAD(&(ic->ic_proc_list), il, il_next);
620 
621 	return il;
622 }
623 
624 void
625 iic_smbus_intr_disestablish_proc(i2c_tag_t ic, void *hdl)
626 {
627 	struct ic_intr_list *il;
628 
629 	il = (struct ic_intr_list *)hdl;
630 
631 	LIST_REMOVE(il, il_next);
632 	free(il, M_DEVBUF);
633 
634 	return;
635 }
636 
637 int
638 iic_smbus_intr(i2c_tag_t ic)
639 {
640 	struct ic_intr_list *il;
641 
642 	LIST_FOREACH(il, &(ic->ic_list), il_next) {
643 		(*il->il_intr)(il->il_intrarg);
644 	}
645 
646 	ic->ic_pending++;
647 	wakeup(ic);
648 
649 	return 1;
650 }
651 
652 static void
653 iic_fill_compat(struct i2c_attach_args *ia, const char *compat, size_t len,
654 	char **buffer)
655 {
656 	int count, i;
657 	const char *c, *start, **ptr;
658 
659 	*buffer = NULL;
660 	for (i = count = 0, c = compat; i < len; i++, c++)
661 		if (*c == 0)
662 			count++;
663 	count += 2;
664 	ptr = malloc(sizeof(char*)*count, M_TEMP, M_WAITOK);
665 	if (!ptr) return;
666 
667 	for (i = count = 0, start = c = compat; i < len; i++, c++) {
668 		if (*c == 0) {
669 			ptr[count++] = start;
670 			start = c+1;
671 		}
672 	}
673 	if (start < compat+len) {
674 		/* last string not 0 terminated */
675 		size_t l = c-start;
676 		*buffer = malloc(l+1, M_TEMP, M_WAITOK);
677 		memcpy(*buffer, start, l);
678 		(*buffer)[l] = 0;
679 		ptr[count++] = *buffer;
680 	}
681 	ptr[count] = NULL;
682 
683 	ia->ia_compat = ptr;
684 	ia->ia_ncompat = count;
685 }
686 
687 /*
688  * iic_compatible_match --
689  *	Match a device's "compatible" property against the list
690  *	of compatible strings provided by the driver.
691  */
692 int
693 iic_compatible_match(const struct i2c_attach_args *ia,
694 		     const struct device_compatible_entry *compats,
695 		     const struct device_compatible_entry **matching_entryp)
696 {
697 	int match_result;
698 
699 	match_result = device_compatible_match(ia->ia_compat, ia->ia_ncompat,
700 					       compats, matching_entryp);
701 	if (match_result) {
702 		match_result =
703 		    MIN(I2C_MATCH_DIRECT_COMPATIBLE + match_result - 1,
704 			I2C_MATCH_DIRECT_COMPATIBLE_MAX);
705 	}
706 
707 	return match_result;
708 }
709 
710 /*
711  * iic_use_direct_match --
712  *	Helper for direct-config of i2c.  Returns true if this is
713  *	a direct-config situation, along with with match result.
714  *	Returns false if the driver should use indirect-config
715  *	matching logic.
716  */
717 bool
718 iic_use_direct_match(const struct i2c_attach_args *ia, const cfdata_t cf,
719 		     const struct device_compatible_entry *compats,
720 		     int *match_resultp)
721 {
722 
723 	KASSERT(match_resultp != NULL);
724 
725 	if (ia->ia_name != NULL &&
726 	    strcmp(ia->ia_name, cf->cf_name) == 0) {
727 		*match_resultp = I2C_MATCH_DIRECT_SPECIFIC;
728 		return true;
729 	}
730 
731 	if (ia->ia_ncompat > 0 && ia->ia_compat != NULL) {
732 		*match_resultp = iic_compatible_match(ia, compats, NULL);
733 		return true;
734 	}
735 
736 	return false;
737 }
738 
739 static int
740 iic_open(dev_t dev, int flag, int fmt, lwp_t *l)
741 {
742 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
743 
744 	mutex_enter(&iic_mtx);
745 	if (sc == NULL) {
746 		mutex_exit(&iic_mtx);
747 		return ENXIO;
748 	}
749 	iic_refcnt++;
750 	mutex_exit(&iic_mtx);
751 
752 	return 0;
753 }
754 
755 static int
756 iic_close(dev_t dev, int flag, int fmt, lwp_t *l)
757 {
758 
759 	mutex_enter(&iic_mtx);
760 	iic_refcnt--;
761 	mutex_exit(&iic_mtx);
762 
763 	return 0;
764 }
765 
766 static int
767 iic_ioctl_exec(struct iic_softc *sc, i2c_ioctl_exec_t *iie, int flag)
768 {
769 	i2c_tag_t ic = sc->sc_tag;
770 	uint8_t buf[I2C_EXEC_MAX_BUFLEN];
771 	void *cmd = NULL;
772 	int error;
773 
774 	/* Validate parameters */
775 	if (iie->iie_addr > I2C_MAX_ADDR)
776 		return EINVAL;
777 	if (iie->iie_cmdlen > I2C_EXEC_MAX_CMDLEN ||
778 	    iie->iie_buflen > I2C_EXEC_MAX_BUFLEN)
779 		return EINVAL;
780 	if (iie->iie_cmd != NULL && iie->iie_cmdlen == 0)
781 		return EINVAL;
782 	if (iie->iie_buf != NULL && iie->iie_buflen == 0)
783 		return EINVAL;
784 	if (I2C_OP_WRITE_P(iie->iie_op) && (flag & FWRITE) == 0)
785 		return EBADF;
786 
787 #if 0
788 	/* Disallow userspace access to devices that have drivers attached. */
789 	if (sc->sc_devices[iie->iie_addr] != NULL)
790 		return EBUSY;
791 #endif
792 
793 	if (iie->iie_cmd != NULL) {
794 		cmd = kmem_alloc(iie->iie_cmdlen, KM_SLEEP);
795 		error = copyin(iie->iie_cmd, cmd, iie->iie_cmdlen);
796 		if (error)
797 			goto out;
798 	}
799 
800 	if (iie->iie_buf != NULL && I2C_OP_WRITE_P(iie->iie_op)) {
801 		error = copyin(iie->iie_buf, buf, iie->iie_buflen);
802 		if (error)
803 			goto out;
804 	}
805 
806 	iic_acquire_bus(ic, 0);
807 	error = iic_exec(ic, iie->iie_op, iie->iie_addr, cmd, iie->iie_cmdlen,
808 	    buf, iie->iie_buflen, 0);
809 	iic_release_bus(ic, 0);
810 
811 	/*
812 	 * Some drivers return error codes on failure, and others return -1.
813 	 */
814 	if (error < 0)
815 		error = EIO;
816 
817 out:
818 	if (cmd)
819 		kmem_free(cmd, iie->iie_cmdlen);
820 
821 	if (error)
822 		return error;
823 
824 	if (iie->iie_buf != NULL && I2C_OP_READ_P(iie->iie_op))
825 		error = copyout(buf, iie->iie_buf, iie->iie_buflen);
826 
827 	return error;
828 }
829 
830 static int
831 iic_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
832 {
833 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
834 
835 	if (sc == NULL)
836 		return ENXIO;
837 
838 	switch (cmd) {
839 	case I2C_IOCTL_EXEC:
840 		return iic_ioctl_exec(sc, (i2c_ioctl_exec_t *)data, flag);
841 	default:
842 		return ENODEV;
843 	}
844 }
845 
846 
847 CFATTACH_DECL2_NEW(iic, sizeof(struct iic_softc),
848     iic_match, iic_attach, iic_detach, NULL, iic_rescan, iic_child_detach);
849 
850 MODULE(MODULE_CLASS_DRIVER, iic, "i2cexec,i2c_bitbang");
851 
852 #ifdef _MODULE
853 #include "ioconf.c"
854 #endif
855 
856 int
857 iic_init(void)
858 {
859 
860 	mutex_init(&iic_mtx, MUTEX_DEFAULT, IPL_NONE);
861 	iic_refcnt = 0;
862 	return 0;
863 }
864 
865 static int
866 iic_modcmd(modcmd_t cmd, void *opaque)
867 {
868 #ifdef _MODULE
869 	int bmajor, cmajor;
870 #endif
871 	int error;
872 
873 	error = 0;
874 	switch (cmd) {
875 	case MODULE_CMD_INIT:
876 		RUN_ONCE(&iic_once, iic_init);
877 
878 #ifdef _MODULE
879 		mutex_enter(&iic_mtx);
880 		bmajor = cmajor = -1;
881 		error = devsw_attach("iic", NULL, &bmajor,
882 		    &iic_cdevsw, &cmajor);
883 		if (error != 0) {
884 			mutex_exit(&iic_mtx);
885 			break;
886 		}
887 		error = config_init_component(cfdriver_ioconf_iic,
888 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
889 		if (error) {
890 			aprint_error("%s: unable to init component\n",
891 			    iic_cd.cd_name);
892 			(void)devsw_detach(NULL, &iic_cdevsw);
893 		}
894 		mutex_exit(&iic_mtx);
895 #endif
896 		break;
897 	case MODULE_CMD_FINI:
898 		mutex_enter(&iic_mtx);
899 		if (iic_refcnt != 0) {
900 			mutex_exit(&iic_mtx);
901 			return EBUSY;
902 		}
903 #ifdef _MODULE
904 		error = config_fini_component(cfdriver_ioconf_iic,
905 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
906 		if (error != 0) {
907 			mutex_exit(&iic_mtx);
908 			break;
909 		}
910 		error = devsw_detach(NULL, &iic_cdevsw);
911 		if (error != 0)
912 			config_init_component(cfdriver_ioconf_iic,
913 			    cfattach_ioconf_iic, cfdata_ioconf_iic);
914 #endif
915 		mutex_exit(&iic_mtx);
916 		break;
917 	default:
918 		error = ENOTTY;
919 	}
920 	return error;
921 }
922