xref: /netbsd-src/sys/dev/spi/spi.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /* $NetBSD: spi.c,v 1.12 2019/08/13 16:37:15 tnn Exp $ */
2 
3 /*-
4  * Copyright (c) 2006 Urbana-Champaign Independent Media Center.
5  * Copyright (c) 2006 Garrett D'Amore.
6  * All rights reserved.
7  *
8  * Portions of this code were written by Garrett D'Amore for the
9  * Champaign-Urbana Community Wireless Network Project.
10  *
11  * Redistribution and use in source and binary forms, with or
12  * without modification, are permitted provided that the following
13  * conditions 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
17  *    copyright notice, this list of conditions and the following
18  *    disclaimer in the documentation and/or other materials provided
19  *    with the distribution.
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgements:
22  *      This product includes software developed by the Urbana-Champaign
23  *      Independent Media Center.
24  *	This product includes software developed by Garrett D'Amore.
25  * 4. Urbana-Champaign Independent Media Center's name and Garrett
26  *    D'Amore's name may not be used to endorse or promote products
27  *    derived from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE URBANA-CHAMPAIGN INDEPENDENT
30  * MEDIA CENTER AND GARRETT D'AMORE ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
32  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE URBANA-CHAMPAIGN INDEPENDENT
34  * MEDIA CENTER OR GARRETT D'AMORE BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  */
43 
44 #include <sys/cdefs.h>
45 __KERNEL_RCSID(0, "$NetBSD: spi.c,v 1.12 2019/08/13 16:37:15 tnn Exp $");
46 
47 #include "locators.h"
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/device.h>
52 #include <sys/conf.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/condvar.h>
56 #include <sys/errno.h>
57 
58 #include <dev/spi/spivar.h>
59 #include <dev/spi/spi_io.h>
60 
61 #include "ioconf.h"
62 #include "locators.h"
63 
64 struct spi_softc {
65 	struct spi_controller	sc_controller;
66 	int			sc_mode;
67 	int			sc_speed;
68 	int			sc_slave;
69 	int			sc_nslaves;
70 	struct spi_handle	*sc_slaves;
71 	kmutex_t		sc_lock;
72 	kcondvar_t		sc_cv;
73 	int			sc_flags;
74 #define SPIC_BUSY		1
75 };
76 
77 static dev_type_open(spi_open);
78 static dev_type_close(spi_close);
79 static dev_type_ioctl(spi_ioctl);
80 
81 const struct cdevsw spi_cdevsw = {
82 	.d_open = spi_open,
83 	.d_close = spi_close,
84 	.d_read = noread,
85 	.d_write = nowrite,
86 	.d_ioctl = spi_ioctl,
87 	.d_stop = nostop,
88 	.d_tty = notty,
89 	.d_poll = nopoll,
90 	.d_mmap = nommap,
91 	.d_kqfilter = nokqfilter,
92 	.d_discard = nodiscard,
93 	.d_flag = D_OTHER
94 };
95 
96 /*
97  * SPI slave device.  We have one of these per slave.
98  */
99 struct spi_handle {
100 	struct spi_softc	*sh_sc;
101 	struct spi_controller	*sh_controller;
102 	int			sh_slave;
103 	int			sh_mode;
104 	int			sh_speed;
105 	int			sh_flags;
106 #define SPIH_ATTACHED		1
107 };
108 
109 #define SPI_MAXDATA 4096
110 
111 /*
112  * API for bus drivers.
113  */
114 
115 int
116 spibus_print(void *aux, const char *pnp)
117 {
118 
119 	if (pnp != NULL)
120 		aprint_normal("spi at %s", pnp);
121 
122 	return (UNCONF);
123 }
124 
125 
126 static int
127 spi_match(device_t parent, cfdata_t cf, void *aux)
128 {
129 
130 	return 1;
131 }
132 
133 static int
134 spi_print(void *aux, const char *pnp)
135 {
136 	struct spi_attach_args *sa = aux;
137 
138 	if (sa->sa_handle->sh_slave != -1)
139 		aprint_normal(" slave %d", sa->sa_handle->sh_slave);
140 
141 	return (UNCONF);
142 }
143 
144 static int
145 spi_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
146 {
147 	struct spi_softc *sc = device_private(parent);
148 	struct spi_attach_args sa;
149 	int addr;
150 
151 	addr = cf->cf_loc[SPICF_SLAVE];
152 	if ((addr < 0) || (addr >= sc->sc_controller.sct_nslaves)) {
153 		return -1;
154 	}
155 
156 	memset(&sa, 0, sizeof sa);
157 	sa.sa_handle = &sc->sc_slaves[addr];
158 	if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
159 		return -1;
160 
161 	if (config_match(parent, cf, &sa) > 0) {
162 		SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
163 		config_attach(parent, cf, &sa, spi_print);
164 	}
165 
166 	return 0;
167 }
168 
169 /*
170  * XXX this is the same as i2c_fill_compat. It could be refactored into a
171  * common fill_compat function with pointers to compat & ncompat instead
172  * of attach_args as the first parameter.
173  */
174 static void
175 spi_fill_compat(struct spi_attach_args *sa, const char *compat, size_t len,
176 	char **buffer)
177 {
178 	int count, i;
179 	const char *c, *start, **ptr;
180 
181 	*buffer = NULL;
182 	for (i = count = 0, c = compat; i < len; i++, c++)
183 		if (*c == 0)
184 			count++;
185 	count += 2;
186 	ptr = malloc(sizeof(char*)*count, M_TEMP, M_WAITOK);
187 	if (!ptr)
188 		return;
189 
190 	for (i = count = 0, start = c = compat; i < len; i++, c++) {
191 		if (*c == 0) {
192 			ptr[count++] = start;
193 			start = c + 1;
194 		}
195 	}
196 	if (start < compat + len) {
197 		/* last string not 0 terminated */
198 		size_t l = c - start;
199 		*buffer = malloc(l + 1, M_TEMP, M_WAITOK);
200 		memcpy(*buffer, start, l);
201 		(*buffer)[l] = 0;
202 		ptr[count++] = *buffer;
203 	}
204 	ptr[count] = NULL;
205 
206 	sa->sa_compat = ptr;
207 	sa->sa_ncompat = count;
208 }
209 
210 static void
211 spi_direct_attach_child_devices(device_t parent, struct spi_softc *sc,
212     prop_array_t child_devices)
213 {
214 	unsigned int count;
215 	prop_dictionary_t child;
216 	prop_data_t cdata;
217 	uint32_t slave;
218 	uint64_t cookie;
219 	struct spi_attach_args sa;
220 	int loc[SPICF_NLOCS];
221 	char *buf;
222 	int i;
223 
224 	memset(loc, 0, sizeof loc);
225 	count = prop_array_count(child_devices);
226 	for (i = 0; i < count; i++) {
227 		child = prop_array_get(child_devices, i);
228 		if (!child)
229 			continue;
230 		if (!prop_dictionary_get_uint32(child, "slave", &slave))
231 			continue;
232 		if(slave >= sc->sc_controller.sct_nslaves)
233 			continue;
234 		if (!prop_dictionary_get_uint64(child, "cookie", &cookie))
235 			continue;
236 		if (!(cdata = prop_dictionary_get(child, "compatible")))
237 			continue;
238 		loc[SPICF_SLAVE] = slave;
239 
240 		memset(&sa, 0, sizeof sa);
241 		sa.sa_handle = &sc->sc_slaves[i];
242 		if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
243 			continue;
244 		SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
245 
246 		buf = NULL;
247 		spi_fill_compat(&sa,
248 				prop_data_data_nocopy(cdata),
249 				prop_data_size(cdata), &buf);
250 		(void) config_found_sm_loc(parent, "spi",
251 					   loc, &sa, spi_print,
252 					   NULL);
253 
254 		if (sa.sa_compat)
255 			free(sa.sa_compat, M_TEMP);
256 		if (buf)
257 			free(buf, M_TEMP);
258 	}
259 }
260 
261 int
262 spi_compatible_match(const struct spi_attach_args *sa, const cfdata_t cf,
263 		     const struct device_compatible_entry *compats)
264 {
265 	if (sa->sa_ncompat > 0)
266 		return device_compatible_match(sa->sa_compat, sa->sa_ncompat,
267 					       compats, NULL);
268 
269 	return 1;
270 }
271 
272 /*
273  * API for device drivers.
274  *
275  * We provide wrapper routines to decouple the ABI for the SPI
276  * device drivers from the ABI for the SPI bus drivers.
277  */
278 static void
279 spi_attach(device_t parent, device_t self, void *aux)
280 {
281 	struct spi_softc *sc = device_private(self);
282 	struct spibus_attach_args *sba = aux;
283 	int i;
284 
285 	aprint_naive(": SPI bus\n");
286 	aprint_normal(": SPI bus\n");
287 
288 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_BIO);
289 	cv_init(&sc->sc_cv, "spictl");
290 
291 	sc->sc_controller = *sba->sba_controller;
292 	sc->sc_nslaves = sba->sba_controller->sct_nslaves;
293 	/* allocate slave structures */
294 	sc->sc_slaves = malloc(sizeof (struct spi_handle) * sc->sc_nslaves,
295 	    M_DEVBUF, M_WAITOK | M_ZERO);
296 
297 	sc->sc_speed = 0;
298 	sc->sc_mode = -1;
299 	sc->sc_slave = -1;
300 
301 	/*
302 	 * Initialize slave handles
303 	 */
304 	for (i = 0; i < sc->sc_nslaves; i++) {
305 		sc->sc_slaves[i].sh_slave = i;
306 		sc->sc_slaves[i].sh_sc = sc;
307 		sc->sc_slaves[i].sh_controller = &sc->sc_controller;
308 	}
309 
310 	/* First attach devices known to be present via fdt */
311 	if (sba->sba_child_devices) {
312 		spi_direct_attach_child_devices(self, sc, sba->sba_child_devices);
313 	}
314 	/* Then do any other devices the user may have manually wired */
315 	config_search_ia(spi_search, self, "spi", NULL);
316 }
317 
318 static int
319 spi_open(dev_t dev, int flag, int fmt, lwp_t *l)
320 {
321 	struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
322 
323 	if (sc == NULL)
324 		return ENXIO;
325 
326 	return 0;
327 }
328 
329 static int
330 spi_close(dev_t dev, int flag, int fmt, lwp_t *l)
331 {
332 
333 	return 0;
334 }
335 
336 static int
337 spi_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
338 {
339 	struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
340 	struct spi_handle *sh;
341 	spi_ioctl_configure_t *sic;
342 	spi_ioctl_transfer_t *sit;
343 	uint8_t *sbuf, *rbuf;
344 	int error;
345 
346 	if (sc == NULL)
347 		return ENXIO;
348 
349 	switch (cmd) {
350 	case SPI_IOCTL_CONFIGURE:
351 		sic = (spi_ioctl_configure_t *)data;
352 		if (sic->sic_addr < 0 || sic->sic_addr >= sc->sc_nslaves) {
353 			error = EINVAL;
354 			break;
355 		}
356 		sh = &sc->sc_slaves[sic->sic_addr];
357 		error = spi_configure(sh, sic->sic_mode, sic->sic_speed);
358 		break;
359 	case SPI_IOCTL_TRANSFER:
360 		sit = (spi_ioctl_transfer_t *)data;
361 		if (sit->sit_addr < 0 || sit->sit_addr >= sc->sc_nslaves) {
362 			error = EINVAL;
363 			break;
364 		}
365 		if ((sit->sit_send && sit->sit_sendlen == 0)
366 		    || (sit->sit_recv && sit->sit_recv == 0)) {
367 			error = EINVAL;
368 			break;
369 		}
370 		sh = &sc->sc_slaves[sit->sit_addr];
371 		sbuf = rbuf = NULL;
372 		error = 0;
373 		if (sit->sit_send && sit->sit_sendlen <= SPI_MAXDATA) {
374 			sbuf = malloc(sit->sit_sendlen, M_DEVBUF, M_WAITOK);
375 			error = copyin(sit->sit_send, sbuf, sit->sit_sendlen);
376 		}
377 		if (sit->sit_recv && sit->sit_recvlen <= SPI_MAXDATA) {
378 			rbuf = malloc(sit->sit_recvlen, M_DEVBUF, M_WAITOK);
379 		}
380 		if (error == 0) {
381 			if (sbuf && rbuf)
382 				error = spi_send_recv(sh,
383 					sit->sit_sendlen, sbuf,
384 					sit->sit_recvlen, rbuf);
385 			else if (sbuf)
386 				error = spi_send(sh,
387 					sit->sit_sendlen, sbuf);
388 			else if (rbuf)
389 				error = spi_recv(sh,
390 					sit->sit_recvlen, rbuf);
391 		}
392 		if (rbuf) {
393 			if (error == 0)
394 				error = copyout(rbuf, sit->sit_recv,
395 						sit->sit_recvlen);
396 			free(rbuf, M_DEVBUF);
397 		}
398 		if (sbuf) {
399 			free(sbuf, M_DEVBUF);
400 		}
401 		break;
402 	default:
403 		error = ENODEV;
404 		break;
405 	}
406 
407 	return error;
408 }
409 
410 CFATTACH_DECL_NEW(spi, sizeof(struct spi_softc),
411     spi_match, spi_attach, NULL, NULL);
412 
413 /*
414  * Configure.  This should be the first thing that the SPI driver
415  * should do, to configure which mode (e.g. SPI_MODE_0, which is the
416  * same as Philips Microwire mode), and speed.  If the bus driver
417  * cannot run fast enough, then it should just configure the fastest
418  * mode that it can support.  If the bus driver cannot run slow
419  * enough, then the device is incompatible and an error should be
420  * returned.
421  */
422 int
423 spi_configure(struct spi_handle *sh, int mode, int speed)
424 {
425 
426 	sh->sh_mode = mode;
427 	sh->sh_speed = speed;
428 	return 0;
429 }
430 
431 /*
432  * Acquire controller
433  */
434 static void
435 spi_acquire(struct spi_handle *sh)
436 {
437 	struct spi_softc *sc = sh->sh_sc;
438 
439 	mutex_enter(&sc->sc_lock);
440 	while ((sc->sc_flags & SPIC_BUSY) != 0)
441 		cv_wait(&sc->sc_cv, &sc->sc_lock);
442 	sc->sc_flags |= SPIC_BUSY;
443 	mutex_exit(&sc->sc_lock);
444 }
445 
446 /*
447  * Release controller
448  */
449 static void
450 spi_release(struct spi_handle *sh)
451 {
452 	struct spi_softc *sc = sh->sh_sc;
453 
454 	mutex_enter(&sc->sc_lock);
455 	sc->sc_flags &= ~SPIC_BUSY;
456 	cv_broadcast(&sc->sc_cv);
457 	mutex_exit(&sc->sc_lock);
458 }
459 
460 void
461 spi_transfer_init(struct spi_transfer *st)
462 {
463 
464 	mutex_init(&st->st_lock, MUTEX_DEFAULT, IPL_BIO);
465 	cv_init(&st->st_cv, "spixfr");
466 
467 	st->st_flags = 0;
468 	st->st_errno = 0;
469 	st->st_done = NULL;
470 	st->st_chunks = NULL;
471 	st->st_private = NULL;
472 	st->st_slave = -1;
473 }
474 
475 void
476 spi_chunk_init(struct spi_chunk *chunk, int cnt, const uint8_t *wptr,
477     uint8_t *rptr)
478 {
479 
480 	chunk->chunk_write = chunk->chunk_wptr = wptr;
481 	chunk->chunk_read = chunk->chunk_rptr = rptr;
482 	chunk->chunk_rresid = chunk->chunk_wresid = chunk->chunk_count = cnt;
483 	chunk->chunk_next = NULL;
484 }
485 
486 void
487 spi_transfer_add(struct spi_transfer *st, struct spi_chunk *chunk)
488 {
489 	struct spi_chunk **cpp;
490 
491 	/* this is an O(n) insert -- perhaps we should use a simpleq? */
492 	for (cpp = &st->st_chunks; *cpp; cpp = &(*cpp)->chunk_next);
493 	*cpp = chunk;
494 }
495 
496 int
497 spi_transfer(struct spi_handle *sh, struct spi_transfer *st)
498 {
499 	struct spi_softc	*sc = sh->sh_sc;
500 	struct spi_controller	*tag = sh->sh_controller;
501 	struct spi_chunk	*chunk;
502 	int error;
503 
504 	/*
505 	 * Initialize "resid" counters and pointers, so that callers
506 	 * and bus drivers don't have to.
507 	 */
508 	for (chunk = st->st_chunks; chunk; chunk = chunk->chunk_next) {
509 		chunk->chunk_wresid = chunk->chunk_rresid = chunk->chunk_count;
510 		chunk->chunk_wptr = chunk->chunk_write;
511 		chunk->chunk_rptr = chunk->chunk_read;
512 	}
513 
514 	/*
515 	 * Match slave and parameters to handle
516 	 */
517 	st->st_slave = sh->sh_slave;
518 
519 	/*
520 	 * Reserve controller during transaction
521  	 */
522 	spi_acquire(sh);
523 
524 	st->st_spiprivate = (void *)sh;
525 
526 	/*
527 	 * Reconfigure controller
528 	 *
529 	 * XXX backends don't configure per-slave parameters
530 	 * Whenever we switch slaves or change mode or speed, we
531 	 * need to tell the backend.
532 	 */
533 	if (sc->sc_slave != sh->sh_slave
534 	    || sc->sc_mode != sh->sh_mode
535 	    || sc->sc_speed != sh->sh_speed) {
536 		error = (*tag->sct_configure)(tag->sct_cookie,
537 				sh->sh_slave, sh->sh_mode, sh->sh_speed);
538 		if (error)
539 			return error;
540 	}
541 	sc->sc_mode = sh->sh_mode;
542 	sc->sc_speed = sh->sh_speed;
543 	sc->sc_slave = sh->sh_slave;
544 
545 	error = (*tag->sct_transfer)(tag->sct_cookie, st);
546 
547 	return error;
548 }
549 
550 void
551 spi_wait(struct spi_transfer *st)
552 {
553 	struct spi_handle *sh = st->st_spiprivate;
554 
555 	mutex_enter(&st->st_lock);
556 	while (!(st->st_flags & SPI_F_DONE)) {
557 		cv_wait(&st->st_cv, &st->st_lock);
558 	}
559 	mutex_exit(&st->st_lock);
560 	cv_destroy(&st->st_cv);
561 	mutex_destroy(&st->st_lock);
562 
563 	/*
564 	 * End transaction
565 	 */
566 	spi_release(sh);
567 }
568 
569 void
570 spi_done(struct spi_transfer *st, int err)
571 {
572 
573 	mutex_enter(&st->st_lock);
574 	if ((st->st_errno = err) != 0) {
575 		st->st_flags |= SPI_F_ERROR;
576 	}
577 	st->st_flags |= SPI_F_DONE;
578 	if (st->st_done != NULL) {
579 		(*st->st_done)(st);
580 	} else {
581 		cv_broadcast(&st->st_cv);
582 	}
583 	mutex_exit(&st->st_lock);
584 }
585 
586 /*
587  * Some convenience routines.  These routines block until the work
588  * is done.
589  *
590  * spi_recv - receives data from the bus
591  *
592  * spi_send - sends data to the bus
593  *
594  * spi_send_recv - sends data to the bus, and then receives.  Note that this is
595  * done synchronously, i.e. send a command and get the response.  This is
596  * not full duplex.  If you wnat full duplex, you can't use these convenience
597  * wrappers.
598  */
599 int
600 spi_recv(struct spi_handle *sh, int cnt, uint8_t *data)
601 {
602 	struct spi_transfer	trans;
603 	struct spi_chunk	chunk;
604 
605 	spi_transfer_init(&trans);
606 	spi_chunk_init(&chunk, cnt, NULL, data);
607 	spi_transfer_add(&trans, &chunk);
608 
609 	/* enqueue it and wait for it to complete */
610 	spi_transfer(sh, &trans);
611 	spi_wait(&trans);
612 
613 	if (trans.st_flags & SPI_F_ERROR)
614 		return trans.st_errno;
615 
616 	return 0;
617 }
618 
619 int
620 spi_send(struct spi_handle *sh, int cnt, const uint8_t *data)
621 {
622 	struct spi_transfer	trans;
623 	struct spi_chunk	chunk;
624 
625 	spi_transfer_init(&trans);
626 	spi_chunk_init(&chunk, cnt, data, NULL);
627 	spi_transfer_add(&trans, &chunk);
628 
629 	/* enqueue it and wait for it to complete */
630 	spi_transfer(sh, &trans);
631 	spi_wait(&trans);
632 
633 	if (trans.st_flags & SPI_F_ERROR)
634 		return trans.st_errno;
635 
636 	return 0;
637 }
638 
639 int
640 spi_send_recv(struct spi_handle *sh, int scnt, const uint8_t *snd,
641     int rcnt, uint8_t *rcv)
642 {
643 	struct spi_transfer	trans;
644 	struct spi_chunk	chunk1, chunk2;
645 
646 	spi_transfer_init(&trans);
647 	spi_chunk_init(&chunk1, scnt, snd, NULL);
648 	spi_chunk_init(&chunk2, rcnt, NULL, rcv);
649 	spi_transfer_add(&trans, &chunk1);
650 	spi_transfer_add(&trans, &chunk2);
651 
652 	/* enqueue it and wait for it to complete */
653 	spi_transfer(sh, &trans);
654 	spi_wait(&trans);
655 
656 	if (trans.st_flags & SPI_F_ERROR)
657 		return trans.st_errno;
658 
659 	return 0;
660 }
661 
662