1/*-
2 * Copyright (c) 2009 Oleksandr Tymoshenko.  All rights reserved.
3 * Copyright (c) 2017 Ruslan Bukin <br@bsdpad.com>
4 * Copyright (c) 2018 Ian Lepore.  All rights reserved.
5 * Copyright (c) 2006 M. Warner Losh <imp@FreeBSD.org>
6 *
7 * This software was developed by SRI International and the University of
8 * Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
9 * ("CTSRD"), as part of the DARPA CRASH research programme.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * 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 copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/* n25q Quad SPI Flash driver. */
34
35#include <sys/cdefs.h>
36#include "opt_platform.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/bio.h>
41#include <sys/bus.h>
42#include <sys/conf.h>
43#include <sys/kernel.h>
44#include <sys/kthread.h>
45#include <sys/lock.h>
46#include <sys/mbuf.h>
47#include <sys/malloc.h>
48#include <sys/module.h>
49#include <sys/mutex.h>
50#include <geom/geom_disk.h>
51
52#include <machine/bus.h>
53
54#include <dev/fdt/fdt_common.h>
55#include <dev/ofw/ofw_bus_subr.h>
56#include <dev/ofw/openfirm.h>
57
58#include <dev/flash/mx25lreg.h>
59
60#include "qspi_if.h"
61
62#define	N25Q_DEBUG
63#undef N25Q_DEBUG
64
65#ifdef N25Q_DEBUG
66#define dprintf(fmt, ...)  printf(fmt, ##__VA_ARGS__)
67#else
68#define dprintf(fmt, ...)
69#endif
70
71#define	FL_NONE			0x00
72#define	FL_ERASE_4K		0x01
73#define	FL_ERASE_32K		0x02
74#define	FL_ENABLE_4B_ADDR	0x04
75#define	FL_DISABLE_4B_ADDR	0x08
76
77/*
78 * Define the sectorsize to be a smaller size rather than the flash
79 * sector size. Trying to run FFS off of a 64k flash sector size
80 * results in a completely un-usable system.
81 */
82#define	FLASH_SECTORSIZE	512
83
84struct n25q_flash_ident {
85	const char	*name;
86	uint8_t		manufacturer_id;
87	uint16_t	device_id;
88	unsigned int	sectorsize;
89	unsigned int	sectorcount;
90	unsigned int	flags;
91};
92
93struct n25q_softc {
94	device_t		dev;
95	bus_space_tag_t		bst;
96	bus_space_handle_t	bsh;
97	void			*ih;
98	struct resource		*res[3];
99
100	uint8_t			sc_manufacturer_id;
101	uint16_t		device_id;
102	unsigned int		sc_sectorsize;
103	struct mtx		sc_mtx;
104	struct disk		*sc_disk;
105	struct proc		*sc_p;
106	struct bio_queue_head	sc_bio_queue;
107	unsigned int		sc_flags;
108	unsigned int		sc_taskstate;
109};
110
111#define	TSTATE_STOPPED	0
112#define	TSTATE_STOPPING	1
113#define	TSTATE_RUNNING	2
114
115#define	N25Q_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
116#define	N25Q_UNLOCK(_sc)	mtx_unlock(&(_sc)->sc_mtx)
117#define N25Q_LOCK_INIT(_sc)					\
118	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev),	\
119	    "n25q", MTX_DEF)
120#define N25Q_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
121#define N25Q_ASSERT_LOCKED(_sc)				\
122	mtx_assert(&_sc->sc_mtx, MA_OWNED);
123#define N25Q_ASSERT_UNLOCKED(_sc)				\
124	mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
125
126static struct ofw_compat_data compat_data[] = {
127	{ "n25q00aa",		1 },
128	{ NULL,			0 },
129};
130
131/* disk routines */
132static int n25q_open(struct disk *dp);
133static int n25q_close(struct disk *dp);
134static int n25q_ioctl(struct disk *, u_long, void *, int, struct thread *);
135static void n25q_strategy(struct bio *bp);
136static int n25q_getattr(struct bio *bp);
137static void n25q_task(void *arg);
138
139static struct n25q_flash_ident flash_devices[] = {
140	{ "n25q00", 0x20, 0xbb21, (64 * 1024), 2048, FL_ENABLE_4B_ADDR},
141};
142
143static int
144n25q_wait_for_device_ready(device_t dev)
145{
146	device_t pdev;
147	uint8_t status;
148	int err;
149
150	pdev = device_get_parent(dev);
151
152	do {
153		err = QSPI_READ_REG(pdev, dev, CMD_READ_STATUS, &status, 1);
154	} while (err == 0 && (status & STATUS_WIP));
155
156	return (err);
157}
158
159static struct n25q_flash_ident*
160n25q_get_device_ident(struct n25q_softc *sc)
161{
162	uint8_t manufacturer_id;
163	uint16_t dev_id;
164	device_t pdev;
165	uint8_t data[4];
166	int i;
167
168	pdev = device_get_parent(sc->dev);
169
170	QSPI_READ_REG(pdev, sc->dev, CMD_READ_IDENT, (uint8_t *)&data[0], 4);
171
172	manufacturer_id = data[0];
173	dev_id = (data[1] << 8) | (data[2]);
174
175	for (i = 0; i < nitems(flash_devices); i++) {
176		if ((flash_devices[i].manufacturer_id == manufacturer_id) &&
177		    (flash_devices[i].device_id == dev_id))
178			return &flash_devices[i];
179	}
180
181	printf("Unknown SPI flash device. Vendor: %02x, device id: %04x\n",
182	    manufacturer_id, dev_id);
183
184	return (NULL);
185}
186
187static int
188n25q_write(device_t dev, struct bio *bp, off_t offset, caddr_t data, off_t count)
189{
190	device_t pdev;
191	int err;
192
193	pdev = device_get_parent(dev);
194
195	dprintf("%s: offset 0x%llx count %lld bytes\n", __func__, offset, count);
196
197	err = QSPI_ERASE(pdev, dev, offset);
198	if (err != 0) {
199		return (err);
200	}
201
202	err = QSPI_WRITE(pdev, dev, bp, offset, data, count);
203
204	return (err);
205}
206
207static int
208n25q_read(device_t dev, struct bio *bp, off_t offset, caddr_t data, off_t count)
209{
210	struct n25q_softc *sc;
211	device_t pdev;
212	int err;
213
214	pdev = device_get_parent(dev);
215	sc = device_get_softc(dev);
216
217	dprintf("%s: offset 0x%llx count %lld bytes\n", __func__, offset, count);
218
219	/*
220	 * Enforce the disk read sectorsize not the erase sectorsize.
221	 * In this way, smaller read IO is possible,dramatically
222	 * speeding up filesystem/geom_compress access.
223	 */
224	if (count % sc->sc_disk->d_sectorsize != 0
225	    || offset % sc->sc_disk->d_sectorsize != 0) {
226		printf("EIO\n");
227		return (EIO);
228	}
229
230	err = QSPI_READ(pdev, dev, bp, offset, data, count);
231
232	return (err);
233}
234
235static int
236n25q_set_4b_mode(device_t dev, uint8_t command)
237{
238	device_t pdev;
239	int err;
240
241	pdev = device_get_parent(dev);
242
243	err = QSPI_WRITE_REG(pdev, dev, command, 0, 0);
244
245	return (err);
246}
247
248static int
249n25q_probe(device_t dev)
250{
251	int i;
252
253	if (!ofw_bus_status_okay(dev))
254		return (ENXIO);
255
256	/* First try to match the compatible property to the compat_data */
257	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 1)
258		goto found;
259
260	/*
261	 * Next, try to find a compatible device using the names in the
262	 * flash_devices structure
263	 */
264	for (i = 0; i < nitems(flash_devices); i++)
265		if (ofw_bus_is_compatible(dev, flash_devices[i].name))
266			goto found;
267
268	return (ENXIO);
269found:
270	device_set_desc(dev, "Micron n25q");
271
272	return (0);
273}
274
275static int
276n25q_attach(device_t dev)
277{
278	struct n25q_flash_ident *ident;
279	struct n25q_softc *sc;
280
281	sc = device_get_softc(dev);
282	sc->dev = dev;
283
284	N25Q_LOCK_INIT(sc);
285
286	ident = n25q_get_device_ident(sc);
287	if (ident == NULL) {
288		return (ENXIO);
289	}
290
291	n25q_wait_for_device_ready(sc->dev);
292
293	sc->sc_disk = disk_alloc();
294	sc->sc_disk->d_open = n25q_open;
295	sc->sc_disk->d_close = n25q_close;
296	sc->sc_disk->d_strategy = n25q_strategy;
297	sc->sc_disk->d_getattr = n25q_getattr;
298	sc->sc_disk->d_ioctl = n25q_ioctl;
299	sc->sc_disk->d_name = "flash/qspi";
300	sc->sc_disk->d_drv1 = sc;
301	sc->sc_disk->d_maxsize = DFLTPHYS;
302	sc->sc_disk->d_sectorsize = FLASH_SECTORSIZE;
303	sc->sc_disk->d_mediasize = (ident->sectorsize * ident->sectorcount);
304	sc->sc_disk->d_unit = device_get_unit(sc->dev);
305	sc->sc_disk->d_dump = NULL;
306	/* Sectorsize for erase operations */
307	sc->sc_sectorsize =  ident->sectorsize;
308	sc->sc_flags = ident->flags;
309
310	if (sc->sc_flags & FL_ENABLE_4B_ADDR)
311		n25q_set_4b_mode(dev, CMD_ENTER_4B_MODE);
312
313	if (sc->sc_flags & FL_DISABLE_4B_ADDR)
314		n25q_set_4b_mode(dev, CMD_EXIT_4B_MODE);
315
316        /* NB: use stripesize to hold the erase/region size for RedBoot */
317	sc->sc_disk->d_stripesize = ident->sectorsize;
318
319	disk_create(sc->sc_disk, DISK_VERSION);
320	bioq_init(&sc->sc_bio_queue);
321
322	kproc_create(&n25q_task, sc, &sc->sc_p, 0, 0, "task: n25q flash");
323	sc->sc_taskstate = TSTATE_RUNNING;
324
325	device_printf(sc->dev, "%s, sector %d bytes, %d sectors\n",
326	    ident->name, ident->sectorsize, ident->sectorcount);
327
328	return (0);
329}
330
331static int
332n25q_detach(device_t dev)
333{
334	struct n25q_softc *sc;
335	int err;
336
337	sc = device_get_softc(dev);
338	err = 0;
339
340	N25Q_LOCK(sc);
341	if (sc->sc_taskstate == TSTATE_RUNNING) {
342		sc->sc_taskstate = TSTATE_STOPPING;
343		wakeup(sc);
344		while (err == 0 && sc->sc_taskstate != TSTATE_STOPPED) {
345			err = msleep(sc, &sc->sc_mtx, 0, "n25q", hz * 3);
346			if (err != 0) {
347				sc->sc_taskstate = TSTATE_RUNNING;
348				device_printf(sc->dev,
349				    "Failed to stop queue task\n");
350			}
351		}
352	}
353	N25Q_UNLOCK(sc);
354
355	if (err == 0 && sc->sc_taskstate == TSTATE_STOPPED) {
356		disk_destroy(sc->sc_disk);
357		bioq_flush(&sc->sc_bio_queue, NULL, ENXIO);
358		N25Q_LOCK_DESTROY(sc);
359	}
360	return (err);
361}
362
363static int
364n25q_open(struct disk *dp)
365{
366
367	return (0);
368}
369
370static int
371n25q_close(struct disk *dp)
372{
373
374	return (0);
375}
376
377static int
378n25q_ioctl(struct disk *dp, u_long cmd, void *data,
379    int fflag, struct thread *td)
380{
381
382	return (EINVAL);
383}
384
385static void
386n25q_strategy(struct bio *bp)
387{
388	struct n25q_softc *sc;
389
390	sc = (struct n25q_softc *)bp->bio_disk->d_drv1;
391
392	N25Q_LOCK(sc);
393	bioq_disksort(&sc->sc_bio_queue, bp);
394	wakeup(sc);
395	N25Q_UNLOCK(sc);
396}
397
398static int
399n25q_getattr(struct bio *bp)
400{
401	struct n25q_softc *sc;
402	device_t dev;
403
404	if (bp->bio_disk == NULL || bp->bio_disk->d_drv1 == NULL) {
405		return (ENXIO);
406	}
407
408	sc = bp->bio_disk->d_drv1;
409	dev = sc->dev;
410
411	if (strcmp(bp->bio_attribute, "SPI::device") == 0) {
412		if (bp->bio_length != sizeof(dev)) {
413			return (EFAULT);
414		}
415		bcopy(&dev, bp->bio_data, sizeof(dev));
416		return (0);
417	}
418
419	return (-1);
420}
421
422static void
423n25q_task(void *arg)
424{
425	struct n25q_softc *sc;
426	struct bio *bp;
427	device_t dev;
428
429	sc = (struct n25q_softc *)arg;
430
431	dev = sc->dev;
432
433	for (;;) {
434		N25Q_LOCK(sc);
435		do {
436			if (sc->sc_taskstate == TSTATE_STOPPING) {
437				sc->sc_taskstate = TSTATE_STOPPED;
438				N25Q_UNLOCK(sc);
439				wakeup(sc);
440				kproc_exit(0);
441			}
442			bp = bioq_first(&sc->sc_bio_queue);
443			if (bp == NULL)
444				msleep(sc, &sc->sc_mtx, PRIBIO, "jobqueue", hz);
445		} while (bp == NULL);
446		bioq_remove(&sc->sc_bio_queue, bp);
447		N25Q_UNLOCK(sc);
448
449		switch (bp->bio_cmd) {
450		case BIO_READ:
451			bp->bio_error = n25q_read(dev, bp, bp->bio_offset,
452			    bp->bio_data, bp->bio_bcount);
453			break;
454		case BIO_WRITE:
455			bp->bio_error = n25q_write(dev, bp, bp->bio_offset,
456			    bp->bio_data, bp->bio_bcount);
457			break;
458		default:
459			bp->bio_error = EOPNOTSUPP;
460		}
461
462		biodone(bp);
463	}
464}
465
466static device_method_t n25q_methods[] = {
467	/* Device interface */
468	DEVMETHOD(device_probe,		n25q_probe),
469	DEVMETHOD(device_attach,	n25q_attach),
470	DEVMETHOD(device_detach,	n25q_detach),
471
472	{ 0, 0 }
473};
474
475static driver_t n25q_driver = {
476	"n25q",
477	n25q_methods,
478	sizeof(struct n25q_softc),
479};
480
481DRIVER_MODULE(n25q, simplebus, n25q_driver, 0, 0);
482