xref: /freebsd/sys/dev/nvme/nvme_ns.c (revision 2e3f49888ec8851bafb22011533217487764fdb0)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2012-2013 Intel Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/bio.h>
31 #include <sys/bus.h>
32 #include <sys/conf.h>
33 #include <sys/disk.h>
34 #include <sys/fcntl.h>
35 #include <sys/ioccom.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/proc.h>
39 #include <sys/systm.h>
40 
41 #include <dev/pci/pcivar.h>
42 
43 #include <geom/geom.h>
44 
45 #include "nvme_private.h"
46 
47 static void		nvme_bio_child_inbed(struct bio *parent, int bio_error);
48 static void		nvme_bio_child_done(void *arg,
49 					    const struct nvme_completion *cpl);
50 static uint32_t		nvme_get_num_segments(uint64_t addr, uint64_t size,
51 					      uint32_t alignment);
52 static void		nvme_free_child_bios(int num_bios,
53 					     struct bio **child_bios);
54 static struct bio **	nvme_allocate_child_bios(int num_bios);
55 static struct bio **	nvme_construct_child_bios(struct bio *bp,
56 						  uint32_t alignment,
57 						  int *num_bios);
58 static int		nvme_ns_split_bio(struct nvme_namespace *ns,
59 					  struct bio *bp,
60 					  uint32_t alignment);
61 
62 static int
63 nvme_ns_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
64     struct thread *td)
65 {
66 	struct nvme_namespace			*ns;
67 	struct nvme_controller			*ctrlr;
68 	struct nvme_pt_command			*pt;
69 
70 	ns = cdev->si_drv1;
71 	ctrlr = ns->ctrlr;
72 
73 	switch (cmd) {
74 	case NVME_IO_TEST:
75 	case NVME_BIO_TEST:
76 		nvme_ns_test(ns, cmd, arg);
77 		break;
78 	case NVME_PASSTHROUGH_CMD:
79 		pt = (struct nvme_pt_command *)arg;
80 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, ns->id,
81 		    1 /* is_user_buffer */, 0 /* is_admin_cmd */));
82 	case NVME_GET_NSID:
83 	{
84 		struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
85 		strncpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
86 		    sizeof(gnsid->cdev));
87 		gnsid->cdev[sizeof(gnsid->cdev) - 1] = '\0';
88 		gnsid->nsid = ns->id;
89 		break;
90 	}
91 	case DIOCGMEDIASIZE:
92 		*(off_t *)arg = (off_t)nvme_ns_get_size(ns);
93 		break;
94 	case DIOCGSECTORSIZE:
95 		*(u_int *)arg = nvme_ns_get_sector_size(ns);
96 		break;
97 	default:
98 		return (ENOTTY);
99 	}
100 
101 	return (0);
102 }
103 
104 static int
105 nvme_ns_open(struct cdev *dev __unused, int flags, int fmt __unused,
106     struct thread *td)
107 {
108 	int error = 0;
109 
110 	if (flags & FWRITE)
111 		error = securelevel_gt(td->td_ucred, 0);
112 
113 	return (error);
114 }
115 
116 static int
117 nvme_ns_close(struct cdev *dev __unused, int flags, int fmt __unused,
118     struct thread *td)
119 {
120 
121 	return (0);
122 }
123 
124 static void
125 nvme_ns_strategy_done(void *arg, const struct nvme_completion *cpl)
126 {
127 	struct bio *bp = arg;
128 
129 	/*
130 	 * TODO: add more extensive translation of NVMe status codes
131 	 *  to different bio error codes (i.e. EIO, EINVAL, etc.)
132 	 */
133 	if (nvme_completion_is_error(cpl)) {
134 		bp->bio_error = EIO;
135 		bp->bio_flags |= BIO_ERROR;
136 		bp->bio_resid = bp->bio_bcount;
137 	} else
138 		bp->bio_resid = 0;
139 
140 	biodone(bp);
141 }
142 
143 static void
144 nvme_ns_strategy(struct bio *bp)
145 {
146 	struct nvme_namespace	*ns;
147 	int			err;
148 
149 	ns = bp->bio_dev->si_drv1;
150 	err = nvme_ns_bio_process(ns, bp, nvme_ns_strategy_done);
151 
152 	if (err) {
153 		bp->bio_error = err;
154 		bp->bio_flags |= BIO_ERROR;
155 		bp->bio_resid = bp->bio_bcount;
156 		biodone(bp);
157 	}
158 
159 }
160 
161 static struct cdevsw nvme_ns_cdevsw = {
162 	.d_version =	D_VERSION,
163 	.d_flags =	D_DISK,
164 	.d_read =	physread,
165 	.d_write =	physwrite,
166 	.d_open =	nvme_ns_open,
167 	.d_close =	nvme_ns_close,
168 	.d_strategy =	nvme_ns_strategy,
169 	.d_ioctl =	nvme_ns_ioctl
170 };
171 
172 uint32_t
173 nvme_ns_get_max_io_xfer_size(struct nvme_namespace *ns)
174 {
175 	return ns->ctrlr->max_xfer_size;
176 }
177 
178 uint32_t
179 nvme_ns_get_sector_size(struct nvme_namespace *ns)
180 {
181 	uint8_t flbas_fmt, lbads;
182 
183 	flbas_fmt = (ns->data.flbas >> NVME_NS_DATA_FLBAS_FORMAT_SHIFT) &
184 		NVME_NS_DATA_FLBAS_FORMAT_MASK;
185 	lbads = (ns->data.lbaf[flbas_fmt] >> NVME_NS_DATA_LBAF_LBADS_SHIFT) &
186 		NVME_NS_DATA_LBAF_LBADS_MASK;
187 
188 	return (1 << lbads);
189 }
190 
191 uint64_t
192 nvme_ns_get_num_sectors(struct nvme_namespace *ns)
193 {
194 	return (ns->data.nsze);
195 }
196 
197 uint64_t
198 nvme_ns_get_size(struct nvme_namespace *ns)
199 {
200 	return (nvme_ns_get_num_sectors(ns) * nvme_ns_get_sector_size(ns));
201 }
202 
203 uint32_t
204 nvme_ns_get_flags(struct nvme_namespace *ns)
205 {
206 	return (ns->flags);
207 }
208 
209 const char *
210 nvme_ns_get_serial_number(struct nvme_namespace *ns)
211 {
212 	return ((const char *)ns->ctrlr->cdata.sn);
213 }
214 
215 const char *
216 nvme_ns_get_model_number(struct nvme_namespace *ns)
217 {
218 	return ((const char *)ns->ctrlr->cdata.mn);
219 }
220 
221 const struct nvme_namespace_data *
222 nvme_ns_get_data(struct nvme_namespace *ns)
223 {
224 
225 	return (&ns->data);
226 }
227 
228 uint32_t
229 nvme_ns_get_stripesize(struct nvme_namespace *ns)
230 {
231 	uint32_t ss;
232 
233 	if (((ns->data.nsfeat >> NVME_NS_DATA_NSFEAT_NPVALID_SHIFT) &
234 	    NVME_NS_DATA_NSFEAT_NPVALID_MASK) != 0) {
235 		ss = nvme_ns_get_sector_size(ns);
236 		if (ns->data.npwa != 0)
237 			return ((ns->data.npwa + 1) * ss);
238 		else if (ns->data.npwg != 0)
239 			return ((ns->data.npwg + 1) * ss);
240 	}
241 	return (ns->boundary);
242 }
243 
244 static void
245 nvme_ns_bio_done(void *arg, const struct nvme_completion *status)
246 {
247 	struct bio	*bp = arg;
248 	nvme_cb_fn_t	bp_cb_fn;
249 
250 	bp_cb_fn = bp->bio_driver1;
251 
252 	if (bp->bio_driver2)
253 		free(bp->bio_driver2, M_NVME);
254 
255 	if (nvme_completion_is_error(status)) {
256 		bp->bio_flags |= BIO_ERROR;
257 		if (bp->bio_error == 0)
258 			bp->bio_error = EIO;
259 	}
260 
261 	if ((bp->bio_flags & BIO_ERROR) == 0)
262 		bp->bio_resid = 0;
263 	else
264 		bp->bio_resid = bp->bio_bcount;
265 
266 	bp_cb_fn(bp, status);
267 }
268 
269 static void
270 nvme_bio_child_inbed(struct bio *parent, int bio_error)
271 {
272 	struct nvme_completion	parent_cpl;
273 	int			children, inbed;
274 
275 	if (bio_error != 0) {
276 		parent->bio_flags |= BIO_ERROR;
277 		parent->bio_error = bio_error;
278 	}
279 
280 	/*
281 	 * atomic_fetchadd will return value before adding 1, so we still
282 	 *  must add 1 to get the updated inbed number.  Save bio_children
283 	 *  before incrementing to guard against race conditions when
284 	 *  two children bios complete on different queues.
285 	 */
286 	children = atomic_load_acq_int(&parent->bio_children);
287 	inbed = atomic_fetchadd_int(&parent->bio_inbed, 1) + 1;
288 	if (inbed == children) {
289 		bzero(&parent_cpl, sizeof(parent_cpl));
290 		if (parent->bio_flags & BIO_ERROR) {
291 			parent_cpl.status &= ~(NVME_STATUS_SC_MASK << NVME_STATUS_SC_SHIFT);
292 			parent_cpl.status |= (NVME_SC_DATA_TRANSFER_ERROR) << NVME_STATUS_SC_SHIFT;
293 		}
294 		nvme_ns_bio_done(parent, &parent_cpl);
295 	}
296 }
297 
298 static void
299 nvme_bio_child_done(void *arg, const struct nvme_completion *cpl)
300 {
301 	struct bio		*child = arg;
302 	struct bio		*parent;
303 	int			bio_error;
304 
305 	parent = child->bio_parent;
306 	g_destroy_bio(child);
307 	bio_error = nvme_completion_is_error(cpl) ? EIO : 0;
308 	nvme_bio_child_inbed(parent, bio_error);
309 }
310 
311 static uint32_t
312 nvme_get_num_segments(uint64_t addr, uint64_t size, uint32_t align)
313 {
314 	uint32_t	num_segs, offset, remainder;
315 
316 	if (align == 0)
317 		return (1);
318 
319 	KASSERT((align & (align - 1)) == 0, ("alignment not power of 2\n"));
320 
321 	num_segs = size / align;
322 	remainder = size & (align - 1);
323 	offset = addr & (align - 1);
324 	if (remainder > 0 || offset > 0)
325 		num_segs += 1 + (remainder + offset - 1) / align;
326 	return (num_segs);
327 }
328 
329 static void
330 nvme_free_child_bios(int num_bios, struct bio **child_bios)
331 {
332 	int i;
333 
334 	for (i = 0; i < num_bios; i++) {
335 		if (child_bios[i] != NULL)
336 			g_destroy_bio(child_bios[i]);
337 	}
338 
339 	free(child_bios, M_NVME);
340 }
341 
342 static struct bio **
343 nvme_allocate_child_bios(int num_bios)
344 {
345 	struct bio **child_bios;
346 	int err = 0, i;
347 
348 	child_bios = malloc(num_bios * sizeof(struct bio *), M_NVME, M_NOWAIT);
349 	if (child_bios == NULL)
350 		return (NULL);
351 
352 	for (i = 0; i < num_bios; i++) {
353 		child_bios[i] = g_new_bio();
354 		if (child_bios[i] == NULL)
355 			err = ENOMEM;
356 	}
357 
358 	if (err == ENOMEM) {
359 		nvme_free_child_bios(num_bios, child_bios);
360 		return (NULL);
361 	}
362 
363 	return (child_bios);
364 }
365 
366 static struct bio **
367 nvme_construct_child_bios(struct bio *bp, uint32_t alignment, int *num_bios)
368 {
369 	struct bio	**child_bios;
370 	struct bio	*child;
371 	uint64_t	cur_offset;
372 	caddr_t		data;
373 	uint32_t	rem_bcount;
374 	int		i;
375 	struct vm_page	**ma;
376 	uint32_t	ma_offset;
377 
378 	*num_bios = nvme_get_num_segments(bp->bio_offset, bp->bio_bcount,
379 	    alignment);
380 	child_bios = nvme_allocate_child_bios(*num_bios);
381 	if (child_bios == NULL)
382 		return (NULL);
383 
384 	bp->bio_children = *num_bios;
385 	bp->bio_inbed = 0;
386 	cur_offset = bp->bio_offset;
387 	rem_bcount = bp->bio_bcount;
388 	data = bp->bio_data;
389 	ma_offset = bp->bio_ma_offset;
390 	ma = bp->bio_ma;
391 
392 	for (i = 0; i < *num_bios; i++) {
393 		child = child_bios[i];
394 		child->bio_parent = bp;
395 		child->bio_cmd = bp->bio_cmd;
396 		child->bio_offset = cur_offset;
397 		child->bio_bcount = min(rem_bcount,
398 		    alignment - (cur_offset & (alignment - 1)));
399 		child->bio_flags = bp->bio_flags;
400 		if (bp->bio_flags & BIO_UNMAPPED) {
401 			child->bio_ma_offset = ma_offset;
402 			child->bio_ma = ma;
403 			child->bio_ma_n =
404 			    nvme_get_num_segments(child->bio_ma_offset,
405 				child->bio_bcount, PAGE_SIZE);
406 			ma_offset = (ma_offset + child->bio_bcount) &
407 			    PAGE_MASK;
408 			ma += child->bio_ma_n;
409 			if (ma_offset != 0)
410 				ma -= 1;
411 		} else {
412 			child->bio_data = data;
413 			data += child->bio_bcount;
414 		}
415 		cur_offset += child->bio_bcount;
416 		rem_bcount -= child->bio_bcount;
417 	}
418 
419 	return (child_bios);
420 }
421 
422 static int
423 nvme_ns_split_bio(struct nvme_namespace *ns, struct bio *bp,
424     uint32_t alignment)
425 {
426 	struct bio	*child;
427 	struct bio	**child_bios;
428 	int		err, i, num_bios;
429 
430 	child_bios = nvme_construct_child_bios(bp, alignment, &num_bios);
431 	if (child_bios == NULL)
432 		return (ENOMEM);
433 
434 	for (i = 0; i < num_bios; i++) {
435 		child = child_bios[i];
436 		err = nvme_ns_bio_process(ns, child, nvme_bio_child_done);
437 		if (err != 0) {
438 			nvme_bio_child_inbed(bp, err);
439 			g_destroy_bio(child);
440 		}
441 	}
442 
443 	free(child_bios, M_NVME);
444 	return (0);
445 }
446 
447 int
448 nvme_ns_bio_process(struct nvme_namespace *ns, struct bio *bp,
449 	nvme_cb_fn_t cb_fn)
450 {
451 	struct nvme_dsm_range	*dsm_range;
452 	uint32_t		num_bios;
453 	int			err;
454 
455 	bp->bio_driver1 = cb_fn;
456 
457 	if (ns->boundary > 0 &&
458 	    (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE)) {
459 		num_bios = nvme_get_num_segments(bp->bio_offset,
460 		    bp->bio_bcount, ns->boundary);
461 		if (num_bios > 1)
462 			return (nvme_ns_split_bio(ns, bp, ns->boundary));
463 	}
464 
465 	switch (bp->bio_cmd) {
466 	case BIO_READ:
467 		err = nvme_ns_cmd_read_bio(ns, bp, nvme_ns_bio_done, bp);
468 		break;
469 	case BIO_WRITE:
470 		err = nvme_ns_cmd_write_bio(ns, bp, nvme_ns_bio_done, bp);
471 		break;
472 	case BIO_FLUSH:
473 		err = nvme_ns_cmd_flush(ns, nvme_ns_bio_done, bp);
474 		break;
475 	case BIO_DELETE:
476 		dsm_range =
477 		    malloc(sizeof(struct nvme_dsm_range), M_NVME,
478 		    M_ZERO | M_NOWAIT);
479 		if (!dsm_range) {
480 			err = ENOMEM;
481 			break;
482 		}
483 		dsm_range->length =
484 		    htole32(bp->bio_bcount/nvme_ns_get_sector_size(ns));
485 		dsm_range->starting_lba =
486 		    htole64(bp->bio_offset/nvme_ns_get_sector_size(ns));
487 		bp->bio_driver2 = dsm_range;
488 		err = nvme_ns_cmd_deallocate(ns, dsm_range, 1,
489 			nvme_ns_bio_done, bp);
490 		if (err != 0)
491 			free(dsm_range, M_NVME);
492 		break;
493 	default:
494 		err = EOPNOTSUPP;
495 		break;
496 	}
497 
498 	return (err);
499 }
500 
501 int
502 nvme_ns_ioctl_process(struct nvme_namespace *ns, u_long cmd, caddr_t arg,
503     int flag, struct thread *td)
504 {
505 	return (nvme_ns_ioctl(ns->cdev, cmd, arg, flag, td));
506 }
507 
508 int
509 nvme_ns_construct(struct nvme_namespace *ns, uint32_t id,
510     struct nvme_controller *ctrlr)
511 {
512 	struct make_dev_args                    md_args;
513 	struct nvme_completion_poll_status	status;
514 	int                                     res;
515 	int					unit;
516 	uint8_t					flbas_fmt;
517 	uint8_t					vwc_present;
518 
519 	ns->ctrlr = ctrlr;
520 	ns->id = id;
521 
522 	/*
523 	 * Namespaces are reconstructed after a controller reset, so check
524 	 *  to make sure we only call mtx_init once on each mtx.
525 	 *
526 	 * TODO: Move this somewhere where it gets called at controller
527 	 *  construction time, which is not invoked as part of each
528 	 *  controller reset.
529 	 */
530 	if (!mtx_initialized(&ns->lock))
531 		mtx_init(&ns->lock, "nvme ns lock", NULL, MTX_DEF);
532 
533 	status.done = 0;
534 	nvme_ctrlr_cmd_identify_namespace(ctrlr, id, &ns->data,
535 	    nvme_completion_poll_cb, &status);
536 	nvme_completion_poll(&status);
537 	if (nvme_completion_is_error(&status.cpl)) {
538 		nvme_printf(ctrlr, "nvme_identify_namespace failed\n");
539 		return (ENXIO);
540 	}
541 
542 	/* Convert data to host endian */
543 	nvme_namespace_data_swapbytes(&ns->data);
544 
545 	/*
546 	 * If the size of is zero, chances are this isn't a valid
547 	 * namespace (eg one that's not been configured yet). The
548 	 * standard says the entire id will be zeros, so this is a
549 	 * cheap way to test for that.
550 	 */
551 	if (ns->data.nsze == 0)
552 		return (ENXIO);
553 
554 	flbas_fmt = (ns->data.flbas >> NVME_NS_DATA_FLBAS_FORMAT_SHIFT) &
555 		NVME_NS_DATA_FLBAS_FORMAT_MASK;
556 	/*
557 	 * Note: format is a 0-based value, so > is appropriate here,
558 	 *  not >=.
559 	 */
560 	if (flbas_fmt > ns->data.nlbaf) {
561 		nvme_printf(ctrlr,
562 		    "lba format %d exceeds number supported (%d)\n",
563 		    flbas_fmt, ns->data.nlbaf + 1);
564 		return (ENXIO);
565 	}
566 
567 	/*
568 	 * Older Intel devices (like the PC35xxx and P45xx series) advertise in
569 	 * vendor specific space an alignment that improves performance.  If
570 	 * present use for the stripe size.  NVMe 1.3 standardized this as
571 	 * NOIOB, and newer Intel drives use that.
572 	 */
573 	if ((ctrlr->quirks & QUIRK_INTEL_ALIGNMENT) != 0) {
574 		if (ctrlr->cdata.vs[3] != 0)
575 			ns->boundary =
576 			    1 << (ctrlr->cdata.vs[3] + NVME_MPS_SHIFT +
577 				NVME_CAP_HI_MPSMIN(ctrlr->cap_hi));
578 		else
579 			ns->boundary = 0;
580 	} else {
581 		ns->boundary = ns->data.noiob * nvme_ns_get_sector_size(ns);
582 	}
583 
584 	if (nvme_ctrlr_has_dataset_mgmt(&ctrlr->cdata))
585 		ns->flags |= NVME_NS_DEALLOCATE_SUPPORTED;
586 
587 	vwc_present = (ctrlr->cdata.vwc >> NVME_CTRLR_DATA_VWC_PRESENT_SHIFT) &
588 		NVME_CTRLR_DATA_VWC_PRESENT_MASK;
589 	if (vwc_present)
590 		ns->flags |= NVME_NS_FLUSH_SUPPORTED;
591 
592 	/*
593 	 * cdev may have already been created, if we are reconstructing the
594 	 *  namespace after a controller-level reset.
595 	 */
596 	if (ns->cdev != NULL)
597 		return (0);
598 
599 	/*
600 	 * Namespace IDs start at 1, so we need to subtract 1 to create a
601 	 *  correct unit number.
602 	 */
603 	unit = device_get_unit(ctrlr->dev) * NVME_MAX_NAMESPACES + ns->id - 1;
604 
605 	make_dev_args_init(&md_args);
606 	md_args.mda_devsw = &nvme_ns_cdevsw;
607 	md_args.mda_unit = unit;
608 	md_args.mda_mode = 0600;
609 	md_args.mda_si_drv1 = ns;
610 	res = make_dev_s(&md_args, &ns->cdev, "nvme%dns%d",
611 	    device_get_unit(ctrlr->dev), ns->id);
612 	if (res != 0)
613 		return (ENXIO);
614 
615 	ns->cdev->si_flags |= SI_UNMAPPED;
616 
617 	return (0);
618 }
619 
620 void
621 nvme_ns_destruct(struct nvme_namespace *ns)
622 {
623 
624 	if (ns->cdev != NULL)
625 		destroy_dev(ns->cdev);
626 }
627