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