spi.c revision 1.29 1 /* $NetBSD: spi.c,v 1.29 2025/09/10 04:11:32 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.29 2025/09/10 04:11:32 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 uint32_t slave;
227 uint64_t cookie;
228 struct spi_attach_args sa;
229 int loc[SPICF_NLOCS];
230 char *buf;
231 int i;
232
233 /* XXX A better way is coming, I promise... */
234 switch (devhandle_type(device_handle(sc->sc_dev))) {
235 #ifdef FDT
236 case DEVHANDLE_TYPE_OF:
237 child_devices = of_copy_spi_devs(sc->sc_dev);
238 break;
239 #endif
240 default:
241 child_devices = NULL;
242 break;
243 }
244
245 if (child_devices == NULL) {
246 return;
247 }
248
249 memset(loc, 0, sizeof loc);
250 count = prop_array_count(child_devices);
251 for (i = 0; i < count; i++) {
252 child = prop_array_get(child_devices, i);
253 if (!child)
254 continue;
255 if (!prop_dictionary_get_uint32(child, "slave", &slave))
256 continue;
257 if (slave >= sc->sc_controller->sct_nslaves)
258 continue;
259 if (!prop_dictionary_get_uint64(child, "cookie", &cookie))
260 continue;
261 if (!(cdata = prop_dictionary_get(child, "compatible")))
262 continue;
263 loc[SPICF_SLAVE] = slave;
264
265 memset(&sa, 0, sizeof sa);
266 sa.sa_handle = &sc->sc_slaves[i];
267 sa.sa_prop = child;
268 sa.sa_cookie = cookie;
269 if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
270 continue;
271 SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
272
273 buf = NULL;
274 spi_fill_compat(&sa,
275 prop_data_value(cdata),
276 prop_data_size(cdata), &buf);
277 config_found(sc->sc_dev, &sa, spi_print,
278 CFARGS(.locators = loc));
279
280 if (sa.sa_compat)
281 free(sa.sa_compat, M_TEMP);
282 if (buf)
283 free(buf, M_TEMP);
284 }
285 prop_object_release(child_devices);
286 }
287
288 int
289 spi_compatible_match(const struct spi_attach_args *sa, const cfdata_t cf,
290 const struct device_compatible_entry *compats)
291 {
292 if (sa->sa_ncompat > 0)
293 return device_compatible_match(sa->sa_compat, sa->sa_ncompat,
294 compats);
295
296 return 1;
297 }
298
299 const struct device_compatible_entry *
300 spi_compatible_lookup(const struct spi_attach_args *sa,
301 const struct device_compatible_entry *compats)
302 {
303 return device_compatible_lookup(sa->sa_compat, sa->sa_ncompat,
304 compats);
305 }
306
307 /*
308 * API for device drivers.
309 *
310 * We provide wrapper routines to decouple the ABI for the SPI
311 * device drivers from the ABI for the SPI bus drivers.
312 */
313 static void
314 spi_attach(device_t parent, device_t self, void *aux)
315 {
316 struct spi_softc *sc = device_private(self);
317 struct spibus_attach_args *sba = aux;
318 int i;
319
320 aprint_naive(": SPI bus\n");
321 aprint_normal(": SPI bus\n");
322
323 mutex_init(&sc->sc_dev_lock, MUTEX_DEFAULT, IPL_NONE);
324 mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_VM);
325 cv_init(&sc->sc_cv, "spictl");
326
327 sc->sc_dev = self;
328 sc->sc_controller = sba->sba_controller;
329 sc->sc_nslaves = sba->sba_controller->sct_nslaves;
330 /* allocate slave structures */
331 sc->sc_slaves = malloc(sizeof (struct spi_handle) * sc->sc_nslaves,
332 M_DEVBUF, M_WAITOK | M_ZERO);
333
334 sc->sc_speed = 0;
335 sc->sc_mode = -1;
336 sc->sc_slave = -1;
337
338 /*
339 * Initialize slave handles
340 */
341 for (i = 0; i < sc->sc_nslaves; i++) {
342 sc->sc_slaves[i].sh_slave = i;
343 sc->sc_slaves[i].sh_sc = sc;
344 sc->sc_slaves[i].sh_controller = sc->sc_controller;
345 }
346
347 /* XXX Need a better way for this. */
348 switch (devhandle_type(device_handle(sc->sc_dev))) {
349 #ifdef FDT
350 case DEVHANDLE_TYPE_OF:
351 fdtbus_register_spi_controller(self, sc->sc_controller);
352 break;
353 #endif /* FDT */
354 default:
355 break;
356 }
357
358 /* First attach devices known to be present via the device tree. */
359 spi_direct_attach_child_devices(sc);
360
361 /* Then do any other devices the user may have manually wired */
362 config_search(self, NULL,
363 CFARGS(.search = spi_search));
364 }
365
366 static int
367 spi_open(dev_t dev, int flag, int fmt, lwp_t *l)
368 {
369 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
370
371 if (sc == NULL)
372 return ENXIO;
373
374 return 0;
375 }
376
377 static int
378 spi_close(dev_t dev, int flag, int fmt, lwp_t *l)
379 {
380
381 return 0;
382 }
383
384 static int
385 spi_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
386 {
387 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
388 struct spi_handle *sh;
389 spi_ioctl_configure_t *sic;
390 spi_ioctl_transfer_t *sit;
391 uint8_t *sbuf, *rbuf;
392 int error;
393
394 if (sc == NULL)
395 return ENXIO;
396
397 mutex_enter(&sc->sc_dev_lock);
398
399 switch (cmd) {
400 case SPI_IOCTL_CONFIGURE:
401 sic = (spi_ioctl_configure_t *)data;
402 if (sic->sic_addr < 0 || sic->sic_addr >= sc->sc_nslaves) {
403 error = EINVAL;
404 break;
405 }
406 sh = &sc->sc_slaves[sic->sic_addr];
407 error = spi_configure(sc->sc_dev, sh, sic->sic_mode,
408 sic->sic_speed);
409 break;
410 case SPI_IOCTL_TRANSFER:
411 sit = (spi_ioctl_transfer_t *)data;
412 if (sit->sit_addr < 0 || sit->sit_addr >= sc->sc_nslaves) {
413 error = EINVAL;
414 break;
415 }
416 if ((sit->sit_send && sit->sit_sendlen == 0)
417 || (sit->sit_recv && sit->sit_recvlen == 0)) {
418 error = EINVAL;
419 break;
420 }
421 sh = &sc->sc_slaves[sit->sit_addr];
422 sbuf = rbuf = NULL;
423 error = 0;
424 if (sit->sit_send && sit->sit_sendlen <= SPI_MAXDATA) {
425 sbuf = malloc(sit->sit_sendlen, M_DEVBUF, M_WAITOK);
426 error = copyin(sit->sit_send, sbuf, sit->sit_sendlen);
427 }
428 if (sit->sit_recv && sit->sit_recvlen <= SPI_MAXDATA) {
429 rbuf = malloc(sit->sit_recvlen, M_DEVBUF, M_WAITOK);
430 }
431 if (error == 0) {
432 if (sbuf && rbuf)
433 error = spi_send_recv(sh,
434 sit->sit_sendlen, sbuf,
435 sit->sit_recvlen, rbuf);
436 else if (sbuf)
437 error = spi_send(sh,
438 sit->sit_sendlen, sbuf);
439 else if (rbuf)
440 error = spi_recv(sh,
441 sit->sit_recvlen, rbuf);
442 }
443 if (rbuf) {
444 if (error == 0)
445 error = copyout(rbuf, sit->sit_recv,
446 sit->sit_recvlen);
447 free(rbuf, M_DEVBUF);
448 }
449 if (sbuf) {
450 free(sbuf, M_DEVBUF);
451 }
452 break;
453 default:
454 error = ENODEV;
455 break;
456 }
457
458 mutex_exit(&sc->sc_dev_lock);
459
460 return error;
461 }
462
463 CFATTACH_DECL_NEW(spi, sizeof(struct spi_softc),
464 spi_match, spi_attach, NULL, NULL);
465
466 /*
467 * Configure. This should be the first thing that the SPI driver
468 * should do, to configure which mode (e.g. SPI_MODE_0, which is the
469 * same as Philips Microwire mode), and speed. If the bus driver
470 * cannot run fast enough, then it should just configure the fastest
471 * mode that it can support. If the bus driver cannot run slow
472 * enough, then the device is incompatible and an error should be
473 * returned.
474 */
475 int
476 spi_configure(device_t dev __unused, struct spi_handle *sh, int mode, int speed)
477 {
478
479 sh->sh_mode = mode;
480 sh->sh_speed = speed;
481
482 /* No need to report errors; no failures. */
483
484 return 0;
485 }
486
487 /*
488 * Acquire controller
489 */
490 static void
491 spi_acquire(struct spi_handle *sh)
492 {
493 struct spi_softc *sc = sh->sh_sc;
494
495 mutex_enter(&sc->sc_lock);
496 while ((sc->sc_flags & SPIC_BUSY) != 0)
497 cv_wait(&sc->sc_cv, &sc->sc_lock);
498 sc->sc_flags |= SPIC_BUSY;
499 mutex_exit(&sc->sc_lock);
500 }
501
502 /*
503 * Release controller
504 */
505 static void
506 spi_release(struct spi_handle *sh)
507 {
508 struct spi_softc *sc = sh->sh_sc;
509
510 mutex_enter(&sc->sc_lock);
511 sc->sc_flags &= ~SPIC_BUSY;
512 cv_broadcast(&sc->sc_cv);
513 mutex_exit(&sc->sc_lock);
514 }
515
516 void
517 spi_transfer_init(struct spi_transfer *st)
518 {
519
520 mutex_init(&st->st_lock, MUTEX_DEFAULT, IPL_VM);
521 cv_init(&st->st_cv, "spixfr");
522
523 st->st_flags = 0;
524 st->st_errno = 0;
525 st->st_done = NULL;
526 st->st_chunks = NULL;
527 st->st_private = NULL;
528 st->st_slave = -1;
529 }
530
531 void
532 spi_chunk_init(struct spi_chunk *chunk, int cnt, const uint8_t *wptr,
533 uint8_t *rptr)
534 {
535
536 chunk->chunk_write = chunk->chunk_wptr = wptr;
537 chunk->chunk_read = chunk->chunk_rptr = rptr;
538 chunk->chunk_rresid = chunk->chunk_wresid = chunk->chunk_count = cnt;
539 chunk->chunk_next = NULL;
540 }
541
542 void
543 spi_transfer_add(struct spi_transfer *st, struct spi_chunk *chunk)
544 {
545 struct spi_chunk **cpp;
546
547 /* this is an O(n) insert -- perhaps we should use a simpleq? */
548 for (cpp = &st->st_chunks; *cpp; cpp = &(*cpp)->chunk_next);
549 *cpp = chunk;
550 }
551
552 int
553 spi_transfer(struct spi_handle *sh, struct spi_transfer *st)
554 {
555 struct spi_softc *sc = sh->sh_sc;
556 const struct spi_controller *tag = sh->sh_controller;
557 struct spi_chunk *chunk;
558 int error;
559
560 /*
561 * Initialize "resid" counters and pointers, so that callers
562 * and bus drivers don't have to.
563 */
564 for (chunk = st->st_chunks; chunk; chunk = chunk->chunk_next) {
565 chunk->chunk_wresid = chunk->chunk_rresid = chunk->chunk_count;
566 chunk->chunk_wptr = chunk->chunk_write;
567 chunk->chunk_rptr = chunk->chunk_read;
568 }
569
570 /*
571 * Match slave and parameters to handle
572 */
573 st->st_slave = sh->sh_slave;
574
575 /*
576 * Reserve controller during transaction
577 */
578 spi_acquire(sh);
579
580 st->st_spiprivate = (void *)sh;
581
582 /*
583 * Reconfigure controller
584 *
585 * XXX backends don't configure per-slave parameters
586 * Whenever we switch slaves or change mode or speed, we
587 * need to tell the backend.
588 */
589 if (sc->sc_slave != sh->sh_slave
590 || sc->sc_mode != sh->sh_mode
591 || sc->sc_speed != sh->sh_speed) {
592 error = (*tag->sct_configure)(tag->sct_cookie,
593 sh->sh_slave, sh->sh_mode, sh->sh_speed);
594 if (error)
595 return error;
596 }
597 sc->sc_mode = sh->sh_mode;
598 sc->sc_speed = sh->sh_speed;
599 sc->sc_slave = sh->sh_slave;
600
601 error = (*tag->sct_transfer)(tag->sct_cookie, st);
602
603 return error;
604 }
605
606 void
607 spi_wait(struct spi_transfer *st)
608 {
609 struct spi_handle *sh = st->st_spiprivate;
610
611 mutex_enter(&st->st_lock);
612 while (!(st->st_flags & SPI_F_DONE)) {
613 cv_wait(&st->st_cv, &st->st_lock);
614 }
615 mutex_exit(&st->st_lock);
616 cv_destroy(&st->st_cv);
617 mutex_destroy(&st->st_lock);
618
619 /*
620 * End transaction
621 */
622 spi_release(sh);
623 }
624
625 void
626 spi_done(struct spi_transfer *st, int err)
627 {
628
629 mutex_enter(&st->st_lock);
630 if ((st->st_errno = err) != 0) {
631 st->st_flags |= SPI_F_ERROR;
632 }
633 st->st_flags |= SPI_F_DONE;
634 if (st->st_done != NULL) {
635 (*st->st_done)(st);
636 } else {
637 cv_broadcast(&st->st_cv);
638 }
639 mutex_exit(&st->st_lock);
640 }
641
642 /*
643 * Some convenience routines. These routines block until the work
644 * is done.
645 *
646 * spi_recv - receives data from the bus
647 *
648 * spi_send - sends data to the bus
649 *
650 * spi_send_recv - sends data to the bus, and then receives. Note that this is
651 * done synchronously, i.e. send a command and get the response. This is
652 * not full duplex. If you want full duplex, you can't use these convenience
653 * wrappers.
654 */
655 int
656 spi_recv(struct spi_handle *sh, int cnt, uint8_t *data)
657 {
658 struct spi_transfer trans;
659 struct spi_chunk chunk;
660
661 spi_transfer_init(&trans);
662 spi_chunk_init(&chunk, cnt, NULL, data);
663 spi_transfer_add(&trans, &chunk);
664
665 /* enqueue it and wait for it to complete */
666 spi_transfer(sh, &trans);
667 spi_wait(&trans);
668
669 if (trans.st_flags & SPI_F_ERROR)
670 return trans.st_errno;
671
672 return 0;
673 }
674
675 int
676 spi_send(struct spi_handle *sh, int cnt, const uint8_t *data)
677 {
678 struct spi_transfer trans;
679 struct spi_chunk chunk;
680
681 spi_transfer_init(&trans);
682 spi_chunk_init(&chunk, cnt, data, NULL);
683 spi_transfer_add(&trans, &chunk);
684
685 /* enqueue it and wait for it to complete */
686 spi_transfer(sh, &trans);
687 spi_wait(&trans);
688
689 if (trans.st_flags & SPI_F_ERROR)
690 return trans.st_errno;
691
692 return 0;
693 }
694
695 int
696 spi_send_recv(struct spi_handle *sh, int scnt, const uint8_t *snd,
697 int rcnt, uint8_t *rcv)
698 {
699 struct spi_transfer trans;
700 struct spi_chunk chunk1, chunk2;
701
702 spi_transfer_init(&trans);
703 spi_chunk_init(&chunk1, scnt, snd, NULL);
704 spi_chunk_init(&chunk2, rcnt, NULL, rcv);
705 spi_transfer_add(&trans, &chunk1);
706 spi_transfer_add(&trans, &chunk2);
707
708 /* enqueue it and wait for it to complete */
709 spi_transfer(sh, &trans);
710 spi_wait(&trans);
711
712 if (trans.st_flags & SPI_F_ERROR)
713 return trans.st_errno;
714
715 return 0;
716 }
717