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