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