summaryrefslogtreecommitdiff
path: root/sys/dev/spi/spi.c
blob: 36f8805cb5c3ca87a1accddaeda70036e308c942 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/* $NetBSD: spi.c,v 1.26 2022/05/17 05:05:20 andvar Exp $ */

/*-
 * Copyright (c) 2006 Urbana-Champaign Independent Media Center.
 * Copyright (c) 2006 Garrett D'Amore.
 * All rights reserved.
 *
 * Portions of this code were written by Garrett D'Amore for the
 * Champaign-Urbana Community Wireless Network Project.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgements:
 *      This product includes software developed by the Urbana-Champaign
 *      Independent Media Center.
 *	This product includes software developed by Garrett D'Amore.
 * 4. Urbana-Champaign Independent Media Center's name and Garrett
 *    D'Amore's name may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE URBANA-CHAMPAIGN INDEPENDENT
 * MEDIA CENTER AND GARRETT D'AMORE ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE URBANA-CHAMPAIGN INDEPENDENT
 * MEDIA CENTER OR GARRETT D'AMORE BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: spi.c,v 1.26 2022/05/17 05:05:20 andvar Exp $");

#include "locators.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/conf.h>
#include <sys/malloc.h>
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/errno.h>

#include <dev/spi/spivar.h>
#include <dev/spi/spi_io.h>

#include "ioconf.h"
#include "locators.h"

struct spi_softc {
	device_t		sc_dev;
	struct spi_controller	sc_controller;
	int			sc_mode;
	int			sc_speed;
	int			sc_slave;
	int			sc_nslaves;
	struct spi_handle	*sc_slaves;
	kmutex_t		sc_lock;
	kcondvar_t		sc_cv;
	kmutex_t		sc_dev_lock;
	int			sc_flags;
#define SPIC_BUSY		1
};

static dev_type_open(spi_open);
static dev_type_close(spi_close);
static dev_type_ioctl(spi_ioctl);

const struct cdevsw spi_cdevsw = {
	.d_open = spi_open,
	.d_close = spi_close,
	.d_read = noread,
	.d_write = nowrite,
	.d_ioctl = spi_ioctl,
	.d_stop = nostop,
	.d_tty = notty,
	.d_poll = nopoll,
	.d_mmap = nommap,
	.d_kqfilter = nokqfilter,
	.d_discard = nodiscard,
	.d_flag = D_OTHER | D_MPSAFE
};

/*
 * SPI slave device.  We have one of these per slave.
 */
struct spi_handle {
	struct spi_softc	*sh_sc;
	struct spi_controller	*sh_controller;
	int			sh_slave;
	int			sh_mode;
	int			sh_speed;
	int			sh_flags;
#define SPIH_ATTACHED		1
};

#define SPI_MAXDATA 4096

/*
 * API for bus drivers.
 */

int
spibus_print(void *aux, const char *pnp)
{

	if (pnp != NULL)
		aprint_normal("spi at %s", pnp);

	return (UNCONF);
}


static int
spi_match(device_t parent, cfdata_t cf, void *aux)
{

	return 1;
}

static int
spi_print(void *aux, const char *pnp)
{
	struct spi_attach_args *sa = aux;

	if (sa->sa_handle->sh_slave != -1)
		aprint_normal(" slave %d", sa->sa_handle->sh_slave);

	return (UNCONF);
}

static int
spi_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
{
	struct spi_softc *sc = device_private(parent);
	struct spi_attach_args sa;
	int addr;

	addr = cf->cf_loc[SPICF_SLAVE];
	if ((addr < 0) || (addr >= sc->sc_controller.sct_nslaves)) {
		return -1;
	}

	memset(&sa, 0, sizeof sa);
	sa.sa_handle = &sc->sc_slaves[addr];
	if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
		return -1;

	if (config_probe(parent, cf, &sa)) {
		SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);
		config_attach(parent, cf, &sa, spi_print, CFARGS_NONE);
	}

	return 0;
}

/*
 * XXX this is the same as i2c_fill_compat. It could be refactored into a
 * common fill_compat function with pointers to compat & ncompat instead
 * of attach_args as the first parameter.
 */
static void
spi_fill_compat(struct spi_attach_args *sa, const char *compat, size_t len,
	char **buffer)
{
	int count, i;
	const char *c, *start, **ptr;

	*buffer = NULL;
	for (i = count = 0, c = compat; i < len; i++, c++)
		if (*c == 0)
			count++;
	count += 2;
	ptr = malloc(sizeof(char*)*count, M_TEMP, M_WAITOK);
	if (!ptr)
		return;

	for (i = count = 0, start = c = compat; i < len; i++, c++) {
		if (*c == 0) {
			ptr[count++] = start;
			start = c + 1;
		}
	}
	if (start < compat + len) {
		/* last string not 0 terminated */
		size_t l = c - start;
		*buffer = malloc(l + 1, M_TEMP, M_WAITOK);
		memcpy(*buffer, start, l);
		(*buffer)[l] = 0;
		ptr[count++] = *buffer;
	}
	ptr[count] = NULL;

	sa->sa_compat = ptr;
	sa->sa_ncompat = count;
}

static void
spi_direct_attach_child_devices(device_t parent, struct spi_softc *sc,
    prop_array_t child_devices)
{
	unsigned int count;
	prop_dictionary_t child;
	prop_data_t cdata;
	uint32_t slave;
	uint64_t cookie;
	struct spi_attach_args sa;
	int loc[SPICF_NLOCS];
	char *buf;
	int i;

	memset(loc, 0, sizeof loc);
	count = prop_array_count(child_devices);
	for (i = 0; i < count; i++) {
		child = prop_array_get(child_devices, i);
		if (!child)
			continue;
		if (!prop_dictionary_get_uint32(child, "slave", &slave))
			continue;
		if(slave >= sc->sc_controller.sct_nslaves)
			continue;
		if (!prop_dictionary_get_uint64(child, "cookie", &cookie))
			continue;
		if (!(cdata = prop_dictionary_get(child, "compatible")))
			continue;
		loc[SPICF_SLAVE] = slave;

		memset(&sa, 0, sizeof sa);
		sa.sa_handle = &sc->sc_slaves[i];
		sa.sa_prop = child;
		sa.sa_cookie = cookie;
		if (ISSET(sa.sa_handle->sh_flags, SPIH_ATTACHED))
			continue;
		SET(sa.sa_handle->sh_flags, SPIH_ATTACHED);

		buf = NULL;
		spi_fill_compat(&sa,
				prop_data_value(cdata),
				prop_data_size(cdata), &buf);
		config_found(parent, &sa, spi_print,
		    CFARGS(.locators = loc));

		if (sa.sa_compat)
			free(sa.sa_compat, M_TEMP);
		if (buf)
			free(buf, M_TEMP);
	}
}

int
spi_compatible_match(const struct spi_attach_args *sa, const cfdata_t cf,
		     const struct device_compatible_entry *compats)
{
	if (sa->sa_ncompat > 0)
		return device_compatible_match(sa->sa_compat, sa->sa_ncompat,
					       compats);

	return 1;
}

const struct device_compatible_entry *
spi_compatible_lookup(const struct spi_attach_args *sa,
    const struct device_compatible_entry *compats)
{
	return device_compatible_lookup(sa->sa_compat, sa->sa_ncompat,
					compats);
}

/*
 * API for device drivers.
 *
 * We provide wrapper routines to decouple the ABI for the SPI
 * device drivers from the ABI for the SPI bus drivers.
 */
static void
spi_attach(device_t parent, device_t self, void *aux)
{
	struct spi_softc *sc = device_private(self);
	struct spibus_attach_args *sba = aux;
	int i;

	aprint_naive(": SPI bus\n");
	aprint_normal(": SPI bus\n");

	mutex_init(&sc->sc_dev_lock, MUTEX_DEFAULT, IPL_NONE);
	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_VM);
	cv_init(&sc->sc_cv, "spictl");

	sc->sc_dev = self;
	sc->sc_controller = *sba->sba_controller;
	sc->sc_nslaves = sba->sba_controller->sct_nslaves;
	/* allocate slave structures */
	sc->sc_slaves = malloc(sizeof (struct spi_handle) * sc->sc_nslaves,
	    M_DEVBUF, M_WAITOK | M_ZERO);

	sc->sc_speed = 0;
	sc->sc_mode = -1;
	sc->sc_slave = -1;

	/*
	 * Initialize slave handles
	 */
	for (i = 0; i < sc->sc_nslaves; i++) {
		sc->sc_slaves[i].sh_slave = i;
		sc->sc_slaves[i].sh_sc = sc;
		sc->sc_slaves[i].sh_controller = &sc->sc_controller;
	}

	/* First attach devices known to be present via fdt */
	if (sba->sba_child_devices) {
		spi_direct_attach_child_devices(self, sc, sba->sba_child_devices);
	}
	/* Then do any other devices the user may have manually wired */
	config_search(self, NULL,
	    CFARGS(.search = spi_search));
}

static int
spi_open(dev_t dev, int flag, int fmt, lwp_t *l)
{
	struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));

	if (sc == NULL)
		return ENXIO;

	return 0;
}

static int
spi_close(dev_t dev, int flag, int fmt, lwp_t *l)
{

	return 0;
}

static int
spi_ioctl(dev_t dev, u_long cmd, void *data, int flag, lwp_t *l)
{
	struct spi_softc *sc = device_lookup_private(&spi_cd, minor(dev));
	struct spi_handle *sh;
	spi_ioctl_configure_t *sic;
	spi_ioctl_transfer_t *sit;
	uint8_t *sbuf, *rbuf;
	int error;

	if (sc == NULL)
		return ENXIO;

	mutex_enter(&sc->sc_dev_lock);

	switch (cmd) {
	case SPI_IOCTL_CONFIGURE:
		sic = (spi_ioctl_configure_t *)data;
		if (sic->sic_addr < 0 || sic->sic_addr >= sc->sc_nslaves) {
			error = EINVAL;
			break;
		}
		sh = &sc->sc_slaves[sic->sic_addr];
		error = spi_configure(sc->sc_dev, sh, sic->sic_mode,
		    sic->sic_speed);
		break;
	case SPI_IOCTL_TRANSFER:
		sit = (spi_ioctl_transfer_t *)data;
		if (sit->sit_addr < 0 || sit->sit_addr >= sc->sc_nslaves) {
			error = EINVAL;
			break;
		}
		if ((sit->sit_send && sit->sit_sendlen == 0)
		    || (sit->sit_recv && sit->sit_recvlen == 0)) {
			error = EINVAL;
			break;
		}
		sh = &sc->sc_slaves[sit->sit_addr];
		sbuf = rbuf = NULL;
		error = 0;
		if (sit->sit_send && sit->sit_sendlen <= SPI_MAXDATA) {
			sbuf = malloc(sit->sit_sendlen, M_DEVBUF, M_WAITOK);
			error = copyin(sit->sit_send, sbuf, sit->sit_sendlen);
		}
		if (sit->sit_recv && sit->sit_recvlen <= SPI_MAXDATA) {
			rbuf = malloc(sit->sit_recvlen, M_DEVBUF, M_WAITOK);
		}
		if (error == 0) {
			if (sbuf && rbuf)
				error = spi_send_recv(sh,
					sit->sit_sendlen, sbuf,
					sit->sit_recvlen, rbuf);
			else if (sbuf)
				error = spi_send(sh,
					sit->sit_sendlen, sbuf);
			else if (rbuf)
				error = spi_recv(sh,
					sit->sit_recvlen, rbuf);
		}
		if (rbuf) {
			if (error == 0)
				error = copyout(rbuf, sit->sit_recv,
						sit->sit_recvlen);
			free(rbuf, M_DEVBUF);
		}
		if (sbuf) {
			free(sbuf, M_DEVBUF);
		}
		break;
	default:
		error = ENODEV;
		break;
	}

	mutex_exit(&sc->sc_dev_lock);

	return error;
}

CFATTACH_DECL_NEW(spi, sizeof(struct spi_softc),
    spi_match, spi_attach, NULL, NULL);

/*
 * Configure.  This should be the first thing that the SPI driver
 * should do, to configure which mode (e.g. SPI_MODE_0, which is the
 * same as Philips Microwire mode), and speed.  If the bus driver
 * cannot run fast enough, then it should just configure the fastest
 * mode that it can support.  If the bus driver cannot run slow
 * enough, then the device is incompatible and an error should be
 * returned.
 */
int
spi_configure(device_t dev __unused, struct spi_handle *sh, int mode, int speed)
{

	sh->sh_mode = mode;
	sh->sh_speed = speed;

	/* No need to report errors; no failures. */

	return 0;
}

/*
 * Acquire controller
 */
static void
spi_acquire(struct spi_handle *sh)
{
	struct spi_softc *sc = sh->sh_sc;

	mutex_enter(&sc->sc_lock);
	while ((sc->sc_flags & SPIC_BUSY) != 0)
		cv_wait(&sc->sc_cv, &sc->sc_lock);
	sc->sc_flags |= SPIC_BUSY;
	mutex_exit(&sc->sc_lock);
}

/*
 * Release controller
 */
static void
spi_release(struct spi_handle *sh)
{
	struct spi_softc *sc = sh->sh_sc;

	mutex_enter(&sc->sc_lock);
	sc->sc_flags &= ~SPIC_BUSY;
	cv_broadcast(&sc->sc_cv);
	mutex_exit(&sc->sc_lock);
}

void
spi_transfer_init(struct spi_transfer *st)
{

	mutex_init(&st->st_lock, MUTEX_DEFAULT, IPL_VM);
	cv_init(&st->st_cv, "spixfr");

	st->st_flags = 0;
	st->st_errno = 0;
	st->st_done = NULL;
	st->st_chunks = NULL;
	st->st_private = NULL;
	st->st_slave = -1;
}

void
spi_chunk_init(struct spi_chunk *chunk, int cnt, const uint8_t *wptr,
    uint8_t *rptr)
{

	chunk->chunk_write = chunk->chunk_wptr = wptr;
	chunk->chunk_read = chunk->chunk_rptr = rptr;
	chunk->chunk_rresid = chunk->chunk_wresid = chunk->chunk_count = cnt;
	chunk->chunk_next = NULL;
}

void
spi_transfer_add(struct spi_transfer *st, struct spi_chunk *chunk)
{
	struct spi_chunk **cpp;

	/* this is an O(n) insert -- perhaps we should use a simpleq? */
	for (cpp = &st->st_chunks; *cpp; cpp = &(*cpp)->chunk_next);
	*cpp = chunk;
}

int
spi_transfer(struct spi_handle *sh, struct spi_transfer *st)
{
	struct spi_softc	*sc = sh->sh_sc;
	struct spi_controller	*tag = sh->sh_controller;
	struct spi_chunk	*chunk;
	int error;

	/*
	 * Initialize "resid" counters and pointers, so that callers
	 * and bus drivers don't have to.
	 */
	for (chunk = st->st_chunks; chunk; chunk = chunk->chunk_next) {
		chunk->chunk_wresid = chunk->chunk_rresid = chunk->chunk_count;
		chunk->chunk_wptr = chunk->chunk_write;
		chunk->chunk_rptr = chunk->chunk_read;
	}

	/*
	 * Match slave and parameters to handle
	 */
	st->st_slave = sh->sh_slave;

	/*
	 * Reserve controller during transaction
 	 */
	spi_acquire(sh);

	st->st_spiprivate = (void *)sh;

	/*
	 * Reconfigure controller
	 *
	 * XXX backends don't configure per-slave parameters
	 * Whenever we switch slaves or change mode or speed, we
	 * need to tell the backend.
	 */
	if (sc->sc_slave != sh->sh_slave
	    || sc->sc_mode != sh->sh_mode
	    || sc->sc_speed != sh->sh_speed) {
		error = (*tag->sct_configure)(tag->sct_cookie,
				sh->sh_slave, sh->sh_mode, sh->sh_speed);
		if (error)
			return error;
	}
	sc->sc_mode = sh->sh_mode;
	sc->sc_speed = sh->sh_speed;
	sc->sc_slave = sh->sh_slave;

	error = (*tag->sct_transfer)(tag->sct_cookie, st);

	return error;
}

void
spi_wait(struct spi_transfer *st)
{
	struct spi_handle *sh = st->st_spiprivate;

	mutex_enter(&st->st_lock);
	while (!(st->st_flags & SPI_F_DONE)) {
		cv_wait(&st->st_cv, &st->st_lock);
	}
	mutex_exit(&st->st_lock);
	cv_destroy(&st->st_cv);
	mutex_destroy(&st->st_lock);

	/*
	 * End transaction
	 */
	spi_release(sh);
}

void
spi_done(struct spi_transfer *st, int err)
{

	mutex_enter(&st->st_lock);
	if ((st->st_errno = err) != 0) {
		st->st_flags |= SPI_F_ERROR;
	}
	st->st_flags |= SPI_F_DONE;
	if (st->st_done != NULL) {
		(*st->st_done)(st);
	} else {
		cv_broadcast(&st->st_cv);
	}
	mutex_exit(&st->st_lock);
}

/*
 * Some convenience routines.  These routines block until the work
 * is done.
 *
 * spi_recv - receives data from the bus
 *
 * spi_send - sends data to the bus
 *
 * spi_send_recv - sends data to the bus, and then receives.  Note that this is
 * done synchronously, i.e. send a command and get the response.  This is
 * not full duplex.  If you want full duplex, you can't use these convenience
 * wrappers.
 */
int
spi_recv(struct spi_handle *sh, int cnt, uint8_t *data)
{
	struct spi_transfer	trans;
	struct spi_chunk	chunk;

	spi_transfer_init(&trans);
	spi_chunk_init(&chunk, cnt, NULL, data);
	spi_transfer_add(&trans, &chunk);

	/* enqueue it and wait for it to complete */
	spi_transfer(sh, &trans);
	spi_wait(&trans);

	if (trans.st_flags & SPI_F_ERROR)
		return trans.st_errno;

	return 0;
}

int
spi_send(struct spi_handle *sh, int cnt, const uint8_t *data)
{
	struct spi_transfer	trans;
	struct spi_chunk	chunk;

	spi_transfer_init(&trans);
	spi_chunk_init(&chunk, cnt, data, NULL);
	spi_transfer_add(&trans, &chunk);

	/* enqueue it and wait for it to complete */
	spi_transfer(sh, &trans);
	spi_wait(&trans);

	if (trans.st_flags & SPI_F_ERROR)
		return trans.st_errno;

	return 0;
}

int
spi_send_recv(struct spi_handle *sh, int scnt, const uint8_t *snd,
    int rcnt, uint8_t *rcv)
{
	struct spi_transfer	trans;
	struct spi_chunk	chunk1, chunk2;

	spi_transfer_init(&trans);
	spi_chunk_init(&chunk1, scnt, snd, NULL);
	spi_chunk_init(&chunk2, rcnt, NULL, rcv);
	spi_transfer_add(&trans, &chunk1);
	spi_transfer_add(&trans, &chunk2);

	/* enqueue it and wait for it to complete */
	spi_transfer(sh, &trans);
	spi_wait(&trans);

	if (trans.st_flags & SPI_F_ERROR)
		return trans.st_errno;

	return 0;
}