spi.c revision 1.19.2.1 1 /* $NetBSD: spi.c,v 1.19.2.1 2021/08/09 00:30:09 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 <sys/cdefs.h>
45 __KERNEL_RCSID(0, "$NetBSD: spi.c,v 1.19.2.1 2021/08/09 00:30:09 thorpej 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/kmem.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 device_t sc_dev;
66 struct spi_controller sc_controller;
67 int sc_mode;
68 int sc_speed;
69 int sc_slave;
70 int sc_nslaves;
71 struct spi_handle *sc_slaves;
72 kmutex_t sc_slave_state_lock;
73 kmutex_t sc_lock;
74 kcondvar_t sc_cv;
75 kmutex_t sc_dev_lock;
76 int sc_flags;
77 #define SPIC_BUSY 1
78 };
79
80 static dev_type_open(spi_open);
81 static dev_type_close(spi_close);
82 static dev_type_ioctl(spi_ioctl);
83
84 const struct cdevsw spi_cdevsw = {
85 .d_open = spi_open,
86 .d_close = spi_close,
87 .d_read = noread,
88 .d_write = nowrite,
89 .d_ioctl = spi_ioctl,
90 .d_stop = nostop,
91 .d_tty = notty,
92 .d_poll = nopoll,
93 .d_mmap = nommap,
94 .d_kqfilter = nokqfilter,
95 .d_discard = nodiscard,
96 .d_flag = D_OTHER | D_MPSAFE
97 };
98
99 /*
100 * SPI slave device. We have one of these per slave.
101 */
102 struct spi_handle {
103 struct spi_softc *sh_sc; /* static */
104 struct spi_controller *sh_controller; /* static */
105 int sh_slave; /* static */
106 int sh_mode; /* locked by owning child */
107 int sh_speed; /* locked by owning child */
108 int sh_flags; /* ^^ slave_state_lock ^^ */
109 #define SPIH_ATTACHED __BIT(0)
110 #define SPIH_DIRECT __BIT(1)
111 };
112
113 #define SPI_MAXDATA 4096
114
115 /*
116 * API for bus drivers.
117 */
118
119 int
120 spibus_print(void *aux, const char *pnp)
121 {
122
123 if (pnp != NULL)
124 aprint_normal("spi at %s", pnp);
125
126 return (UNCONF);
127 }
128
129
130 static int
131 spi_match(device_t parent, cfdata_t cf, void *aux)
132 {
133
134 return 1;
135 }
136
137 static int
138 spi_print_direct(void *aux, const char *pnp)
139 {
140 struct spi_attach_args *sa = aux;
141
142 if (pnp != NULL) {
143 aprint_normal("%s%s%s%s at %s slave %d",
144 sa->sa_name ? sa->sa_name : "(unknown)",
145 sa->sa_clist ? " (" : "",
146 sa->sa_clist ? sa->sa_clist : "",
147 sa->sa_clist ? ")" : "",
148 pnp, sa->sa_handle->sh_slave);
149 } else {
150 aprint_normal(" slave %d", sa->sa_handle->sh_slave);
151 }
152
153 return UNCONF;
154 }
155
156 static int
157 spi_print(void *aux, const char *pnp)
158 {
159 struct spi_attach_args *sa = aux;
160
161 aprint_normal(" slave %d", sa->sa_handle->sh_slave);
162
163 return UNCONF;
164 }
165
166 /*
167 * Direct and indrect for SPI are pretty similar, so we can collapse
168 * them into a single function.
169 */
170 static void
171 spi_attach_child(struct spi_softc *sc, struct spi_attach_args *sa,
172 int chip_select, cfdata_t cf)
173 {
174 struct spi_handle *sh;
175 device_t newdev = NULL;
176 bool is_direct = cf == NULL;
177 const int skip_flags = is_direct ? SPIH_ATTACHED
178 : (SPIH_ATTACHED | SPIH_DIRECT);
179 const int claim_flags = skip_flags ^ SPIH_DIRECT;
180 int locs[SPICF_NLOCS] = { 0 };
181
182 if (chip_select < 0 ||
183 chip_select >= sc->sc_controller.sct_nslaves) {
184 return;
185 }
186
187 sh = &sc->sc_slaves[chip_select];
188
189 mutex_enter(&sc->sc_slave_state_lock);
190 if (ISSET(sh->sh_flags, skip_flags)) {
191 mutex_exit(&sc->sc_slave_state_lock);
192 return;
193 }
194
195 /* Keep others off of this chip select. */
196 SET(sh->sh_flags, claim_flags);
197 mutex_exit(&sc->sc_slave_state_lock);
198
199 locs[SPICF_SLAVE] = chip_select;
200 sa->sa_handle = sh;
201
202 if (is_direct) {
203 newdev = config_found(sc->sc_dev, sa, spi_print_direct,
204 CFARGS(/* .submatch = config_stdsubmatch, XXX */
205 .locators = locs,
206 .devhandle = sa->sa_devhandle));
207 } else {
208 if (config_probe(sc->sc_dev, cf, &sa)) {
209 newdev = config_attach(sc->sc_dev, cf, &sa, spi_print,
210 CFARGS(.locators = locs));
211 }
212 }
213
214 if (newdev == NULL) {
215 /*
216 * Clear our claim on this chip select (yes, just
217 * the ATTACHED flag; we want to keep indirects off
218 * of chip selects for which there is a device tree
219 * node).
220 */
221 mutex_enter(&sc->sc_slave_state_lock);
222 CLR(sh->sh_flags, SPIH_ATTACHED);
223 mutex_exit(&sc->sc_slave_state_lock);
224 }
225 }
226
227 static int
228 spi_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
229 {
230 struct spi_softc *sc = device_private(parent);
231 struct spi_attach_args sa;
232
233 if (cf->cf_loc[SPICF_SLAVE] == SPICF_SLAVE_DEFAULT) {
234 /* No wildcards for indirect on SPI. */
235 return 0;
236 }
237
238 memset(&sa, 0, sizeof(sa));
239 spi_attach_child(sc, &sa, cf->cf_loc[SPICF_SLAVE], cf);
240
241 return 0;
242 }
243
244 static bool
245 spi_enumerate_devices_callback(device_t self,
246 struct spi_enumerate_devices_args *args)
247 {
248 struct spi_softc *sc = device_private(self);
249
250 spi_attach_child(sc, args->sa, args->chip_select, NULL);
251
252 return true; /* keep enumerating */
253 }
254
255 int
256 spi_compatible_match(const struct spi_attach_args *sa, const cfdata_t cf,
257 const struct device_compatible_entry *compats)
258 {
259 if (sa->sa_clist != NULL) {
260 return device_compatible_match_strlist(sa->sa_clist,
261 sa->sa_clist_size, compats);
262 }
263
264 /*
265 * In this case, we're using indirect configuration, but SPI
266 * has no real addressing system, and we've filtered out
267 * wildcarded chip selects in spi_search(), so we have no
268 * choice but to trust the user-specified config.
269 */
270 return 1;
271 }
272
273 static void
274 spi_attach(device_t parent, device_t self, void *aux)
275 {
276 struct spi_softc *sc = device_private(self);
277 struct spibus_attach_args *sba = aux;
278 int i;
279
280 sc->sc_dev = self;
281
282 aprint_naive(": SPI bus\n");
283 aprint_normal(": SPI bus\n");
284
285 mutex_init(&sc->sc_dev_lock, MUTEX_DEFAULT, IPL_NONE);
286 mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_VM);
287 mutex_init(&sc->sc_slave_state_lock, MUTEX_DEFAULT, IPL_NONE);
288 cv_init(&sc->sc_cv, "spictl");
289
290 sc->sc_controller = *sba->sba_controller;
291 sc->sc_nslaves = sba->sba_controller->sct_nslaves;
292
293 /* allocate slave structures */
294 sc->sc_slaves = kmem_zalloc(sizeof(*sc->sc_slaves) * sc->sc_nslaves,
295 KM_SLEEP);
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 /*
311 * Attempt to enumerate the devices on the bus using the
312 * platform device tree.
313 */
314 struct spi_attach_args sa = { 0 };
315 struct spi_enumerate_devices_args enumargs = {
316 .sa = &sa,
317 .callback = spi_enumerate_devices_callback,
318 };
319 device_call(self, "spi-enumerate-devices", &enumargs);
320
321 /* Then do any other devices the user may have manually wired */
322 config_search(self, NULL,
323 CFARGS(.search = spi_search));
324 }
325
326 CFATTACH_DECL_NEW(spi, sizeof(struct spi_softc),
327 spi_match, spi_attach, NULL, NULL);
328
329 static int
330 spi_open(dev_t dev, int flag, int fmt, lwp_t *l)
331 {
332 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
333
334 if (sc == NULL)
335 return ENXIO;
336
337 return 0;
338 }
339
340 static int
341 spi_close(dev_t dev, int flag, int fmt, lwp_t *l)
342 {
343
344 return 0;
345 }
346
347 static int
348 spi_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
349 {
350 struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
351 struct spi_handle *sh;
352 spi_ioctl_configure_t *sic;
353 spi_ioctl_transfer_t *sit;
354 uint8_t *sbuf, *rbuf;
355 int error;
356
357 if (sc == NULL)
358 return ENXIO;
359
360 mutex_enter(&sc->sc_dev_lock);
361
362 switch (cmd) {
363 case SPI_IOCTL_CONFIGURE:
364 sic = (spi_ioctl_configure_t *)data;
365 if (sic->sic_addr < 0 || sic->sic_addr >= sc->sc_nslaves) {
366 error = EINVAL;
367 break;
368 }
369 sh = &sc->sc_slaves[sic->sic_addr];
370 error = spi_configure(sh, sic->sic_mode, sic->sic_speed);
371 break;
372 case SPI_IOCTL_TRANSFER:
373 sit = (spi_ioctl_transfer_t *)data;
374 if (sit->sit_addr < 0 || sit->sit_addr >= sc->sc_nslaves) {
375 error = EINVAL;
376 break;
377 }
378 if ((sit->sit_send && sit->sit_sendlen == 0)
379 || (sit->sit_recv && sit->sit_recv == 0)) {
380 error = EINVAL;
381 break;
382 }
383 sh = &sc->sc_slaves[sit->sit_addr];
384 sbuf = rbuf = NULL;
385 error = 0;
386 if (sit->sit_send && sit->sit_sendlen <= SPI_MAXDATA) {
387 sbuf = kmem_alloc(sit->sit_sendlen, KM_SLEEP);
388 error = copyin(sit->sit_send, sbuf, sit->sit_sendlen);
389 }
390 if (sit->sit_recv && sit->sit_recvlen <= SPI_MAXDATA) {
391 rbuf = kmem_alloc(sit->sit_recvlen, KM_SLEEP);
392 }
393 if (error == 0) {
394 if (sbuf && rbuf)
395 error = spi_send_recv(sh,
396 sit->sit_sendlen, sbuf,
397 sit->sit_recvlen, rbuf);
398 else if (sbuf)
399 error = spi_send(sh,
400 sit->sit_sendlen, sbuf);
401 else if (rbuf)
402 error = spi_recv(sh,
403 sit->sit_recvlen, rbuf);
404 }
405 if (rbuf) {
406 if (error == 0)
407 error = copyout(rbuf, sit->sit_recv,
408 sit->sit_recvlen);
409 kmem_free(rbuf, sit->sit_recvlen);
410 }
411 if (sbuf) {
412 kmem_free(sbuf, sit->sit_sendlen);
413 }
414 break;
415 default:
416 error = ENODEV;
417 break;
418 }
419
420 mutex_exit(&sc->sc_dev_lock);
421
422 return error;
423 }
424
425 /*
426 * API for device drivers.
427 *
428 * We provide wrapper routines to decouple the ABI for the SPI
429 * device drivers from the ABI for the SPI bus drivers.
430 */
431
432 /*
433 * Configure. This should be the first thing that the SPI driver
434 * should do, to configure which mode (e.g. SPI_MODE_0, which is the
435 * same as Philips Microwire mode), and speed. If the bus driver
436 * cannot run fast enough, then it should just configure the fastest
437 * mode that it can support. If the bus driver cannot run slow
438 * enough, then the device is incompatible and an error should be
439 * returned.
440 */
441 int
442 spi_configure(struct spi_handle *sh, int mode, int speed)
443 {
444
445 sh->sh_mode = mode;
446 sh->sh_speed = speed;
447 return 0;
448 }
449
450 /*
451 * Acquire controller
452 */
453 static void
454 spi_acquire(struct spi_handle *sh)
455 {
456 struct spi_softc *sc = sh->sh_sc;
457
458 mutex_enter(&sc->sc_lock);
459 while ((sc->sc_flags & SPIC_BUSY) != 0)
460 cv_wait(&sc->sc_cv, &sc->sc_lock);
461 sc->sc_flags |= SPIC_BUSY;
462 mutex_exit(&sc->sc_lock);
463 }
464
465 /*
466 * Release controller
467 */
468 static void
469 spi_release(struct spi_handle *sh)
470 {
471 struct spi_softc *sc = sh->sh_sc;
472
473 mutex_enter(&sc->sc_lock);
474 sc->sc_flags &= ~SPIC_BUSY;
475 cv_broadcast(&sc->sc_cv);
476 mutex_exit(&sc->sc_lock);
477 }
478
479 void
480 spi_transfer_init(struct spi_transfer *st)
481 {
482
483 mutex_init(&st->st_lock, MUTEX_DEFAULT, IPL_VM);
484 cv_init(&st->st_cv, "spixfr");
485
486 st->st_flags = 0;
487 st->st_errno = 0;
488 st->st_done = NULL;
489 st->st_chunks = NULL;
490 st->st_private = NULL;
491 st->st_slave = -1;
492 }
493
494 void
495 spi_chunk_init(struct spi_chunk *chunk, int cnt, const uint8_t *wptr,
496 uint8_t *rptr)
497 {
498
499 chunk->chunk_write = chunk->chunk_wptr = wptr;
500 chunk->chunk_read = chunk->chunk_rptr = rptr;
501 chunk->chunk_rresid = chunk->chunk_wresid = chunk->chunk_count = cnt;
502 chunk->chunk_next = NULL;
503 }
504
505 void
506 spi_transfer_add(struct spi_transfer *st, struct spi_chunk *chunk)
507 {
508 struct spi_chunk **cpp;
509
510 /* this is an O(n) insert -- perhaps we should use a simpleq? */
511 for (cpp = &st->st_chunks; *cpp; cpp = &(*cpp)->chunk_next);
512 *cpp = chunk;
513 }
514
515 int
516 spi_transfer(struct spi_handle *sh, struct spi_transfer *st)
517 {
518 struct spi_softc *sc = sh->sh_sc;
519 struct spi_controller *tag = sh->sh_controller;
520 struct spi_chunk *chunk;
521 int error;
522
523 /*
524 * Initialize "resid" counters and pointers, so that callers
525 * and bus drivers don't have to.
526 */
527 for (chunk = st->st_chunks; chunk; chunk = chunk->chunk_next) {
528 chunk->chunk_wresid = chunk->chunk_rresid = chunk->chunk_count;
529 chunk->chunk_wptr = chunk->chunk_write;
530 chunk->chunk_rptr = chunk->chunk_read;
531 }
532
533 /*
534 * Match slave and parameters to handle
535 */
536 st->st_slave = sh->sh_slave;
537
538 /*
539 * Reserve controller during transaction
540 */
541 spi_acquire(sh);
542
543 st->st_spiprivate = (void *)sh;
544
545 /*
546 * Reconfigure controller
547 *
548 * XXX backends don't configure per-slave parameters
549 * Whenever we switch slaves or change mode or speed, we
550 * need to tell the backend.
551 */
552 if (sc->sc_slave != sh->sh_slave
553 || sc->sc_mode != sh->sh_mode
554 || sc->sc_speed != sh->sh_speed) {
555 error = (*tag->sct_configure)(tag->sct_cookie,
556 sh->sh_slave, sh->sh_mode, sh->sh_speed);
557 if (error)
558 return error;
559 }
560 sc->sc_mode = sh->sh_mode;
561 sc->sc_speed = sh->sh_speed;
562 sc->sc_slave = sh->sh_slave;
563
564 error = (*tag->sct_transfer)(tag->sct_cookie, st);
565
566 return error;
567 }
568
569 void
570 spi_wait(struct spi_transfer *st)
571 {
572 struct spi_handle *sh = st->st_spiprivate;
573
574 mutex_enter(&st->st_lock);
575 while (!(st->st_flags & SPI_F_DONE)) {
576 cv_wait(&st->st_cv, &st->st_lock);
577 }
578 mutex_exit(&st->st_lock);
579 cv_destroy(&st->st_cv);
580 mutex_destroy(&st->st_lock);
581
582 /*
583 * End transaction
584 */
585 spi_release(sh);
586 }
587
588 void
589 spi_done(struct spi_transfer *st, int err)
590 {
591
592 mutex_enter(&st->st_lock);
593 if ((st->st_errno = err) != 0) {
594 st->st_flags |= SPI_F_ERROR;
595 }
596 st->st_flags |= SPI_F_DONE;
597 if (st->st_done != NULL) {
598 (*st->st_done)(st);
599 } else {
600 cv_broadcast(&st->st_cv);
601 }
602 mutex_exit(&st->st_lock);
603 }
604
605 /*
606 * Some convenience routines. These routines block until the work
607 * is done.
608 *
609 * spi_recv - receives data from the bus
610 *
611 * spi_send - sends data to the bus
612 *
613 * spi_send_recv - sends data to the bus, and then receives. Note that this is
614 * done synchronously, i.e. send a command and get the response. This is
615 * not full duplex. If you wnat full duplex, you can't use these convenience
616 * wrappers.
617 */
618 int
619 spi_recv(struct spi_handle *sh, int cnt, uint8_t *data)
620 {
621 struct spi_transfer trans;
622 struct spi_chunk chunk;
623
624 spi_transfer_init(&trans);
625 spi_chunk_init(&chunk, cnt, NULL, data);
626 spi_transfer_add(&trans, &chunk);
627
628 /* enqueue it and wait for it to complete */
629 spi_transfer(sh, &trans);
630 spi_wait(&trans);
631
632 if (trans.st_flags & SPI_F_ERROR)
633 return trans.st_errno;
634
635 return 0;
636 }
637
638 int
639 spi_send(struct spi_handle *sh, int cnt, const uint8_t *data)
640 {
641 struct spi_transfer trans;
642 struct spi_chunk chunk;
643
644 spi_transfer_init(&trans);
645 spi_chunk_init(&chunk, cnt, data, NULL);
646 spi_transfer_add(&trans, &chunk);
647
648 /* enqueue it and wait for it to complete */
649 spi_transfer(sh, &trans);
650 spi_wait(&trans);
651
652 if (trans.st_flags & SPI_F_ERROR)
653 return trans.st_errno;
654
655 return 0;
656 }
657
658 int
659 spi_send_recv(struct spi_handle *sh, int scnt, const uint8_t *snd,
660 int rcnt, uint8_t *rcv)
661 {
662 struct spi_transfer trans;
663 struct spi_chunk chunk1, chunk2;
664
665 spi_transfer_init(&trans);
666 spi_chunk_init(&chunk1, scnt, snd, NULL);
667 spi_chunk_init(&chunk2, rcnt, NULL, rcv);
668 spi_transfer_add(&trans, &chunk1);
669 spi_transfer_add(&trans, &chunk2);
670
671 /* enqueue it and wait for it to complete */
672 spi_transfer(sh, &trans);
673 spi_wait(&trans);
674
675 if (trans.st_flags & SPI_F_ERROR)
676 return trans.st_errno;
677
678 return 0;
679 }
680