Home | History | Annotate | Line # | Download | only in onewire
      1 /*	$NetBSD: onewire.c,v 1.23 2026/11/11 12:22:42 brad Exp $	*/
      2 /*	$OpenBSD: onewire.c,v 1.1 2006/03/04 16:27:03 grange Exp $	*/
      3 
      4 /*-
      5  * Copyright (c) 2019 The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Andrew Doran.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 2006 Alexander Yurchenko <grange (at) openbsd.org>
     35  *
     36  * Permission to use, copy, modify, and distribute this software for any
     37  * purpose with or without fee is hereby granted, provided that the above
     38  * copyright notice and this permission notice appear in all copies.
     39  *
     40  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     41  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     42  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     43  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     44  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     45  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     46  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     47  */
     48 
     49 #include <sys/cdefs.h>
     50 __KERNEL_RCSID(0, "$NetBSD: onewire.c,v 1.23 2026/11/11 12:22:42 brad Exp $");
     51 
     52 /*
     53  * 1-Wire bus driver.
     54  */
     55 
     56 #include <sys/param.h>
     57 #include <sys/systm.h>
     58 #include <sys/conf.h>
     59 #include <sys/device.h>
     60 #include <sys/kernel.h>
     61 #include <sys/kthread.h>
     62 #include <sys/kmem.h>
     63 #include <sys/proc.h>
     64 #include <sys/queue.h>
     65 #include <sys/module.h>
     66 
     67 #ifdef _KERNEL_OPT
     68 #include "opt_onewire.h"
     69 #endif
     70 
     71 #include <dev/onewire/onewirereg.h>
     72 #include <dev/onewire/onewirevar.h>
     73 
     74 #ifdef ONEWIRE_DEBUG
     75 #define DPRINTF(x) printf x
     76 #else
     77 #define DPRINTF(x)
     78 #endif
     79 
     80 int	onewire_maxdevs = 8;
     81 int	onewire_scantime = 10;	/* was 3 seconds - too often */
     82 
     83 struct onewire_softc {
     84 	device_t			sc_dev;
     85 	struct onewire_bus *		sc_bus;
     86 	kmutex_t			sc_lock;
     87 	kcondvar_t			sc_scancv;
     88 	struct lwp *			sc_thread;
     89 	TAILQ_HEAD(, onewire_device)	sc_devs;
     90 	int				sc_dying;
     91 };
     92 
     93 struct onewire_device {
     94 	TAILQ_ENTRY(onewire_device)	d_list;
     95 	device_t			d_dev;
     96 	u_int64_t			d_rom;
     97 	bool				d_present;
     98 };
     99 
    100 static int	onewire_match(device_t, cfdata_t, void *);
    101 static void	onewire_attach(device_t, device_t, void *);
    102 static int	onewire_detach(device_t, int);
    103 static int	onewire_activate(device_t, enum devact);
    104 int		onewire_print(void *, const char *);
    105 
    106 static void	onewire_thread(void *);
    107 static void	onewire_scan(struct onewire_softc *);
    108 
    109 CFATTACH_DECL_NEW(onewire, sizeof(struct onewire_softc),
    110 	onewire_match, onewire_attach, onewire_detach, onewire_activate);
    111 
    112 extern struct cfdriver onewire_cd;
    113 
    114 static int
    115 onewire_match(device_t parent, cfdata_t cf, void *aux)
    116 {
    117 	return 1;
    118 }
    119 
    120 static void
    121 onewire_attach(device_t parent, device_t self, void *aux)
    122 {
    123 	struct onewire_softc *sc = device_private(self);
    124 	struct onewirebus_attach_args *oba = aux;
    125 
    126 	sc->sc_dev = self;
    127 	sc->sc_bus = oba->oba_bus;
    128 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
    129 	cv_init(&sc->sc_scancv, "owscan");
    130 	TAILQ_INIT(&sc->sc_devs);
    131 
    132 	aprint_normal("\n");
    133 
    134 	if (kthread_create(PRI_NONE, KTHREAD_MUSTJOIN | KTHREAD_MPSAFE, NULL,
    135 	    onewire_thread, sc, &sc->sc_thread, "%s", device_xname(self)) != 0) {
    136 		aprint_error_dev(self, "can't create kernel thread\n");
    137 		/* Normally the kthread destroys these. */
    138 		mutex_destroy(&sc->sc_lock);
    139 		cv_destroy(&sc->sc_scancv);
    140 	}
    141 }
    142 
    143 static int
    144 onewire_detach(device_t self, int flags)
    145 {
    146 	struct onewire_softc *sc = device_private(self);
    147 	int rv;
    148 
    149 	if (sc->sc_thread != NULL) {
    150 		mutex_enter(&sc->sc_lock);
    151 		sc->sc_dying = 1;
    152 		cv_broadcast(&sc->sc_scancv);
    153 		mutex_exit(&sc->sc_lock);
    154 		/* Must no longer touch sc_lock nor sc_scancv. */
    155 		kthread_join(sc->sc_thread);
    156 	}
    157 
    158 	rv = config_detach_children(self, flags);
    159 
    160 	return rv;
    161 }
    162 
    163 static int
    164 onewire_activate(device_t self, enum devact act)
    165 {
    166 	struct onewire_softc *sc = device_private(self);
    167 
    168 	switch (act) {
    169 	case DVACT_DEACTIVATE:
    170 		sc->sc_dying = 1;
    171 		return 0;
    172 	default:
    173 		return EOPNOTSUPP;
    174 	}
    175 }
    176 
    177 int
    178 onewire_print(void *aux, const char *pnp)
    179 {
    180 	struct onewire_attach_args *oa = aux;
    181 	const char *famname;
    182 
    183 	if (pnp == NULL)
    184 		aprint_normal(" ");
    185 
    186 	famname = onewire_famname(ONEWIRE_ROM_FAMILY_TYPE(oa->oa_rom));
    187 	if (famname == NULL)
    188 		aprint_normal("family 0x%02x",
    189 		    (uint)ONEWIRE_ROM_FAMILY_TYPE(oa->oa_rom));
    190 	else
    191 		aprint_normal("\"%s\"", famname);
    192 	aprint_normal(" sn %012" PRIx64, ONEWIRE_ROM_SN(oa->oa_rom));
    193 
    194 	if (pnp != NULL)
    195 		aprint_normal(" at %s", pnp);
    196 
    197 	return UNCONF;
    198 }
    199 
    200 int
    201 onewirebus_print(void *aux, const char *pnp)
    202 {
    203 	if (pnp != NULL)
    204 		aprint_normal("onewire at %s", pnp);
    205 
    206 	return UNCONF;
    207 }
    208 
    209 void
    210 onewire_lock(void *arg)
    211 {
    212 	struct onewire_softc *sc = arg;
    213 
    214 	mutex_enter(&sc->sc_lock);
    215 }
    216 
    217 void
    218 onewire_unlock(void *arg)
    219 {
    220 	struct onewire_softc *sc = arg;
    221 
    222 	mutex_exit(&sc->sc_lock);
    223 }
    224 
    225 int
    226 onewire_reset(void *arg)
    227 {
    228 	struct onewire_softc *sc = arg;
    229 	struct onewire_bus *bus = sc->sc_bus;
    230 
    231 	KASSERT(mutex_owned(&sc->sc_lock));
    232 
    233 	return bus->bus_reset(bus->bus_cookie);
    234 }
    235 
    236 int
    237 onewire_read_bit(void *arg)
    238 {
    239 	struct onewire_softc *sc = arg;
    240 	struct onewire_bus *bus = sc->sc_bus;
    241 
    242 	KASSERT(mutex_owned(&sc->sc_lock));
    243 
    244 	return bus->bus_read_bit(bus->bus_cookie);
    245 }
    246 
    247 void
    248 onewire_write_bit(void *arg, int value)
    249 {
    250 	struct onewire_softc *sc = arg;
    251 	struct onewire_bus *bus = sc->sc_bus;
    252 
    253 	KASSERT(mutex_owned(&sc->sc_lock));
    254 
    255 	bus->bus_write_bit(bus->bus_cookie, value);
    256 }
    257 
    258 int
    259 onewire_read_byte(void *arg)
    260 {
    261 	struct onewire_softc *sc = arg;
    262 	struct onewire_bus *bus = sc->sc_bus;
    263 	uint8_t value = 0;
    264 	int i;
    265 
    266 	KASSERT(mutex_owned(&sc->sc_lock));
    267 
    268 	if (bus->bus_read_byte != NULL)
    269 		return bus->bus_read_byte(bus->bus_cookie);
    270 
    271 	for (i = 0; i < 8; i++)
    272 		value |= (bus->bus_read_bit(bus->bus_cookie) << i);
    273 
    274 	return value;
    275 }
    276 
    277 void
    278 onewire_write_byte(void *arg, int value)
    279 {
    280 	struct onewire_softc *sc = arg;
    281 	struct onewire_bus *bus = sc->sc_bus;
    282 	int i;
    283 
    284 	KASSERT(mutex_owned(&sc->sc_lock));
    285 
    286 	if (bus->bus_write_byte != NULL)
    287 		return bus->bus_write_byte(bus->bus_cookie, value);
    288 
    289 	for (i = 0; i < 8; i++)
    290 		bus->bus_write_bit(bus->bus_cookie, (value >> i) & 0x1);
    291 }
    292 
    293 int
    294 onewire_triplet(void *arg, int dir)
    295 {
    296 	struct onewire_softc *sc = arg;
    297 	struct onewire_bus *bus = sc->sc_bus;
    298 	int rv;
    299 
    300 	KASSERT(mutex_owned(&sc->sc_lock));
    301 
    302 	if (bus->bus_triplet != NULL)
    303 		return bus->bus_triplet(bus->bus_cookie, dir);
    304 
    305 	rv = bus->bus_read_bit(bus->bus_cookie);
    306 	rv <<= 1;
    307 	rv |= bus->bus_read_bit(bus->bus_cookie);
    308 
    309 	switch (rv) {
    310 	case 0x0:
    311 		bus->bus_write_bit(bus->bus_cookie, dir);
    312 		break;
    313 	case 0x1:
    314 		bus->bus_write_bit(bus->bus_cookie, 0);
    315 		break;
    316 	default:
    317 		bus->bus_write_bit(bus->bus_cookie, 1);
    318 	}
    319 
    320 	return rv;
    321 }
    322 
    323 void
    324 onewire_read_block(void *arg, void *buf, int len)
    325 {
    326 	struct onewire_softc *sc = arg;
    327 	uint8_t *p = buf;
    328 
    329 	KASSERT(mutex_owned(&sc->sc_lock));
    330 
    331 	while (len--)
    332 		*p++ = onewire_read_byte(sc);
    333 }
    334 
    335 void
    336 onewire_write_block(void *arg, const void *buf, int len)
    337 {
    338 	struct onewire_softc *sc = arg;
    339 	const uint8_t *p = buf;
    340 
    341 	KASSERT(mutex_owned(&sc->sc_lock));
    342 
    343 	while (len--)
    344 		onewire_write_byte(sc, *p++);
    345 }
    346 
    347 void
    348 onewire_matchrom(void *arg, u_int64_t rom)
    349 {
    350 	struct onewire_softc *sc = arg;
    351 	int i;
    352 
    353 	KASSERT(mutex_owned(&sc->sc_lock));
    354 
    355 	onewire_write_byte(sc, ONEWIRE_CMD_MATCH_ROM);
    356 	for (i = 0; i < 8; i++)
    357 		onewire_write_byte(sc, (rom >> (i * 8)) & 0xff);
    358 }
    359 
    360 static void
    361 onewire_thread(void *arg)
    362 {
    363 	struct onewire_softc *sc = arg;
    364 	int unit, dly;
    365 
    366 	/*
    367 	 * There can be many onewire busses, potentially funneled through
    368 	 * few GPIO controllers.  To avoid a thundering herd of kthreads and
    369 	 * resulting contention for the GPIO controller, spread the probes
    370 	 * out across an 8 second window.  The kthreads could converge later
    371 	 * due to timing effects.
    372 	 */
    373 	unit = device_unit(sc->sc_dev);
    374 	dly = (unit & 0x07) * hz + ((unit >> 3) * hz >> 3) + 1;
    375 	(void)kpause("owdly", false, dly, NULL);
    376 
    377 	mutex_enter(&sc->sc_lock);
    378 	while (!sc->sc_dying) {
    379 		onewire_scan(sc);
    380 		(void)cv_timedwait(&sc->sc_scancv, &sc->sc_lock,
    381 		    onewire_scantime * hz);
    382 	}
    383 	mutex_exit(&sc->sc_lock);
    384 
    385 	/* Caller has set sc_dying and will no longer touch these. */
    386 	cv_destroy(&sc->sc_scancv);
    387 	mutex_destroy(&sc->sc_lock);
    388 	kthread_exit(0);
    389 }
    390 
    391 static void
    392 onewire_scan(struct onewire_softc *sc)
    393 {
    394 	struct onewire_device *d, *next, *nd;
    395 	struct onewire_attach_args oa;
    396 	int search = 1, count = 0, present;
    397 	int dir, rv;
    398 	uint64_t mask, rom = 0, lastrom;
    399 	uint8_t data[8];
    400 	int i, i0 = -1, lastd = -1;
    401 
    402 	TAILQ_FOREACH(d, &sc->sc_devs, d_list) {
    403 		d->d_present = false;
    404 		KASSERT(d->d_dev != NULL);
    405 	}
    406 
    407 	KASSERT(mutex_owned(&sc->sc_lock));
    408 	KASSERT(curlwp == sc->sc_thread);
    409 
    410 	while (search && count++ < onewire_maxdevs) {
    411 		/*
    412 		 * Reset the bus, allowing for one retry if reset fails.  If
    413 		 * there's no presence pulse don't search for any devices.
    414 		 */
    415 		if (onewire_reset(sc) != 0) {
    416 			DPRINTF(("%s: scan: no presence pulse\n",
    417 			    device_xname(sc->sc_dev)));
    418 			if (onewire_reset(sc) != 0) {
    419 				DPRINTF(("%s: scan: retry failed\n",
    420 				    device_xname(sc->sc_dev)));
    421 				break;
    422 			}
    423 		}
    424 
    425 		/*
    426 		 * Start new search. Go through the previous path to
    427 		 * the point we made a decision last time and make an
    428 		 * opposite decision. If we didn't make any decision
    429 		 * stop searching.
    430 		 */
    431 		search = 0;
    432 		lastrom = rom;
    433 		rom = 0;
    434 		onewire_write_byte(sc, ONEWIRE_CMD_SEARCH_ROM);
    435 		for (i = 0,i0 = -1; i < 64; i++) {
    436 			dir = (lastrom >> i) & 0x1;
    437 			if (i == lastd)
    438 				dir = 1;
    439 			else if (i > lastd)
    440 				dir = 0;
    441 			rv = onewire_triplet(sc, dir);
    442 			switch (rv) {
    443 			case 0x0:
    444 				if (i != lastd) {
    445 					if (dir == 0)
    446 						i0 = i;
    447 					search = 1;
    448 				}
    449 				mask = dir;
    450 				break;
    451 			case 0x1:
    452 				mask = 0;
    453 				break;
    454 			case 0x2:
    455 				mask = 1;
    456 				break;
    457 			default:
    458 				DPRINTF(("%s: scan: triplet error 0x%x, "
    459 				    "step %d\n",
    460 				    device_xname(sc->sc_dev), rv, i));
    461 				return;
    462 			}
    463 			rom |= (mask << i);
    464 		}
    465 		lastd = i0;
    466 
    467 		/*
    468 		 * Yield processor, but continue to hold the lock
    469 		 * so that scan is not interrupted.
    470 		 */
    471 		(void)kpause("owscan", false, 1, NULL);
    472 
    473 		if (rom == 0)
    474 			continue;
    475 
    476 		/*
    477 		 * The last byte of the ROM code contains a CRC calculated
    478 		 * from the first 7 bytes. Re-calculate it to make sure
    479 		 * we found a valid device.
    480 		 */
    481 		for (i = 0; i < 8; i++)
    482 			data[i] = (rom >> (i * 8)) & 0xff;
    483 		if (onewire_crc(data, 7) != data[7])
    484 			continue;
    485 
    486 		/*
    487 		 * Go through the list of attached devices to see if we
    488 		 * found a new one.
    489 		 */
    490 		present = 0;
    491 	 	TAILQ_FOREACH(d, &sc->sc_devs, d_list) {
    492 			if (d->d_rom == rom) {
    493 				d->d_present = true;
    494 				present = 1;
    495 				break;
    496 			}
    497 		}
    498 		if (!present) {
    499 			nd = kmem_alloc(sizeof(*nd), KM_SLEEP);
    500 			nd->d_dev = NULL;
    501 			nd->d_rom = rom;
    502 			nd->d_present = true;
    503 			TAILQ_INSERT_TAIL(&sc->sc_devs, nd, d_list);
    504 		}
    505 	}
    506 
    507 	/*
    508 	 * Detach disappeared devices, and attach new devices.  Drop the
    509 	 * lock when doing this in order to prevent lock order reversal
    510 	 * against sysmon.  This is safe because nothing other than this
    511 	 * kthread modifies our device list.
    512 	 */
    513 	for (d = TAILQ_FIRST(&sc->sc_devs); d != NULL; d = next) {
    514 		next = TAILQ_NEXT(d, d_list);
    515 		if (!d->d_present) {
    516 			mutex_exit(&sc->sc_lock);
    517 
    518 			KERNEL_LOCK(1, NULL); /* XXXSMP */
    519 			config_detach(d->d_dev, DETACH_FORCE);
    520 			d->d_dev = NULL;
    521 			KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
    522 
    523 			mutex_enter(&sc->sc_lock);
    524 		} else if (d->d_dev == NULL) {
    525 			memset(&oa, 0, sizeof(oa));
    526 			oa.oa_onewire = sc;
    527 			oa.oa_rom = d->d_rom;
    528 			mutex_exit(&sc->sc_lock);
    529 
    530 			KERNEL_LOCK(1, NULL); /* XXXSMP */
    531 			d->d_dev = config_found(sc->sc_dev, &oa, onewire_print,
    532 			    CFARGS_NONE);
    533 			KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
    534 
    535 			mutex_enter(&sc->sc_lock);
    536 		}
    537 		if (d->d_dev == NULL) {
    538 			TAILQ_REMOVE(&sc->sc_devs, d, d_list);
    539 			kmem_free(d, sizeof(*d));
    540 		}
    541 	}
    542 }
    543 
    544 MODULE(MODULE_CLASS_DRIVER, onewire, NULL);
    545 
    546 #ifdef _MODULE
    547 #include "ioconf.c"
    548 #endif
    549 
    550 static int
    551 onewire_modcmd(modcmd_t cmd, void *opaque)
    552 {
    553 	int error;
    554 
    555 	error = 0;
    556 	switch (cmd) {
    557 	case MODULE_CMD_INIT:
    558 #ifdef _MODULE
    559 		error = config_init_component(cfdriver_ioconf_onewire,
    560 		    cfattach_ioconf_onewire, cfdata_ioconf_onewire);
    561 		if (error)
    562 			aprint_error("%s: unable to init component\n",
    563 			    onewire_cd.cd_name);
    564 #endif
    565 		break;
    566 	case MODULE_CMD_FINI:
    567 #ifdef _MODULE
    568 		config_fini_component(cfdriver_ioconf_onewire,
    569 		    cfattach_ioconf_onewire, cfdata_ioconf_onewire);
    570 #endif
    571 		break;
    572 	default:
    573 		error = ENOTTY;
    574 	}
    575 	return error;
    576 }
    577