xref: /netbsd-src/sys/dev/i2c/i2c.c (revision 114ca20a4a7aa68e9c04e01636b83f9c6daf73e8)
1 /*	$NetBSD: i2c.c,v 1.58 2018/05/15 02:02:18 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.58 2018/05/15 02:02:18 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 	i2c_tag_t sc_tag;
71 	int sc_type;
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", ia->ia_name, pnp,
112 			ia->ia_addr);
113 	else
114 		aprint_normal(" addr 0x%02x", ia->ia_addr);
115 
116 	return UNCONF;
117 }
118 
119 static int
120 iic_print(void *aux, const char *pnp)
121 {
122 	struct i2c_attach_args *ia = aux;
123 
124 	if (ia->ia_addr != (i2c_addr_t)IICCF_ADDR_DEFAULT)
125 		aprint_normal(" addr 0x%x", ia->ia_addr);
126 
127 	return UNCONF;
128 }
129 
130 static int
131 iic_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
132 {
133 	struct iic_softc *sc = device_private(parent);
134 	struct i2c_attach_args ia;
135 
136 	/*
137 	 * I2C doesn't have any regular probing capability.  If we
138 	 * encounter a cfdata with a wild-carded address or a wild-
139 	 * carded parent spec, we skip them because they can only
140 	 * be used for direct-coniguration.
141 	 */
142 	if (cf->cf_loc[IICCF_ADDR] == IICCF_ADDR_DEFAULT ||
143 	    cf->cf_pspec->cfp_unit == DVUNIT_ANY)
144 		return 0;
145 
146 	ia.ia_tag = sc->sc_tag;
147 	ia.ia_size = cf->cf_loc[IICCF_SIZE];
148 	ia.ia_type = sc->sc_type;
149 
150 	ia.ia_name = NULL;
151 	ia.ia_ncompat = 0;
152 	ia.ia_compat = NULL;
153 	ia.ia_prop = NULL;
154 
155 	for (ia.ia_addr = 0; ia.ia_addr <= I2C_MAX_ADDR; ia.ia_addr++) {
156 		if (sc->sc_devices[ia.ia_addr] != NULL)
157 			continue;
158 
159 		if (cf->cf_loc[IICCF_ADDR] != ia.ia_addr)
160 			continue;
161 
162 		if (config_match(parent, cf, &ia) > 0)
163 			sc->sc_devices[ia.ia_addr] =
164 			    config_attach(parent, cf, &ia, iic_print);
165 	}
166 
167 	return 0;
168 }
169 
170 static void
171 iic_child_detach(device_t parent, device_t child)
172 {
173 	struct iic_softc *sc = device_private(parent);
174 	int i;
175 
176 	for (i = 0; i <= I2C_MAX_ADDR; i++)
177 		if (sc->sc_devices[i] == child) {
178 			sc->sc_devices[i] = NULL;
179 			break;
180 		}
181 }
182 
183 static int
184 iic_rescan(device_t self, const char *ifattr, const int *locators)
185 {
186 	config_search_ia(iic_search, self, ifattr, NULL);
187 	return 0;
188 }
189 
190 static int
191 iic_match(device_t parent, cfdata_t cf, void *aux)
192 {
193 
194 	return 1;
195 }
196 
197 static void
198 iic_attach(device_t parent, device_t self, void *aux)
199 {
200 	struct iic_softc *sc = device_private(self);
201 	struct i2cbus_attach_args *iba = aux;
202 	prop_array_t child_devices;
203 	prop_dictionary_t props;
204 	char *buf;
205 	i2c_tag_t ic;
206 	int rv;
207 	bool indirect_config;
208 
209 	aprint_naive("\n");
210 	aprint_normal(": I2C bus\n");
211 
212 	sc->sc_tag = iba->iba_tag;
213 	sc->sc_type = iba->iba_type;
214 	ic = sc->sc_tag;
215 	ic->ic_devname = device_xname(self);
216 
217 	LIST_INIT(&(sc->sc_tag->ic_list));
218 	LIST_INIT(&(sc->sc_tag->ic_proc_list));
219 
220 	rv = kthread_create(PRI_NONE, KTHREAD_MUSTJOIN, NULL,
221 	    iic_smbus_intr_thread, ic, &ic->ic_intr_thread,
222 	    "%s", ic->ic_devname);
223 	if (rv)
224 		aprint_error_dev(self, "unable to create intr thread\n");
225 
226 	if (!pmf_device_register(self, NULL, NULL))
227 		aprint_error_dev(self, "couldn't establish power handler\n");
228 
229 	if (iba->iba_child_devices) {
230 		child_devices = iba->iba_child_devices;
231 		indirect_config = false;
232 	} else {
233 		props = device_properties(parent);
234 		if (!prop_dictionary_get_bool(props, "i2c-indirect-config",
235 		    &indirect_config))
236 			indirect_config = true;
237 		child_devices = prop_dictionary_get(props, "i2c-child-devices");
238 	}
239 
240 	if (child_devices) {
241 		unsigned int i, count;
242 		prop_dictionary_t dev;
243 		prop_data_t cdata;
244 		uint32_t addr, size;
245 		uint64_t cookie;
246 		const char *name;
247 		struct i2c_attach_args ia;
248 		int loc[IICCF_NLOCS];
249 
250 		memset(loc, 0, sizeof loc);
251 		count = prop_array_count(child_devices);
252 		for (i = 0; i < count; i++) {
253 			dev = prop_array_get(child_devices, i);
254 			if (!dev) continue;
255  			if (!prop_dictionary_get_cstring_nocopy(
256 			    dev, "name", &name))
257 				continue;
258 			if (!prop_dictionary_get_uint32(dev, "addr", &addr))
259 				continue;
260 			if (!prop_dictionary_get_uint64(dev, "cookie", &cookie))
261 				cookie = 0;
262 			loc[IICCF_ADDR] = addr;
263 			if (prop_dictionary_get_uint32(dev, "size", &size))
264 				loc[IICCF_SIZE] = size;
265 			else
266 				size = loc[IICCF_SIZE] = IICCF_SIZE_DEFAULT;
267 
268 			memset(&ia, 0, sizeof ia);
269 			ia.ia_addr = addr;
270 			ia.ia_type = sc->sc_type;
271 			ia.ia_tag = ic;
272 			ia.ia_name = name;
273 			ia.ia_cookie = cookie;
274 			ia.ia_size = size;
275 			ia.ia_prop = dev;
276 
277 			buf = NULL;
278 			cdata = prop_dictionary_get(dev, "compatible");
279 			if (cdata)
280 				iic_fill_compat(&ia,
281 				    prop_data_data_nocopy(cdata),
282 				    prop_data_size(cdata), &buf);
283 
284 			if (addr > I2C_MAX_ADDR) {
285 				aprint_error_dev(self,
286 				    "WARNING: ignoring bad device address "
287 				    "@ 0x%02x\n", addr);
288 			} else if (sc->sc_devices[addr] == NULL) {
289 				sc->sc_devices[addr] =
290 				    config_found_sm_loc(self, "iic", loc, &ia,
291 					iic_print_direct, NULL);
292 			}
293 
294 			if (ia.ia_compat)
295 				free(ia.ia_compat, M_TEMP);
296 			if (buf)
297 				free(buf, M_TEMP);
298 		}
299 	} else if (indirect_config) {
300 		/*
301 		 * Attach all i2c devices described in the kernel
302 		 * configuration file.
303 		 */
304 		iic_rescan(self, "iic", NULL);
305 	}
306 }
307 
308 static int
309 iic_detach(device_t self, int flags)
310 {
311 	struct iic_softc *sc = device_private(self);
312 	i2c_tag_t ic = sc->sc_tag;
313 	int i, error;
314 	void *hdl;
315 
316 	for (i = 0; i <= I2C_MAX_ADDR; i++) {
317 		if (sc->sc_devices[i]) {
318 			error = config_detach(sc->sc_devices[i], flags);
319 			if (error)
320 				return error;
321 		}
322 	}
323 
324 	if (ic->ic_running) {
325 		ic->ic_running = 0;
326 		wakeup(ic);
327 		kthread_join(ic->ic_intr_thread);
328 	}
329 
330 	if (!LIST_EMPTY(&ic->ic_list)) {
331 		device_printf(self, "WARNING: intr handler list not empty\n");
332 		while (!LIST_EMPTY(&ic->ic_list)) {
333 			hdl = LIST_FIRST(&ic->ic_list);
334 			iic_smbus_intr_disestablish(ic, hdl);
335 		}
336 	}
337 	if (!LIST_EMPTY(&ic->ic_proc_list)) {
338 		device_printf(self, "WARNING: proc handler list not empty\n");
339 		while (!LIST_EMPTY(&ic->ic_proc_list)) {
340 			hdl = LIST_FIRST(&ic->ic_proc_list);
341 			iic_smbus_intr_disestablish_proc(ic, hdl);
342 		}
343 	}
344 
345 	pmf_device_deregister(self);
346 
347 	return 0;
348 }
349 
350 static void
351 iic_smbus_intr_thread(void *aux)
352 {
353 	i2c_tag_t ic;
354 	struct ic_intr_list *il;
355 
356 	ic = (i2c_tag_t)aux;
357 	ic->ic_running = 1;
358 	ic->ic_pending = 0;
359 
360 	while (ic->ic_running) {
361 		if (ic->ic_pending == 0)
362 			tsleep(ic, PZERO, "iicintr", hz);
363 		if (ic->ic_pending > 0) {
364 			LIST_FOREACH(il, &(ic->ic_proc_list), il_next) {
365 				(*il->il_intr)(il->il_intrarg);
366 			}
367 			ic->ic_pending--;
368 		}
369 	}
370 
371 	kthread_exit(0);
372 }
373 
374 void *
375 iic_smbus_intr_establish(i2c_tag_t ic, int (*intr)(void *), void *intrarg)
376 {
377 	struct ic_intr_list *il;
378 
379 	il = malloc(sizeof(struct ic_intr_list), M_DEVBUF, M_WAITOK);
380 	if (il == NULL)
381 		return NULL;
382 
383 	il->il_intr = intr;
384 	il->il_intrarg = intrarg;
385 
386 	LIST_INSERT_HEAD(&(ic->ic_list), il, il_next);
387 
388 	return il;
389 }
390 
391 void
392 iic_smbus_intr_disestablish(i2c_tag_t ic, void *hdl)
393 {
394 	struct ic_intr_list *il;
395 
396 	il = (struct ic_intr_list *)hdl;
397 
398 	LIST_REMOVE(il, il_next);
399 	free(il, M_DEVBUF);
400 
401 	return;
402 }
403 
404 void *
405 iic_smbus_intr_establish_proc(i2c_tag_t ic, int (*intr)(void *), void *intrarg)
406 {
407 	struct ic_intr_list *il;
408 
409 	il = malloc(sizeof(struct ic_intr_list), M_DEVBUF, M_WAITOK);
410 	if (il == NULL)
411 		return NULL;
412 
413 	il->il_intr = intr;
414 	il->il_intrarg = intrarg;
415 
416 	LIST_INSERT_HEAD(&(ic->ic_proc_list), il, il_next);
417 
418 	return il;
419 }
420 
421 void
422 iic_smbus_intr_disestablish_proc(i2c_tag_t ic, void *hdl)
423 {
424 	struct ic_intr_list *il;
425 
426 	il = (struct ic_intr_list *)hdl;
427 
428 	LIST_REMOVE(il, il_next);
429 	free(il, M_DEVBUF);
430 
431 	return;
432 }
433 
434 int
435 iic_smbus_intr(i2c_tag_t ic)
436 {
437 	struct ic_intr_list *il;
438 
439 	LIST_FOREACH(il, &(ic->ic_list), il_next) {
440 		(*il->il_intr)(il->il_intrarg);
441 	}
442 
443 	ic->ic_pending++;
444 	wakeup(ic);
445 
446 	return 1;
447 }
448 
449 static void
450 iic_fill_compat(struct i2c_attach_args *ia, const char *compat, size_t len,
451 	char **buffer)
452 {
453 	int count, i;
454 	const char *c, *start, **ptr;
455 
456 	*buffer = NULL;
457 	for (i = count = 0, c = compat; i < len; i++, c++)
458 		if (*c == 0)
459 			count++;
460 	count += 2;
461 	ptr = malloc(sizeof(char*)*count, M_TEMP, M_WAITOK);
462 	if (!ptr) return;
463 
464 	for (i = count = 0, start = c = compat; i < len; i++, c++) {
465 		if (*c == 0) {
466 			ptr[count++] = start;
467 			start = c+1;
468 		}
469 	}
470 	if (start < compat+len) {
471 		/* last string not 0 terminated */
472 		size_t l = c-start;
473 		*buffer = malloc(l+1, M_TEMP, M_WAITOK);
474 		memcpy(*buffer, start, l);
475 		(*buffer)[l] = 0;
476 		ptr[count++] = *buffer;
477 	}
478 	ptr[count] = NULL;
479 
480 	ia->ia_compat = ptr;
481 	ia->ia_ncompat = count;
482 }
483 
484 int
485 iic_compat_match(struct i2c_attach_args *ia, const char ** compats)
486 {
487 	int i;
488 
489 	for (; compats && *compats; compats++) {
490 		for (i = 0; i < ia->ia_ncompat; i++) {
491 			if (strcmp(*compats, ia->ia_compat[i]) == 0)
492 				return 1;
493 		}
494 	}
495 	return 0;
496 }
497 
498 static int
499 iic_open(dev_t dev, int flag, int fmt, lwp_t *l)
500 {
501 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
502 
503 	mutex_enter(&iic_mtx);
504 	if (sc == NULL) {
505 		mutex_exit(&iic_mtx);
506 		return ENXIO;
507 	}
508 	iic_refcnt++;
509 	mutex_exit(&iic_mtx);
510 
511 	return 0;
512 }
513 
514 static int
515 iic_close(dev_t dev, int flag, int fmt, lwp_t *l)
516 {
517 
518 	mutex_enter(&iic_mtx);
519 	iic_refcnt--;
520 	mutex_exit(&iic_mtx);
521 
522 	return 0;
523 }
524 
525 static int
526 iic_ioctl_exec(struct iic_softc *sc, i2c_ioctl_exec_t *iie, int flag)
527 {
528 	i2c_tag_t ic = sc->sc_tag;
529 	uint8_t buf[I2C_EXEC_MAX_BUFLEN];
530 	void *cmd = NULL;
531 	int error;
532 
533 	/* Validate parameters */
534 	if (iie->iie_addr > I2C_MAX_ADDR)
535 		return EINVAL;
536 	if (iie->iie_cmdlen > I2C_EXEC_MAX_CMDLEN ||
537 	    iie->iie_buflen > I2C_EXEC_MAX_BUFLEN)
538 		return EINVAL;
539 	if (iie->iie_cmd != NULL && iie->iie_cmdlen == 0)
540 		return EINVAL;
541 	if (iie->iie_buf != NULL && iie->iie_buflen == 0)
542 		return EINVAL;
543 	if (I2C_OP_WRITE_P(iie->iie_op) && (flag & FWRITE) == 0)
544 		return EBADF;
545 
546 #if 0
547 	/* Disallow userspace access to devices that have drivers attached. */
548 	if (sc->sc_devices[iie->iie_addr] != NULL)
549 		return EBUSY;
550 #endif
551 
552 	if (iie->iie_cmd != NULL) {
553 		cmd = kmem_alloc(iie->iie_cmdlen, KM_SLEEP);
554 		error = copyin(iie->iie_cmd, cmd, iie->iie_cmdlen);
555 		if (error)
556 			goto out;
557 	}
558 
559 	if (iie->iie_buf != NULL && I2C_OP_WRITE_P(iie->iie_op)) {
560 		error = copyin(iie->iie_buf, buf, iie->iie_buflen);
561 		if (error)
562 			goto out;
563 	}
564 
565 	iic_acquire_bus(ic, 0);
566 	error = iic_exec(ic, iie->iie_op, iie->iie_addr, cmd, iie->iie_cmdlen,
567 	    buf, iie->iie_buflen, 0);
568 	iic_release_bus(ic, 0);
569 
570 	/*
571 	 * Some drivers return error codes on failure, and others return -1.
572 	 */
573 	if (error < 0)
574 		error = EIO;
575 
576 out:
577 	if (cmd)
578 		kmem_free(cmd, iie->iie_cmdlen);
579 
580 	if (error)
581 		return error;
582 
583 	if (iie->iie_buf != NULL && I2C_OP_READ_P(iie->iie_op))
584 		error = copyout(buf, iie->iie_buf, iie->iie_buflen);
585 
586 	return error;
587 }
588 
589 static int
590 iic_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
591 {
592 	struct iic_softc *sc = device_lookup_private(&iic_cd, minor(dev));
593 
594 	if (sc == NULL)
595 		return ENXIO;
596 
597 	switch (cmd) {
598 	case I2C_IOCTL_EXEC:
599 		return iic_ioctl_exec(sc, (i2c_ioctl_exec_t *)data, flag);
600 	default:
601 		return ENODEV;
602 	}
603 }
604 
605 
606 CFATTACH_DECL2_NEW(iic, sizeof(struct iic_softc),
607     iic_match, iic_attach, iic_detach, NULL, iic_rescan, iic_child_detach);
608 
609 MODULE(MODULE_CLASS_DRIVER, iic, "i2cexec,i2c_bitbang");
610 
611 #ifdef _MODULE
612 #include "ioconf.c"
613 #endif
614 
615 int
616 iic_init(void)
617 {
618 
619 	mutex_init(&iic_mtx, MUTEX_DEFAULT, IPL_NONE);
620 	iic_refcnt = 0;
621 	return 0;
622 }
623 
624 static int
625 iic_modcmd(modcmd_t cmd, void *opaque)
626 {
627 #ifdef _MODULE
628 	int bmajor, cmajor;
629 #endif
630 	int error;
631 
632 	error = 0;
633 	switch (cmd) {
634 	case MODULE_CMD_INIT:
635 		RUN_ONCE(&iic_once, iic_init);
636 
637 #ifdef _MODULE
638 		mutex_enter(&iic_mtx);
639 		bmajor = cmajor = -1;
640 		error = devsw_attach("iic", NULL, &bmajor,
641 		    &iic_cdevsw, &cmajor);
642 		if (error != 0) {
643 			mutex_exit(&iic_mtx);
644 			break;
645 		}
646 		error = config_init_component(cfdriver_ioconf_iic,
647 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
648 		if (error) {
649 			aprint_error("%s: unable to init component\n",
650 			    iic_cd.cd_name);
651 			(void)devsw_detach(NULL, &iic_cdevsw);
652 		}
653 		mutex_exit(&iic_mtx);
654 #endif
655 		break;
656 	case MODULE_CMD_FINI:
657 		mutex_enter(&iic_mtx);
658 		if (iic_refcnt != 0) {
659 			mutex_exit(&iic_mtx);
660 			return EBUSY;
661 		}
662 #ifdef _MODULE
663 		error = config_fini_component(cfdriver_ioconf_iic,
664 		    cfattach_ioconf_iic, cfdata_ioconf_iic);
665 		if (error != 0) {
666 			mutex_exit(&iic_mtx);
667 			break;
668 		}
669 		error = devsw_detach(NULL, &iic_cdevsw);
670 		if (error != 0)
671 			config_init_component(cfdriver_ioconf_iic,
672 			    cfattach_ioconf_iic, cfdata_ioconf_iic);
673 #endif
674 		mutex_exit(&iic_mtx);
675 		break;
676 	default:
677 		error = ENOTTY;
678 	}
679 	return error;
680 }
681