spi.c revision 1.30 1 /* $NetBSD: spi.c,v 1.30 2025/09/10 04:33:46 thorpej 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 "opt_fdt.h" /* XXX */
45
46 #include <sys/cdefs.h>
47 __KERNEL_RCSID(0, "$NetBSD: spi.c,v 1.30 2025/09/10 04:33:46 thorpej Exp $");
48
49 #include "locators.h"
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/device.h>
54 #include <sys/conf.h>
55 #include <sys/malloc.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/errno.h>
59
60 #include <dev/spi/spivar.h>
61 #include <dev/spi/spi_io.h>
62
63 #ifdef FDT
64 #include <dev/fdt/fdt_spi.h> /* XXX */
65 #include <dev/ofw/openfirm.h> /* XXX */
66 #endif
67
68 #include "ioconf.h"
69 #include "locators.h"
70
71 struct spi_softc {
72 device_t sc_dev;
73 const struct spi_controller *sc_controller;
74 int sc_mode;
75 int sc_speed;
76 int sc_slave;
77 int sc_nslaves;
78 struct spi_handle *sc_slaves;
79 kmutex_t sc_lock;
80 kcondvar_t sc_cv;
81 kmutex_t sc_dev_lock;
82 int sc_flags;
83 #define SPIC_BUSY 1
84 };
85
86 static dev_type_open(spi_open);
87 static dev_type_close(spi_close);
88 static dev_type_ioctl(spi_ioctl);
89
90 const struct cdevsw spi_cdevsw = {
91 .d_open = spi_open,
92 .d_close = spi_close,
93 .d_read = noread,
94 .d_write = nowrite,
95 .d_ioctl = spi_ioctl,
96 .d_stop = nostop,
97 .d_tty = notty,
98 .d_poll = nopoll,
99 .d_mmap = nommap,
100 .d_kqfilter = nokqfilter,
101 .d_discard = nodiscard,
102 .d_flag = D_OTHER | D_MPSAFE
103 };
104
105 /*
106 * SPI slave device. We have one of these per slave.
107 */
108 struct spi_handle {
109 struct spi_softc *sh_sc;
110 const struct spi_controller *sh_controller;
111 int sh_slave;
112 int sh_mode;
113 int sh_speed;
114 int sh_flags;
115 #define SPIH_ATTACHED 1
116 };
117
118 #define SPI_MAXDATA 4096
119
120 /*
121 * API for bus drivers.
122 */
123
124 int
125 spibus_print(void *aux, const char *pnp)
126 {
127
128 if (pnp != NULL)
129 aprint_normal("spi at %s", pnp);
130
131 return (UNCONF);
132 }
133
134
135 static int
136 spi_match(device_t parent, cfdata_t cf, void *aux)
137 {
138
139 return 1;
140 }
141
142 static int
143 spi_print(void *aux, const char *pnp)
144 {
145 struct spi_attach_args *sa = aux;
146
147 if (sa->sa_handle->sh_slave != -1)
148 aprint_normal(" slave %d", sa->sa_handle->sh_slave);
149
150 return (UNCONF);
151 }
152
153 static int
154 spi_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
155 {
156 struct spi_softc *sc = device_private(parent);
157 struct spi_attach_args sa;
158 int addr;
159
160 addr = cf->cf_loc[SPICF_SLAVE];
161 if ((addr < 0) || (addr >= sc->sc_controller->sct_nslaves)) {
162 return -1;
163 }
164
165 memset(&sa, 0, sizeof sa);
166 sa.sa_handle = &sc->sc_slaves[addr];
167 if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
168 return -1;
169
170 if (config_probe(parent, cf, &sa)) {
171 SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
172 config_attach(parent, cf, &sa, spi_print, CFARGS_NONE);
173 }
174
175 return 0;
176 }
177
178 /*
179 * XXX this is the same as i2c_fill_compat. It could be refactored into a
180 * common fill_compat function with pointers to compat & ncompat instead
181 * of attach_args as the first parameter.
182 */
183 static void
184 spi_fill_compat(struct spi_attach_args *sa, const char *compat, size_t len,
185 char **buffer)
186 {
187 int count, i;
188 const char *c, *start, **ptr;
189
190 *buffer = NULL;
191 for (i = count = 0, c = compat; i < len; i++, c++)
192 if (*c == 0)
193 count++;
194 count += 2;
195 ptr = malloc(sizeof(char*)*count, M_TEMP, M_WAITOK);
196 if (!ptr)
197 return;
198
199 for (i = count = 0, start = c = compat; i < len; i++, c++) {
200 if (*c == 0) {
201 ptr[count++] = start;
202 start = c + 1;
203 }
204 }
205 if (start < compat + len) {
206 /* last string not 0 terminated */
207 size_t l = c - start;
208 *buffer = malloc(l + 1, M_TEMP, M_WAITOK);
209 memcpy(*buffer, start, l);
210 (*buffer)[l] = 0;
211 ptr[count++] = *buffer;
212 }
213 ptr[count] = NULL;
214
215 sa->sa_compat = ptr;
216 sa->sa_ncompat = count;
217 }
218
219 static void
220 spi_direct_attach_child_devices(struct spi_softc *sc)
221 {
222 unsigned int count;
223 prop_dictionary_t child;
224 prop_array_t child_devices;
225 prop_data_t cdata;
226 devhandle_t parent_handle = device_handle(sc->sc_dev);
227 devhandle_t child_handle;
228 uint32_t slave;
229 uint64_t cookie;
230 struct spi_attach_args sa;
231 int loc[SPICF_NLOCS];
232 char *buf;
233 int i;
234
235 /* XXX A better way is coming, I promise... */
236 switch (devhandle_type(parent_handle)) {
237 #ifdef FDT
238 case DEVHANDLE_TYPE_OF:
239 child_devices = of_copy_spi_devs(sc->sc_dev);
240 break;
241 #endif
242 default:
243 child_devices = NULL;
244 break;
245 }
246
247 if (child_devices == NULL) {
248 return;
249 }
250
251 memset(loc, 0, sizeof loc);
252 count = prop_array_count(child_devices);
253 for (i = 0; i < count; i++) {
254 child = prop_array_get(child_devices, i);
255 if (!child)
256 continue;
257 if (!prop_dictionary_get_uint32(child, "slave", &slave))
258 continue;
259 if (slave >= sc->sc_controller->sct_nslaves)
260 continue;
261 if (!prop_dictionary_get_uint64(child, "cookie", &cookie))
262 continue;
263 if (!(cdata = prop_dictionary_get(child, "compatible")))
264 continue;
265 loc[SPICF_SLAVE] = slave;
266
267 memset(&sa, 0, sizeof sa);
268 sa.sa_handle = &sc->sc_slaves[i];
269
270 /* XXX Really, I promise, it'll get better... */
271 switch (devhandle_type(parent_handle)) {
272 #ifdef FDT
273 case DEVHANDLE_TYPE_OF:
274 child_handle = devhandle_from_of(parent_handle,
275 (int)cookie);
276 break;
277 #endif
278 default:
279 child_handle = devhandle_invalid();
280 }
281
282 if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
283 continue;
284 SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
285
286 buf = NULL;
287 spi_fill_compat(&sa,
288 prop_data_value(cdata),
289 prop_data_size(cdata), &buf);
290 config_found(sc->sc_dev, &sa, spi_print,
291 CFARGS(.locators = loc,
292 .devhandle = child_handle));
293
294 if (sa.sa_compat)
295 free(sa.sa_compat, M_TEMP);
296 if (buf)
297 free(buf, M_TEMP);
298 }
299 prop_object_release(child_devices);
300 }
301
302 int
303 spi_compatible_match(const struct spi_attach_args *sa, const cfdata_t cf,
304 const struct device_compatible_entry *compats)
305 {
306 if (sa->sa_ncompat > 0)
307 return device_compatible_match(sa->sa_compat, sa->sa_ncompat,
308 compats);
309
310 return 1;
311 }
312
313 const struct device_compatible_entry *
314 spi_compatible_lookup(const struct spi_attach_args *sa,
315 const struct device_compatible_entry *compats)
316 {
317 return device_compatible_lookup(sa->sa_compat, sa->sa_ncompat,
318 compats);
319 }
320
321 /*
322 * API for device drivers.
323 *
324 * We provide wrapper routines to decouple the ABI for the SPI
325 * device drivers from the ABI for the SPI bus drivers.
326 */
327 static void
328 spi_attach(device_t parent, device_t self, void *aux)
329 {
330 struct spi_softc *sc = device_private(self);
331 struct spibus_attach_args *sba = aux;
332 int i;
333
334 aprint_naive(": SPI bus\n");
335 aprint_normal(": SPI bus\n");
336
337 mutex_init(&sc->sc_dev_lock, MUTEX_DEFAULT, IPL_NONE);
338 mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_VM);
339 cv_init(&sc->sc_cv, "spictl");
340
341 sc->sc_dev = self;
342 sc->sc_controller = sba->sba_controller;
343 sc->sc_nslaves = sba->sba_controller->sct_nslaves;
344 /* allocate slave structures */
345 sc->sc_slaves = malloc(sizeof (struct spi_handle) * sc->sc_nslaves,
346 M_DEVBUF, M_WAITOK | M_ZERO);
347
348 sc->sc_speed = 0;
349 sc->sc_mode = -1;
350 sc->sc_slave = -1;
351
352 /*
353 * Initialize slave handles
354 */
355 for (i = 0; i < sc->sc_nslaves; i++) {
356 sc->sc_slaves[i].sh_slave = i;
357 sc->sc_slaves[i].sh_sc = sc;
358 sc->sc_slaves[i].sh_controller = sc->sc_controller;
359 }
360
361 /* XXX Need a better way for this. */
362 switch (devhandle_type(device_handle(sc->sc_dev))) {
363 #ifdef FDT
364 case DEVHANDLE_TYPE_OF:
365 fdtbus_register_spi_controller(self, sc->sc_controller);
366 break;
367 #endif /* FDT */
368 default:
369 break;
370 }
371
372 /* First attach devices known to be present via the device tree. */
373 spi_direct_attach_child_devices(sc);
374
375 /* Then do any other devices the user may have manually wired */
376 config_search(self, NULL,
377 CFARGS(.search = spi_search));
378 }
379
380 static int
381 spi_open(dev_t dev, int flag, int fmt, lwp_t *l)
382 {
383 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
384
385 if (sc == NULL)
386 return ENXIO;
387
388 return 0;
389 }
390
391 static int
392 spi_close(dev_t dev, int flag, int fmt, lwp_t *l)
393 {
394
395 return 0;
396 }
397
398 static int
399 spi_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
400 {
401 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
402 struct spi_handle *sh;
403 spi_ioctl_configure_t *sic;
404 spi_ioctl_transfer_t *sit;
405 uint8_t *sbuf, *rbuf;
406 int error;
407
408 if (sc == NULL)
409 return ENXIO;
410
411 mutex_enter(&sc->sc_dev_lock);
412
413 switch (cmd) {
414 case SPI_IOCTL_CONFIGURE:
415 sic = (spi_ioctl_configure_t *)data;
416 if (sic->sic_addr < 0 || sic->sic_addr >= sc->sc_nslaves) {
417 error = EINVAL;
418 break;
419 }
420 sh = &sc->sc_slaves[sic->sic_addr];
421 error = spi_configure(sc->sc_dev, sh, sic->sic_mode,
422 sic->sic_speed);
423 break;
424 case SPI_IOCTL_TRANSFER:
425 sit = (spi_ioctl_transfer_t *)data;
426 if (sit->sit_addr < 0 || sit->sit_addr >= sc->sc_nslaves) {
427 error = EINVAL;
428 break;
429 }
430 if ((sit->sit_send && sit->sit_sendlen == 0)
431 || (sit->sit_recv && sit->sit_recvlen == 0)) {
432 error = EINVAL;
433 break;
434 }
435 sh = &sc->sc_slaves[sit->sit_addr];
436 sbuf = rbuf = NULL;
437 error = 0;
438 if (sit->sit_send && sit->sit_sendlen <= SPI_MAXDATA) {
439 sbuf = malloc(sit->sit_sendlen, M_DEVBUF, M_WAITOK);
440 error = copyin(sit->sit_send, sbuf, sit->sit_sendlen);
441 }
442 if (sit->sit_recv && sit->sit_recvlen <= SPI_MAXDATA) {
443 rbuf = malloc(sit->sit_recvlen, M_DEVBUF, M_WAITOK);
444 }
445 if (error == 0) {
446 if (sbuf && rbuf)
447 error = spi_send_recv(sh,
448 sit->sit_sendlen, sbuf,
449 sit->sit_recvlen, rbuf);
450 else if (sbuf)
451 error = spi_send(sh,
452 sit->sit_sendlen, sbuf);
453 else if (rbuf)
454 error = spi_recv(sh,
455 sit->sit_recvlen, rbuf);
456 }
457 if (rbuf) {
458 if (error == 0)
459 error = copyout(rbuf, sit->sit_recv,
460 sit->sit_recvlen);
461 free(rbuf, M_DEVBUF);
462 }
463 if (sbuf) {
464 free(sbuf, M_DEVBUF);
465 }
466 break;
467 default:
468 error = ENODEV;
469 break;
470 }
471
472 mutex_exit(&sc->sc_dev_lock);
473
474 return error;
475 }
476
477 CFATTACH_DECL_NEW(spi, sizeof(struct spi_softc),
478 spi_match, spi_attach, NULL, NULL);
479
480 /*
481 * Configure. This should be the first thing that the SPI driver
482 * should do, to configure which mode (e.g. SPI_MODE_0, which is the
483 * same as Philips Microwire mode), and speed. If the bus driver
484 * cannot run fast enough, then it should just configure the fastest
485 * mode that it can support. If the bus driver cannot run slow
486 * enough, then the device is incompatible and an error should be
487 * returned.
488 */
489 int
490 spi_configure(device_t dev __unused, struct spi_handle *sh, int mode, int speed)
491 {
492
493 sh->sh_mode = mode;
494 sh->sh_speed = speed;
495
496 /* No need to report errors; no failures. */
497
498 return 0;
499 }
500
501 /*
502 * Acquire controller
503 */
504 static void
505 spi_acquire(struct spi_handle *sh)
506 {
507 struct spi_softc *sc = sh->sh_sc;
508
509 mutex_enter(&sc->sc_lock);
510 while ((sc->sc_flags & SPIC_BUSY) != 0)
511 cv_wait(&sc->sc_cv, &sc->sc_lock);
512 sc->sc_flags |= SPIC_BUSY;
513 mutex_exit(&sc->sc_lock);
514 }
515
516 /*
517 * Release controller
518 */
519 static void
520 spi_release(struct spi_handle *sh)
521 {
522 struct spi_softc *sc = sh->sh_sc;
523
524 mutex_enter(&sc->sc_lock);
525 sc->sc_flags &= ~SPIC_BUSY;
526 cv_broadcast(&sc->sc_cv);
527 mutex_exit(&sc->sc_lock);
528 }
529
530 void
531 spi_transfer_init(struct spi_transfer *st)
532 {
533
534 mutex_init(&st->st_lock, MUTEX_DEFAULT, IPL_VM);
535 cv_init(&st->st_cv, "spixfr");
536
537 st->st_flags = 0;
538 st->st_errno = 0;
539 st->st_done = NULL;
540 st->st_chunks = NULL;
541 st->st_private = NULL;
542 st->st_slave = -1;
543 }
544
545 void
546 spi_chunk_init(struct spi_chunk *chunk, int cnt, const uint8_t *wptr,
547 uint8_t *rptr)
548 {
549
550 chunk->chunk_write = chunk->chunk_wptr = wptr;
551 chunk->chunk_read = chunk->chunk_rptr = rptr;
552 chunk->chunk_rresid = chunk->chunk_wresid = chunk->chunk_count = cnt;
553 chunk->chunk_next = NULL;
554 }
555
556 void
557 spi_transfer_add(struct spi_transfer *st, struct spi_chunk *chunk)
558 {
559 struct spi_chunk **cpp;
560
561 /* this is an O(n) insert -- perhaps we should use a simpleq? */
562 for (cpp = &st->st_chunks; *cpp; cpp = &(*cpp)->chunk_next);
563 *cpp = chunk;
564 }
565
566 int
567 spi_transfer(struct spi_handle *sh, struct spi_transfer *st)
568 {
569 struct spi_softc *sc = sh->sh_sc;
570 const struct spi_controller *tag = sh->sh_controller;
571 struct spi_chunk *chunk;
572 int error;
573
574 /*
575 * Initialize "resid" counters and pointers, so that callers
576 * and bus drivers don't have to.
577 */
578 for (chunk = st->st_chunks; chunk; chunk = chunk->chunk_next) {
579 chunk->chunk_wresid = chunk->chunk_rresid = chunk->chunk_count;
580 chunk->chunk_wptr = chunk->chunk_write;
581 chunk->chunk_rptr = chunk->chunk_read;
582 }
583
584 /*
585 * Match slave and parameters to handle
586 */
587 st->st_slave = sh->sh_slave;
588
589 /*
590 * Reserve controller during transaction
591 */
592 spi_acquire(sh);
593
594 st->st_spiprivate = (void *)sh;
595
596 /*
597 * Reconfigure controller
598 *
599 * XXX backends don't configure per-slave parameters
600 * Whenever we switch slaves or change mode or speed, we
601 * need to tell the backend.
602 */
603 if (sc->sc_slave != sh->sh_slave
604 || sc->sc_mode != sh->sh_mode
605 || sc->sc_speed != sh->sh_speed) {
606 error = (*tag->sct_configure)(tag->sct_cookie,
607 sh->sh_slave, sh->sh_mode, sh->sh_speed);
608 if (error)
609 return error;
610 }
611 sc->sc_mode = sh->sh_mode;
612 sc->sc_speed = sh->sh_speed;
613 sc->sc_slave = sh->sh_slave;
614
615 error = (*tag->sct_transfer)(tag->sct_cookie, st);
616
617 return error;
618 }
619
620 void
621 spi_wait(struct spi_transfer *st)
622 {
623 struct spi_handle *sh = st->st_spiprivate;
624
625 mutex_enter(&st->st_lock);
626 while (!(st->st_flags & SPI_F_DONE)) {
627 cv_wait(&st->st_cv, &st->st_lock);
628 }
629 mutex_exit(&st->st_lock);
630 cv_destroy(&st->st_cv);
631 mutex_destroy(&st->st_lock);
632
633 /*
634 * End transaction
635 */
636 spi_release(sh);
637 }
638
639 void
640 spi_done(struct spi_transfer *st, int err)
641 {
642
643 mutex_enter(&st->st_lock);
644 if ((st->st_errno = err) != 0) {
645 st->st_flags |= SPI_F_ERROR;
646 }
647 st->st_flags |= SPI_F_DONE;
648 if (st->st_done != NULL) {
649 (*st->st_done)(st);
650 } else {
651 cv_broadcast(&st->st_cv);
652 }
653 mutex_exit(&st->st_lock);
654 }
655
656 /*
657 * Some convenience routines. These routines block until the work
658 * is done.
659 *
660 * spi_recv - receives data from the bus
661 *
662 * spi_send - sends data to the bus
663 *
664 * spi_send_recv - sends data to the bus, and then receives. Note that this is
665 * done synchronously, i.e. send a command and get the response. This is
666 * not full duplex. If you want full duplex, you can't use these convenience
667 * wrappers.
668 */
669 int
670 spi_recv(struct spi_handle *sh, int cnt, uint8_t *data)
671 {
672 struct spi_transfer trans;
673 struct spi_chunk chunk;
674
675 spi_transfer_init(&trans);
676 spi_chunk_init(&chunk, cnt, NULL, data);
677 spi_transfer_add(&trans, &chunk);
678
679 /* enqueue it and wait for it to complete */
680 spi_transfer(sh, &trans);
681 spi_wait(&trans);
682
683 if (trans.st_flags & SPI_F_ERROR)
684 return trans.st_errno;
685
686 return 0;
687 }
688
689 int
690 spi_send(struct spi_handle *sh, int cnt, const uint8_t *data)
691 {
692 struct spi_transfer trans;
693 struct spi_chunk chunk;
694
695 spi_transfer_init(&trans);
696 spi_chunk_init(&chunk, cnt, data, NULL);
697 spi_transfer_add(&trans, &chunk);
698
699 /* enqueue it and wait for it to complete */
700 spi_transfer(sh, &trans);
701 spi_wait(&trans);
702
703 if (trans.st_flags & SPI_F_ERROR)
704 return trans.st_errno;
705
706 return 0;
707 }
708
709 int
710 spi_send_recv(struct spi_handle *sh, int scnt, const uint8_t *snd,
711 int rcnt, uint8_t *rcv)
712 {
713 struct spi_transfer trans;
714 struct spi_chunk chunk1, chunk2;
715
716 spi_transfer_init(&trans);
717 spi_chunk_init(&chunk1, scnt, snd, NULL);
718 spi_chunk_init(&chunk2, rcnt, NULL, rcv);
719 spi_transfer_add(&trans, &chunk1);
720 spi_transfer_add(&trans, &chunk2);
721
722 /* enqueue it and wait for it to complete */
723 spi_transfer(sh, &trans);
724 spi_wait(&trans);
725
726 if (trans.st_flags & SPI_F_ERROR)
727 return trans.st_errno;
728
729 return 0;
730 }
731