1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (C) 2012-2016 Intel Corporation
5 * All rights reserved.
6 * Copyright (C) 2018 Alexander Motin <mav@FreeBSD.org>
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD$");
32
33#include <sys/param.h>
34#include <sys/bio.h>
35#include <sys/kernel.h>
36#include <sys/malloc.h>
37#include <sys/module.h>
38#include <sys/queue.h>
39#include <sys/sysctl.h>
40#include <sys/systm.h>
41#include <sys/taskqueue.h>
42#include <machine/atomic.h>
43
44#include <geom/geom.h>
45#include <geom/geom_disk.h>
46
47#include <dev/nvme/nvme.h>
48
49#define NVD_STR		"nvd"
50
51struct nvd_disk;
52struct nvd_controller;
53
54static disk_ioctl_t nvd_ioctl;
55static disk_strategy_t nvd_strategy;
56static dumper_t nvd_dump;
57static disk_getattr_t nvd_getattr;
58
59static void nvd_done(void *arg, const struct nvme_completion *cpl);
60static void nvd_gone(struct nvd_disk *ndisk);
61
62static void *nvd_new_disk(struct nvme_namespace *ns, void *ctrlr);
63
64static void *nvd_new_controller(struct nvme_controller *ctrlr);
65static void nvd_controller_fail(void *ctrlr);
66
67static int nvd_load(void);
68static void nvd_unload(void);
69
70MALLOC_DEFINE(M_NVD, "nvd", "nvd(4) allocations");
71
72struct nvme_consumer *consumer_handle;
73
74struct nvd_disk {
75	struct nvd_controller	*ctrlr;
76
77	struct bio_queue_head	bioq;
78	struct task		bioqtask;
79	struct mtx		bioqlock;
80
81	struct disk		*disk;
82	struct taskqueue	*tq;
83	struct nvme_namespace	*ns;
84
85	uint32_t		cur_depth;
86#define	NVD_ODEPTH	(1 << 30)
87	uint32_t		ordered_in_flight;
88	u_int			unit;
89
90	TAILQ_ENTRY(nvd_disk)	global_tailq;
91	TAILQ_ENTRY(nvd_disk)	ctrlr_tailq;
92};
93
94struct nvd_controller {
95
96	TAILQ_ENTRY(nvd_controller)	tailq;
97	TAILQ_HEAD(, nvd_disk)		disk_head;
98};
99
100static struct mtx			nvd_lock;
101static TAILQ_HEAD(, nvd_controller)	ctrlr_head;
102static TAILQ_HEAD(disk_list, nvd_disk)	disk_head;
103
104static SYSCTL_NODE(_hw, OID_AUTO, nvd, CTLFLAG_RD, 0, "nvd driver parameters");
105/*
106 * The NVMe specification does not define a maximum or optimal delete size, so
107 *  technically max delete size is min(full size of the namespace, 2^32 - 1
108 *  LBAs).  A single delete for a multi-TB NVMe namespace though may take much
109 *  longer to complete than the nvme(4) I/O timeout period.  So choose a sensible
110 *  default here that is still suitably large to minimize the number of overall
111 *  delete operations.
112 */
113static uint64_t nvd_delete_max = (1024 * 1024 * 1024);  /* 1GB */
114SYSCTL_UQUAD(_hw_nvd, OID_AUTO, delete_max, CTLFLAG_RDTUN, &nvd_delete_max, 0,
115	     "nvd maximum BIO_DELETE size in bytes");
116
117static int nvd_modevent(module_t mod, int type, void *arg)
118{
119	int error = 0;
120
121	switch (type) {
122	case MOD_LOAD:
123		error = nvd_load();
124		break;
125	case MOD_UNLOAD:
126		nvd_unload();
127		break;
128	default:
129		break;
130	}
131
132	return (error);
133}
134
135moduledata_t nvd_mod = {
136	NVD_STR,
137	(modeventhand_t)nvd_modevent,
138	0
139};
140
141DECLARE_MODULE(nvd, nvd_mod, SI_SUB_DRIVERS, SI_ORDER_ANY);
142MODULE_VERSION(nvd, 1);
143MODULE_DEPEND(nvd, nvme, 1, 1, 1);
144
145static int
146nvd_load()
147{
148	if (!nvme_use_nvd)
149		return 0;
150
151	mtx_init(&nvd_lock, "nvd_lock", NULL, MTX_DEF);
152	TAILQ_INIT(&ctrlr_head);
153	TAILQ_INIT(&disk_head);
154
155	consumer_handle = nvme_register_consumer(nvd_new_disk,
156	    nvd_new_controller, NULL, nvd_controller_fail);
157
158	return (consumer_handle != NULL ? 0 : -1);
159}
160
161static void
162nvd_unload()
163{
164	struct nvd_controller	*ctrlr;
165	struct nvd_disk		*ndisk;
166
167	if (!nvme_use_nvd)
168		return;
169
170	mtx_lock(&nvd_lock);
171	while ((ctrlr = TAILQ_FIRST(&ctrlr_head)) != NULL) {
172		TAILQ_REMOVE(&ctrlr_head, ctrlr, tailq);
173		TAILQ_FOREACH(ndisk, &ctrlr->disk_head, ctrlr_tailq)
174			nvd_gone(ndisk);
175		while (!TAILQ_EMPTY(&ctrlr->disk_head))
176			msleep(&ctrlr->disk_head, &nvd_lock, 0, "nvd_unload",0);
177		free(ctrlr, M_NVD);
178	}
179	mtx_unlock(&nvd_lock);
180
181	nvme_unregister_consumer(consumer_handle);
182
183	mtx_destroy(&nvd_lock);
184}
185
186static void
187nvd_bio_submit(struct nvd_disk *ndisk, struct bio *bp)
188{
189	int err;
190
191	bp->bio_driver1 = NULL;
192	if (__predict_false(bp->bio_flags & BIO_ORDERED))
193		atomic_add_int(&ndisk->cur_depth, NVD_ODEPTH);
194	else
195		atomic_add_int(&ndisk->cur_depth, 1);
196	err = nvme_ns_bio_process(ndisk->ns, bp, nvd_done);
197	if (err) {
198		if (__predict_false(bp->bio_flags & BIO_ORDERED)) {
199			atomic_add_int(&ndisk->cur_depth, -NVD_ODEPTH);
200			atomic_add_int(&ndisk->ordered_in_flight, -1);
201			wakeup(&ndisk->cur_depth);
202		} else {
203			if (atomic_fetchadd_int(&ndisk->cur_depth, -1) == 1 &&
204			    __predict_false(ndisk->ordered_in_flight != 0))
205				wakeup(&ndisk->cur_depth);
206		}
207		bp->bio_error = err;
208		bp->bio_flags |= BIO_ERROR;
209		bp->bio_resid = bp->bio_bcount;
210		biodone(bp);
211	}
212}
213
214static void
215nvd_strategy(struct bio *bp)
216{
217	struct nvd_disk *ndisk = (struct nvd_disk *)bp->bio_disk->d_drv1;
218
219	/*
220	 * bio with BIO_ORDERED flag must be executed after all previous
221	 * bios in the queue, and before any successive bios.
222	 */
223	if (__predict_false(bp->bio_flags & BIO_ORDERED)) {
224		if (atomic_fetchadd_int(&ndisk->ordered_in_flight, 1) == 0 &&
225		    ndisk->cur_depth == 0 && bioq_first(&ndisk->bioq) == NULL) {
226			nvd_bio_submit(ndisk, bp);
227			return;
228		}
229	} else if (__predict_true(ndisk->ordered_in_flight == 0)) {
230		nvd_bio_submit(ndisk, bp);
231		return;
232	}
233
234	/*
235	 * There are ordered bios in flight, so we need to submit
236	 *  bios through the task queue to enforce ordering.
237	 */
238	mtx_lock(&ndisk->bioqlock);
239	bioq_insert_tail(&ndisk->bioq, bp);
240	mtx_unlock(&ndisk->bioqlock);
241	taskqueue_enqueue(ndisk->tq, &ndisk->bioqtask);
242}
243
244static void
245nvd_gone(struct nvd_disk *ndisk)
246{
247	struct bio	*bp;
248
249	printf(NVD_STR"%u: detached\n", ndisk->unit);
250	mtx_lock(&ndisk->bioqlock);
251	disk_gone(ndisk->disk);
252	while ((bp = bioq_takefirst(&ndisk->bioq)) != NULL) {
253		if (__predict_false(bp->bio_flags & BIO_ORDERED))
254			atomic_add_int(&ndisk->ordered_in_flight, -1);
255		bp->bio_error = ENXIO;
256		bp->bio_flags |= BIO_ERROR;
257		bp->bio_resid = bp->bio_bcount;
258		biodone(bp);
259	}
260	mtx_unlock(&ndisk->bioqlock);
261}
262
263static void
264nvd_gonecb(struct disk *dp)
265{
266	struct nvd_disk *ndisk = (struct nvd_disk *)dp->d_drv1;
267
268	disk_destroy(ndisk->disk);
269	mtx_lock(&nvd_lock);
270	TAILQ_REMOVE(&disk_head, ndisk, global_tailq);
271	TAILQ_REMOVE(&ndisk->ctrlr->disk_head, ndisk, ctrlr_tailq);
272	if (TAILQ_EMPTY(&ndisk->ctrlr->disk_head))
273		wakeup(&ndisk->ctrlr->disk_head);
274	mtx_unlock(&nvd_lock);
275	taskqueue_free(ndisk->tq);
276	mtx_destroy(&ndisk->bioqlock);
277	free(ndisk, M_NVD);
278}
279
280static int
281nvd_ioctl(struct disk *dp, u_long cmd, void *data, int fflag,
282    struct thread *td)
283{
284	struct nvd_disk		*ndisk = dp->d_drv1;
285
286	return (nvme_ns_ioctl_process(ndisk->ns, cmd, data, fflag, td));
287}
288
289static int
290nvd_dump(void *arg, void *virt, vm_offset_t phys, off_t offset, size_t len)
291{
292	struct disk *dp = arg;
293	struct nvd_disk *ndisk = dp->d_drv1;
294
295	return (nvme_ns_dump(ndisk->ns, virt, offset, len));
296}
297
298static int
299nvd_getattr(struct bio *bp)
300{
301	struct nvd_disk *ndisk = (struct nvd_disk *)bp->bio_disk->d_drv1;
302	const struct nvme_namespace_data *nsdata;
303	u_int i;
304
305	if (!strcmp("GEOM::lunid", bp->bio_attribute)) {
306		nsdata = nvme_ns_get_data(ndisk->ns);
307
308		/* Try to return NGUID as lunid. */
309		for (i = 0; i < sizeof(nsdata->nguid); i++) {
310			if (nsdata->nguid[i] != 0)
311				break;
312		}
313		if (i < sizeof(nsdata->nguid)) {
314			if (bp->bio_length < sizeof(nsdata->nguid) * 2 + 1)
315				return (EFAULT);
316			for (i = 0; i < sizeof(nsdata->nguid); i++) {
317				sprintf(&bp->bio_data[i * 2], "%02x",
318				    nsdata->nguid[i]);
319			}
320			bp->bio_completed = bp->bio_length;
321			return (0);
322		}
323
324		/* Try to return EUI64 as lunid. */
325		for (i = 0; i < sizeof(nsdata->eui64); i++) {
326			if (nsdata->eui64[i] != 0)
327				break;
328		}
329		if (i < sizeof(nsdata->eui64)) {
330			if (bp->bio_length < sizeof(nsdata->eui64) * 2 + 1)
331				return (EFAULT);
332			for (i = 0; i < sizeof(nsdata->eui64); i++) {
333				sprintf(&bp->bio_data[i * 2], "%02x",
334				    nsdata->eui64[i]);
335			}
336			bp->bio_completed = bp->bio_length;
337			return (0);
338		}
339	}
340	return (-1);
341}
342
343static void
344nvd_done(void *arg, const struct nvme_completion *cpl)
345{
346	struct bio *bp = (struct bio *)arg;
347	struct nvd_disk *ndisk = bp->bio_disk->d_drv1;
348
349	if (__predict_false(bp->bio_flags & BIO_ORDERED)) {
350		atomic_add_int(&ndisk->cur_depth, -NVD_ODEPTH);
351		atomic_add_int(&ndisk->ordered_in_flight, -1);
352		wakeup(&ndisk->cur_depth);
353	} else {
354		if (atomic_fetchadd_int(&ndisk->cur_depth, -1) == 1 &&
355		    __predict_false(ndisk->ordered_in_flight != 0))
356			wakeup(&ndisk->cur_depth);
357	}
358
359	biodone(bp);
360}
361
362static void
363nvd_bioq_process(void *arg, int pending)
364{
365	struct nvd_disk *ndisk = arg;
366	struct bio *bp;
367
368	for (;;) {
369		mtx_lock(&ndisk->bioqlock);
370		bp = bioq_takefirst(&ndisk->bioq);
371		mtx_unlock(&ndisk->bioqlock);
372		if (bp == NULL)
373			break;
374
375		if (__predict_false(bp->bio_flags & BIO_ORDERED)) {
376			/*
377			 * bio with BIO_ORDERED flag set must be executed
378			 * after all previous bios.
379			 */
380			while (ndisk->cur_depth > 0)
381				tsleep(&ndisk->cur_depth, 0, "nvdorb", 1);
382		} else {
383			/*
384			 * bio with BIO_ORDERED flag set must be completed
385			 * before proceeding with additional bios.
386			 */
387			while (ndisk->cur_depth >= NVD_ODEPTH)
388				tsleep(&ndisk->cur_depth, 0, "nvdora", 1);
389		}
390
391		nvd_bio_submit(ndisk, bp);
392	}
393}
394
395static void *
396nvd_new_controller(struct nvme_controller *ctrlr)
397{
398	struct nvd_controller	*nvd_ctrlr;
399
400	nvd_ctrlr = malloc(sizeof(struct nvd_controller), M_NVD,
401	    M_ZERO | M_WAITOK);
402
403	TAILQ_INIT(&nvd_ctrlr->disk_head);
404	mtx_lock(&nvd_lock);
405	TAILQ_INSERT_TAIL(&ctrlr_head, nvd_ctrlr, tailq);
406	mtx_unlock(&nvd_lock);
407
408	return (nvd_ctrlr);
409}
410
411static void *
412nvd_new_disk(struct nvme_namespace *ns, void *ctrlr_arg)
413{
414	uint8_t			descr[NVME_MODEL_NUMBER_LENGTH+1];
415	struct nvd_disk		*ndisk, *tnd;
416	struct disk		*disk;
417	struct nvd_controller	*ctrlr = ctrlr_arg;
418	int unit;
419
420	ndisk = malloc(sizeof(struct nvd_disk), M_NVD, M_ZERO | M_WAITOK);
421	ndisk->ctrlr = ctrlr;
422	ndisk->ns = ns;
423	ndisk->cur_depth = 0;
424	ndisk->ordered_in_flight = 0;
425	mtx_init(&ndisk->bioqlock, "nvd bioq lock", NULL, MTX_DEF);
426	bioq_init(&ndisk->bioq);
427	TASK_INIT(&ndisk->bioqtask, 0, nvd_bioq_process, ndisk);
428
429	mtx_lock(&nvd_lock);
430	unit = 0;
431	TAILQ_FOREACH(tnd, &disk_head, global_tailq) {
432		if (tnd->unit > unit)
433			break;
434		unit = tnd->unit + 1;
435	}
436	ndisk->unit = unit;
437	if (tnd != NULL)
438		TAILQ_INSERT_BEFORE(tnd, ndisk, global_tailq);
439	else
440		TAILQ_INSERT_TAIL(&disk_head, ndisk, global_tailq);
441	TAILQ_INSERT_TAIL(&ctrlr->disk_head, ndisk, ctrlr_tailq);
442	mtx_unlock(&nvd_lock);
443
444	ndisk->tq = taskqueue_create("nvd_taskq", M_WAITOK,
445	    taskqueue_thread_enqueue, &ndisk->tq);
446	taskqueue_start_threads(&ndisk->tq, 1, PI_DISK, "nvd taskq");
447
448	disk = ndisk->disk = disk_alloc();
449	disk->d_strategy = nvd_strategy;
450	disk->d_ioctl = nvd_ioctl;
451	disk->d_dump = nvd_dump;
452	disk->d_getattr = nvd_getattr;
453	disk->d_gone = nvd_gonecb;
454	disk->d_name = NVD_STR;
455	disk->d_unit = ndisk->unit;
456	disk->d_drv1 = ndisk;
457
458	disk->d_sectorsize = nvme_ns_get_sector_size(ns);
459	disk->d_mediasize = (off_t)nvme_ns_get_size(ns);
460	disk->d_maxsize = nvme_ns_get_max_io_xfer_size(ns);
461	disk->d_delmaxsize = (off_t)nvme_ns_get_size(ns);
462	if (disk->d_delmaxsize > nvd_delete_max)
463		disk->d_delmaxsize = nvd_delete_max;
464	disk->d_stripesize = nvme_ns_get_stripesize(ns);
465	disk->d_flags = DISKFLAG_UNMAPPED_BIO | DISKFLAG_DIRECT_COMPLETION;
466	if (nvme_ns_get_flags(ns) & NVME_NS_DEALLOCATE_SUPPORTED)
467		disk->d_flags |= DISKFLAG_CANDELETE;
468	if (nvme_ns_get_flags(ns) & NVME_NS_FLUSH_SUPPORTED)
469		disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
470
471	/*
472	 * d_ident and d_descr are both far bigger than the length of either
473	 *  the serial or model number strings.
474	 */
475	nvme_strvis(disk->d_ident, nvme_ns_get_serial_number(ns),
476	    sizeof(disk->d_ident), NVME_SERIAL_NUMBER_LENGTH);
477	nvme_strvis(descr, nvme_ns_get_model_number(ns), sizeof(descr),
478	    NVME_MODEL_NUMBER_LENGTH);
479	strlcpy(disk->d_descr, descr, sizeof(descr));
480
481	disk->d_rotation_rate = DISK_RR_NON_ROTATING;
482
483	disk_create(disk, DISK_VERSION);
484
485	printf(NVD_STR"%u: <%s> NVMe namespace\n", disk->d_unit, descr);
486	printf(NVD_STR"%u: %juMB (%ju %u byte sectors)\n", disk->d_unit,
487		(uintmax_t)disk->d_mediasize / (1024*1024),
488		(uintmax_t)disk->d_mediasize / disk->d_sectorsize,
489		disk->d_sectorsize);
490
491	return (ndisk);
492}
493
494static void
495nvd_controller_fail(void *ctrlr_arg)
496{
497	struct nvd_controller	*ctrlr = ctrlr_arg;
498	struct nvd_disk		*ndisk;
499
500	mtx_lock(&nvd_lock);
501	TAILQ_REMOVE(&ctrlr_head, ctrlr, tailq);
502	TAILQ_FOREACH(ndisk, &ctrlr->disk_head, ctrlr_tailq)
503		nvd_gone(ndisk);
504	while (!TAILQ_EMPTY(&ctrlr->disk_head))
505		msleep(&ctrlr->disk_head, &nvd_lock, 0, "nvd_fail", 0);
506	mtx_unlock(&nvd_lock);
507	free(ctrlr, M_NVD);
508}
509
510