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