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