xref: /freebsd/sys/cam/nvme/nvme_da.c (revision 97cb52fa9aefd90fad38790fded50905aeeb9b9e)
1 /*-
2  * Copyright (c) 2015 Netflix, Inc
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * Derived from ata_da.c:
27  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/bio.h>
39 #include <sys/sysctl.h>
40 #include <sys/taskqueue.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/conf.h>
44 #include <sys/devicestat.h>
45 #include <sys/eventhandler.h>
46 #include <sys/malloc.h>
47 #include <sys/cons.h>
48 #include <sys/proc.h>
49 #include <sys/reboot.h>
50 #include <geom/geom_disk.h>
51 #endif /* _KERNEL */
52 
53 #ifndef _KERNEL
54 #include <stdio.h>
55 #include <string.h>
56 #endif /* _KERNEL */
57 
58 #include <cam/cam.h>
59 #include <cam/cam_ccb.h>
60 #include <cam/cam_periph.h>
61 #include <cam/cam_xpt_periph.h>
62 #include <cam/cam_sim.h>
63 #include <cam/cam_iosched.h>
64 
65 #include <cam/nvme/nvme_all.h>
66 
67 typedef enum {
68 	NDA_STATE_NORMAL
69 } nda_state;
70 
71 typedef enum {
72 	NDA_FLAG_OPEN		= 0x0001,
73 	NDA_FLAG_DIRTY		= 0x0002,
74 	NDA_FLAG_SCTX_INIT	= 0x0004,
75 } nda_flags;
76 
77 typedef enum {
78 	NDA_Q_4K   = 0x01,
79 	NDA_Q_NONE = 0x00,
80 } nda_quirks;
81 
82 #define NDA_Q_BIT_STRING	\
83 	"\020"			\
84 	"\001Bit 0"
85 
86 typedef enum {
87 	NDA_CCB_BUFFER_IO	= 0x01,
88 	NDA_CCB_DUMP            = 0x02,
89 	NDA_CCB_TRIM            = 0x03,
90 	NDA_CCB_TYPE_MASK	= 0x0F,
91 } nda_ccb_state;
92 
93 /* Offsets into our private area for storing information */
94 #define ccb_state	ppriv_field0
95 #define ccb_bp		ppriv_ptr1
96 
97 struct trim_request {
98 	TAILQ_HEAD(, bio) bps;
99 };
100 struct nda_softc {
101 	struct   cam_iosched_softc *cam_iosched;
102 	int	 outstanding_cmds;	/* Number of active commands */
103 	int	 refcount;		/* Active xpt_action() calls */
104 	nda_state state;
105 	nda_flags flags;
106 	nda_quirks quirks;
107 	int	 unmappedio;
108 	uint32_t  nsid;			/* Namespace ID for this nda device */
109 	struct disk *disk;
110 	struct task		sysctl_task;
111 	struct sysctl_ctx_list	sysctl_ctx;
112 	struct sysctl_oid	*sysctl_tree;
113 	struct trim_request	trim_req;
114 #ifdef CAM_IO_STATS
115 	struct sysctl_ctx_list	sysctl_stats_ctx;
116 	struct sysctl_oid	*sysctl_stats_tree;
117 	u_int	timeouts;
118 	u_int	errors;
119 	u_int	invalidations;
120 #endif
121 };
122 
123 /* Need quirk table */
124 
125 static	disk_strategy_t	ndastrategy;
126 static	dumper_t	ndadump;
127 static	periph_init_t	ndainit;
128 static	void		ndaasync(void *callback_arg, u_int32_t code,
129 				struct cam_path *path, void *arg);
130 static	void		ndasysctlinit(void *context, int pending);
131 static	periph_ctor_t	ndaregister;
132 static	periph_dtor_t	ndacleanup;
133 static	periph_start_t	ndastart;
134 static	periph_oninv_t	ndaoninvalidate;
135 static	void		ndadone(struct cam_periph *periph,
136 			       union ccb *done_ccb);
137 static  int		ndaerror(union ccb *ccb, u_int32_t cam_flags,
138 				u_int32_t sense_flags);
139 static void		ndashutdown(void *arg, int howto);
140 static void		ndasuspend(void *arg);
141 
142 #ifndef	NDA_DEFAULT_SEND_ORDERED
143 #define	NDA_DEFAULT_SEND_ORDERED	1
144 #endif
145 #ifndef NDA_DEFAULT_TIMEOUT
146 #define NDA_DEFAULT_TIMEOUT 30	/* Timeout in seconds */
147 #endif
148 #ifndef	NDA_DEFAULT_RETRY
149 #define	NDA_DEFAULT_RETRY	4
150 #endif
151 
152 
153 //static int nda_retry_count = NDA_DEFAULT_RETRY;
154 static int nda_send_ordered = NDA_DEFAULT_SEND_ORDERED;
155 static int nda_default_timeout = NDA_DEFAULT_TIMEOUT;
156 
157 /*
158  * All NVMe media is non-rotational, so all nvme device instances
159  * share this to implement the sysctl.
160  */
161 static int nda_rotating_media = 0;
162 
163 static SYSCTL_NODE(_kern_cam, OID_AUTO, nda, CTLFLAG_RD, 0,
164             "CAM Direct Access Disk driver");
165 
166 static struct periph_driver ndadriver =
167 {
168 	ndainit, "nda",
169 	TAILQ_HEAD_INITIALIZER(ndadriver.units), /* generation */ 0
170 };
171 
172 PERIPHDRIVER_DECLARE(nda, ndadriver);
173 
174 static MALLOC_DEFINE(M_NVMEDA, "nvme_da", "nvme_da buffers");
175 
176 /*
177  * nice wrappers. Maybe these belong in nvme_all.c instead of
178  * here, but this is the only place that uses these. Should
179  * we ever grow another NVME periph, we should move them
180  * all there wholesale.
181  */
182 
183 static void
184 nda_nvme_flush(struct nda_softc *softc, struct ccb_nvmeio *nvmeio)
185 {
186 	cam_fill_nvmeio(nvmeio,
187 	    0,			/* retries */
188 	    ndadone,		/* cbfcnp */
189 	    CAM_DIR_NONE,	/* flags */
190 	    NULL,		/* data_ptr */
191 	    0,			/* dxfer_len */
192 	    nda_default_timeout * 1000); /* timeout 30s */
193 	nvme_ns_flush_cmd(&nvmeio->cmd, softc->nsid);
194 }
195 
196 static void
197 nda_nvme_trim(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
198     void *payload, uint32_t num_ranges)
199 {
200 	cam_fill_nvmeio(nvmeio,
201 	    0,			/* retries */
202 	    ndadone,		/* cbfcnp */
203 	    CAM_DIR_OUT,	/* flags */
204 	    payload,		/* data_ptr */
205 	    num_ranges * sizeof(struct nvme_dsm_range), /* dxfer_len */
206 	    nda_default_timeout * 1000); /* timeout 30s */
207 	nvme_ns_trim_cmd(&nvmeio->cmd, softc->nsid, num_ranges);
208 }
209 
210 static void
211 nda_nvme_write(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
212     void *payload, uint64_t lba, uint32_t len, uint32_t count)
213 {
214 	cam_fill_nvmeio(nvmeio,
215 	    0,			/* retries */
216 	    ndadone,		/* cbfcnp */
217 	    CAM_DIR_OUT,	/* flags */
218 	    payload,		/* data_ptr */
219 	    len,		/* dxfer_len */
220 	    nda_default_timeout * 1000); /* timeout 30s */
221 	nvme_ns_write_cmd(&nvmeio->cmd, softc->nsid, lba, count);
222 }
223 
224 static void
225 nda_nvme_rw_bio(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
226     struct bio *bp, uint32_t rwcmd)
227 {
228 	int flags = rwcmd == NVME_OPC_READ ? CAM_DIR_IN : CAM_DIR_OUT;
229 	void *payload;
230 	uint64_t lba;
231 	uint32_t count;
232 
233 	if (bp->bio_flags & BIO_UNMAPPED) {
234 		flags |= CAM_DATA_BIO;
235 		payload = bp;
236 	} else {
237 		payload = bp->bio_data;
238 	}
239 
240 	lba = bp->bio_pblkno;
241 	count = bp->bio_bcount / softc->disk->d_sectorsize;
242 
243 	cam_fill_nvmeio(nvmeio,
244 	    0,			/* retries */
245 	    ndadone,		/* cbfcnp */
246 	    flags,		/* flags */
247 	    payload,		/* data_ptr */
248 	    bp->bio_bcount,	/* dxfer_len */
249 	    nda_default_timeout * 1000); /* timeout 30s */
250 	nvme_ns_rw_cmd(&nvmeio->cmd, rwcmd, softc->nsid, lba, count);
251 }
252 
253 static int
254 ndaopen(struct disk *dp)
255 {
256 	struct cam_periph *periph;
257 	struct nda_softc *softc;
258 	int error;
259 
260 	periph = (struct cam_periph *)dp->d_drv1;
261 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
262 		return(ENXIO);
263 	}
264 
265 	cam_periph_lock(periph);
266 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
267 		cam_periph_unlock(periph);
268 		cam_periph_release(periph);
269 		return (error);
270 	}
271 
272 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
273 	    ("ndaopen\n"));
274 
275 	softc = (struct nda_softc *)periph->softc;
276 	softc->flags |= NDA_FLAG_OPEN;
277 
278 	cam_periph_unhold(periph);
279 	cam_periph_unlock(periph);
280 	return (0);
281 }
282 
283 static int
284 ndaclose(struct disk *dp)
285 {
286 	struct	cam_periph *periph;
287 	struct	nda_softc *softc;
288 	union ccb *ccb;
289 	int error;
290 
291 	periph = (struct cam_periph *)dp->d_drv1;
292 	softc = (struct nda_softc *)periph->softc;
293 	cam_periph_lock(periph);
294 
295 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
296 	    ("ndaclose\n"));
297 
298 	if ((softc->flags & NDA_FLAG_DIRTY) != 0 &&
299 	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
300 	    cam_periph_hold(periph, PRIBIO) == 0) {
301 
302 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
303 		nda_nvme_flush(softc, &ccb->nvmeio);
304 		error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
305 		    /*sense_flags*/0, softc->disk->d_devstat);
306 
307 		if (error != 0)
308 			xpt_print(periph->path, "Synchronize cache failed\n");
309 		else
310 			softc->flags &= ~NDA_FLAG_DIRTY;
311 		xpt_release_ccb(ccb);
312 		cam_periph_unhold(periph);
313 	}
314 
315 	softc->flags &= ~NDA_FLAG_OPEN;
316 
317 	while (softc->refcount != 0)
318 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "ndaclose", 1);
319 	cam_periph_unlock(periph);
320 	cam_periph_release(periph);
321 	return (0);
322 }
323 
324 static void
325 ndaschedule(struct cam_periph *periph)
326 {
327 	struct nda_softc *softc = (struct nda_softc *)periph->softc;
328 
329 	if (softc->state != NDA_STATE_NORMAL)
330 		return;
331 
332 	cam_iosched_schedule(softc->cam_iosched, periph);
333 }
334 
335 /*
336  * Actually translate the requested transfer into one the physical driver
337  * can understand.  The transfer is described by a buf and will include
338  * only one physical transfer.
339  */
340 static void
341 ndastrategy(struct bio *bp)
342 {
343 	struct cam_periph *periph;
344 	struct nda_softc *softc;
345 
346 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
347 	softc = (struct nda_softc *)periph->softc;
348 
349 	cam_periph_lock(periph);
350 
351 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastrategy(%p)\n", bp));
352 
353 	/*
354 	 * If the device has been made invalid, error out
355 	 */
356 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
357 		cam_periph_unlock(periph);
358 		biofinish(bp, NULL, ENXIO);
359 		return;
360 	}
361 
362 	/*
363 	 * Place it in the queue of disk activities for this disk
364 	 */
365 	cam_iosched_queue_work(softc->cam_iosched, bp);
366 
367 	/*
368 	 * Schedule ourselves for performing the work.
369 	 */
370 	ndaschedule(periph);
371 	cam_periph_unlock(periph);
372 
373 	return;
374 }
375 
376 static int
377 ndadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
378 {
379 	struct	    cam_periph *periph;
380 	struct	    nda_softc *softc;
381 	u_int	    secsize;
382 	struct ccb_nvmeio nvmeio;
383 	struct	    disk *dp;
384 	uint64_t    lba;
385 	uint32_t    count;
386 	int	    error = 0;
387 
388 	dp = arg;
389 	periph = dp->d_drv1;
390 	softc = (struct nda_softc *)periph->softc;
391 	cam_periph_lock(periph);
392 	secsize = softc->disk->d_sectorsize;
393 	lba = offset / secsize;
394 	count = length / secsize;
395 
396 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
397 		cam_periph_unlock(periph);
398 		return (ENXIO);
399 	}
400 
401 	/* xpt_get_ccb returns a zero'd allocation for the ccb, mimic that here */
402 	memset(&nvmeio, 0, sizeof(nvmeio));
403 	if (length > 0) {
404 		xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
405 		nvmeio.ccb_h.ccb_state = NDA_CCB_DUMP;
406 		nda_nvme_write(softc, &nvmeio, virtual, lba, length, count);
407 		error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
408 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
409 		if (error != 0)
410 			printf("Aborting dump due to I/O error %d.\n", error);
411 		cam_periph_unlock(periph);
412 
413 		return (error);
414 	}
415 
416 	/* Flush */
417 	xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
418 
419 	nvmeio.ccb_h.ccb_state = NDA_CCB_DUMP;
420 	nda_nvme_flush(softc, &nvmeio);
421 	error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
422 	    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
423 	if (error != 0)
424 		xpt_print(periph->path, "flush cmd failed\n");
425 	cam_periph_unlock(periph);
426 	return (error);
427 }
428 
429 static void
430 ndainit(void)
431 {
432 	cam_status status;
433 
434 	/*
435 	 * Install a global async callback.  This callback will
436 	 * receive async callbacks like "new device found".
437 	 */
438 	status = xpt_register_async(AC_FOUND_DEVICE, ndaasync, NULL, NULL);
439 
440 	if (status != CAM_REQ_CMP) {
441 		printf("nda: Failed to attach master async callback "
442 		       "due to status 0x%x!\n", status);
443 	} else if (nda_send_ordered) {
444 
445 		/* Register our event handlers */
446 		if ((EVENTHANDLER_REGISTER(power_suspend, ndasuspend,
447 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
448 		    printf("ndainit: power event registration failed!\n");
449 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, ndashutdown,
450 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
451 		    printf("ndainit: shutdown event registration failed!\n");
452 	}
453 }
454 
455 /*
456  * Callback from GEOM, called when it has finished cleaning up its
457  * resources.
458  */
459 static void
460 ndadiskgonecb(struct disk *dp)
461 {
462 	struct cam_periph *periph;
463 
464 	periph = (struct cam_periph *)dp->d_drv1;
465 
466 	cam_periph_release(periph);
467 }
468 
469 static void
470 ndaoninvalidate(struct cam_periph *periph)
471 {
472 	struct nda_softc *softc;
473 
474 	softc = (struct nda_softc *)periph->softc;
475 
476 	/*
477 	 * De-register any async callbacks.
478 	 */
479 	xpt_register_async(0, ndaasync, periph, periph->path);
480 #ifdef CAM_IO_STATS
481 	softc->invalidations++;
482 #endif
483 
484 	/*
485 	 * Return all queued I/O with ENXIO.
486 	 * XXX Handle any transactions queued to the card
487 	 *     with XPT_ABORT_CCB.
488 	 */
489 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
490 
491 	disk_gone(softc->disk);
492 }
493 
494 static void
495 ndacleanup(struct cam_periph *periph)
496 {
497 	struct nda_softc *softc;
498 
499 	softc = (struct nda_softc *)periph->softc;
500 
501 	cam_periph_unlock(periph);
502 
503 	cam_iosched_fini(softc->cam_iosched);
504 
505 	/*
506 	 * If we can't free the sysctl tree, oh well...
507 	 */
508 	if ((softc->flags & NDA_FLAG_SCTX_INIT) != 0) {
509 #ifdef CAM_IO_STATS
510 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
511 			xpt_print(periph->path,
512 			    "can't remove sysctl stats context\n");
513 #endif
514 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
515 			xpt_print(periph->path,
516 			    "can't remove sysctl context\n");
517 	}
518 
519 	disk_destroy(softc->disk);
520 	free(softc, M_DEVBUF);
521 	cam_periph_lock(periph);
522 }
523 
524 static void
525 ndaasync(void *callback_arg, u_int32_t code,
526 	struct cam_path *path, void *arg)
527 {
528 	struct cam_periph *periph;
529 
530 	periph = (struct cam_periph *)callback_arg;
531 	switch (code) {
532 	case AC_FOUND_DEVICE:
533 	{
534 		struct ccb_getdev *cgd;
535 		cam_status status;
536 
537 		cgd = (struct ccb_getdev *)arg;
538 		if (cgd == NULL)
539 			break;
540 
541 		if (cgd->protocol != PROTO_NVME)
542 			break;
543 
544 		/*
545 		 * Allocate a peripheral instance for
546 		 * this device and start the probe
547 		 * process.
548 		 */
549 		status = cam_periph_alloc(ndaregister, ndaoninvalidate,
550 					  ndacleanup, ndastart,
551 					  "nda", CAM_PERIPH_BIO,
552 					  path, ndaasync,
553 					  AC_FOUND_DEVICE, cgd);
554 
555 		if (status != CAM_REQ_CMP
556 		 && status != CAM_REQ_INPROG)
557 			printf("ndaasync: Unable to attach to new device "
558 				"due to status 0x%x\n", status);
559 		break;
560 	}
561 	case AC_ADVINFO_CHANGED:
562 	{
563 		uintptr_t buftype;
564 
565 		buftype = (uintptr_t)arg;
566 		if (buftype == CDAI_TYPE_PHYS_PATH) {
567 			struct nda_softc *softc;
568 
569 			softc = periph->softc;
570 			disk_attr_changed(softc->disk, "GEOM::physpath",
571 					  M_NOWAIT);
572 		}
573 		break;
574 	}
575 	case AC_LOST_DEVICE:
576 	default:
577 		cam_periph_async(periph, code, path, arg);
578 		break;
579 	}
580 }
581 
582 static void
583 ndasysctlinit(void *context, int pending)
584 {
585 	struct cam_periph *periph;
586 	struct nda_softc *softc;
587 	char tmpstr[80], tmpstr2[80];
588 
589 	periph = (struct cam_periph *)context;
590 
591 	/* periph was held for us when this task was enqueued */
592 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
593 		cam_periph_release(periph);
594 		return;
595 	}
596 
597 	softc = (struct nda_softc *)periph->softc;
598 	snprintf(tmpstr, sizeof(tmpstr), "CAM NDA unit %d", periph->unit_number);
599 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
600 
601 	sysctl_ctx_init(&softc->sysctl_ctx);
602 	softc->flags |= NDA_FLAG_SCTX_INIT;
603 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
604 		SYSCTL_STATIC_CHILDREN(_kern_cam_nda), OID_AUTO, tmpstr2,
605 		CTLFLAG_RD, 0, tmpstr, "device_index");
606 	if (softc->sysctl_tree == NULL) {
607 		printf("ndasysctlinit: unable to allocate sysctl tree\n");
608 		cam_periph_release(periph);
609 		return;
610 	}
611 
612 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
613 		OID_AUTO, "unmapped_io", CTLFLAG_RD | CTLFLAG_MPSAFE,
614 		&softc->unmappedio, 0, "Unmapped I/O leaf");
615 
616 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
617 		       SYSCTL_CHILDREN(softc->sysctl_tree),
618 		       OID_AUTO,
619 		       "rotating",
620 		       CTLFLAG_RD | CTLFLAG_MPSAFE,
621 		       &nda_rotating_media,
622 		       0,
623 		       "Rotating media");
624 
625 #ifdef CAM_IO_STATS
626 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
627 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
628 		CTLFLAG_RD, 0, "Statistics");
629 	if (softc->sysctl_stats_tree == NULL) {
630 		printf("ndasysctlinit: unable to allocate sysctl tree for stats\n");
631 		cam_periph_release(periph);
632 		return;
633 	}
634 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
635 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
636 		OID_AUTO, "timeouts", CTLFLAG_RD | CTLFLAG_MPSAFE,
637 		&softc->timeouts, 0,
638 		"Device timeouts reported by the SIM");
639 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
640 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
641 		OID_AUTO, "errors", CTLFLAG_RD | CTLFLAG_MPSAFE,
642 		&softc->errors, 0,
643 		"Transport errors reported by the SIM.");
644 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
645 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
646 		OID_AUTO, "pack_invalidations", CTLFLAG_RD | CTLFLAG_MPSAFE,
647 		&softc->invalidations, 0,
648 		"Device pack invalidations.");
649 #endif
650 
651 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
652 	    softc->sysctl_tree);
653 
654 	cam_periph_release(periph);
655 }
656 
657 static int
658 ndagetattr(struct bio *bp)
659 {
660 	int ret;
661 	struct cam_periph *periph;
662 
663 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
664 	cam_periph_lock(periph);
665 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
666 	    periph->path);
667 	cam_periph_unlock(periph);
668 	if (ret == 0)
669 		bp->bio_completed = bp->bio_length;
670 	return ret;
671 }
672 
673 static cam_status
674 ndaregister(struct cam_periph *periph, void *arg)
675 {
676 	struct nda_softc *softc;
677 	struct disk *disk;
678 	struct ccb_pathinq cpi;
679 	const struct nvme_namespace_data *nsd;
680 	const struct nvme_controller_data *cd;
681 	char   announce_buf[80];
682 	u_int maxio;
683 	int quirks;
684 
685 	nsd = nvme_get_identify_ns(periph);
686 	cd = nvme_get_identify_cntrl(periph);
687 
688 	softc = (struct nda_softc *)malloc(sizeof(*softc), M_DEVBUF,
689 	    M_NOWAIT | M_ZERO);
690 
691 	if (softc == NULL) {
692 		printf("ndaregister: Unable to probe new device. "
693 		    "Unable to allocate softc\n");
694 		return(CAM_REQ_CMP_ERR);
695 	}
696 
697 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
698 		printf("ndaregister: Unable to probe new device. "
699 		       "Unable to allocate iosched memory\n");
700 		return(CAM_REQ_CMP_ERR);
701 	}
702 
703 	/* ident_data parsing */
704 
705 	periph->softc = softc;
706 
707 	softc->quirks = NDA_Q_NONE;
708 
709 	xpt_path_inq(&cpi, periph->path);
710 
711 	TASK_INIT(&softc->sysctl_task, 0, ndasysctlinit, periph);
712 
713 	/*
714 	 * The name space ID is the lun, save it for later I/O
715 	 */
716 	softc->nsid = (uint32_t)xpt_path_lun_id(periph->path);
717 
718 	/*
719 	 * Register this media as a disk
720 	 */
721 	(void)cam_periph_hold(periph, PRIBIO);
722 	cam_periph_unlock(periph);
723 	snprintf(announce_buf, sizeof(announce_buf),
724 	    "kern.cam.nda.%d.quirks", periph->unit_number);
725 	quirks = softc->quirks;
726 	TUNABLE_INT_FETCH(announce_buf, &quirks);
727 	softc->quirks = quirks;
728 	cam_iosched_set_sort_queue(softc->cam_iosched, 0);
729 	softc->disk = disk = disk_alloc();
730 	strlcpy(softc->disk->d_descr, cd->mn,
731 	    MIN(sizeof(softc->disk->d_descr), sizeof(cd->mn)));
732 	strlcpy(softc->disk->d_ident, cd->sn,
733 	    MIN(sizeof(softc->disk->d_ident), sizeof(cd->sn)));
734 	disk->d_rotation_rate = DISK_RR_NON_ROTATING;
735 	disk->d_open = ndaopen;
736 	disk->d_close = ndaclose;
737 	disk->d_strategy = ndastrategy;
738 	disk->d_getattr = ndagetattr;
739 	disk->d_dump = ndadump;
740 	disk->d_gone = ndadiskgonecb;
741 	disk->d_name = "nda";
742 	disk->d_drv1 = periph;
743 	disk->d_unit = periph->unit_number;
744 	maxio = cpi.maxio;		/* Honor max I/O size of SIM */
745 	if (maxio == 0)
746 		maxio = DFLTPHYS;	/* traditional default */
747 	else if (maxio > MAXPHYS)
748 		maxio = MAXPHYS;	/* for safety */
749 	disk->d_maxsize = maxio;
750 	disk->d_sectorsize = 1 << nsd->lbaf[nsd->flbas.format].lbads;
751 	disk->d_mediasize = (off_t)(disk->d_sectorsize * nsd->nsze);
752 	disk->d_delmaxsize = disk->d_mediasize;
753 	disk->d_flags = DISKFLAG_DIRECT_COMPLETION;
754 //	if (cd->oncs.dsm) // XXX broken?
755 		disk->d_flags |= DISKFLAG_CANDELETE;
756 	if (cd->vwc.present)
757 		disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
758 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0) {
759 		disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
760 		softc->unmappedio = 1;
761 	}
762 	/*
763 	 * d_ident and d_descr are both far bigger than the length of either
764 	 *  the serial or model number strings.
765 	 */
766 	nvme_strvis(disk->d_descr, cd->mn,
767 	    sizeof(disk->d_descr), NVME_MODEL_NUMBER_LENGTH);
768 	nvme_strvis(disk->d_ident, cd->sn,
769 	    sizeof(disk->d_ident), NVME_SERIAL_NUMBER_LENGTH);
770 	disk->d_hba_vendor = cpi.hba_vendor;
771 	disk->d_hba_device = cpi.hba_device;
772 	disk->d_hba_subvendor = cpi.hba_subvendor;
773 	disk->d_hba_subdevice = cpi.hba_subdevice;
774 	disk->d_stripesize = disk->d_sectorsize;
775 	disk->d_stripeoffset = 0;
776 	disk->d_devstat = devstat_new_entry(periph->periph_name,
777 	    periph->unit_number, disk->d_sectorsize,
778 	    DEVSTAT_ALL_SUPPORTED,
779 	    DEVSTAT_TYPE_DIRECT | XPORT_DEVSTAT_TYPE(cpi.transport),
780 	    DEVSTAT_PRIORITY_DISK);
781 	/*
782 	 * Add alias for older nvd drives to ease transition.
783 	 */
784 	/* disk_add_alias(disk, "nvd"); Have reports of this causing problems */
785 
786 	/*
787 	 * Acquire a reference to the periph before we register with GEOM.
788 	 * We'll release this reference once GEOM calls us back (via
789 	 * ndadiskgonecb()) telling us that our provider has been freed.
790 	 */
791 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
792 		xpt_print(periph->path, "%s: lost periph during "
793 			  "registration!\n", __func__);
794 		cam_periph_lock(periph);
795 		return (CAM_REQ_CMP_ERR);
796 	}
797 	disk_create(softc->disk, DISK_VERSION);
798 	cam_periph_lock(periph);
799 	cam_periph_unhold(periph);
800 
801 	snprintf(announce_buf, sizeof(announce_buf),
802 		"%juMB (%ju %u byte sectors)",
803 	    (uintmax_t)((uintmax_t)disk->d_mediasize / (1024*1024)),
804 		(uintmax_t)disk->d_mediasize / disk->d_sectorsize,
805 		disk->d_sectorsize);
806 	xpt_announce_periph(periph, announce_buf);
807 	xpt_announce_quirks(periph, softc->quirks, NDA_Q_BIT_STRING);
808 
809 	/*
810 	 * Create our sysctl variables, now that we know
811 	 * we have successfully attached.
812 	 */
813 	if (cam_periph_acquire(periph) == CAM_REQ_CMP)
814 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
815 
816 	/*
817 	 * Register for device going away and info about the drive
818 	 * changing (though with NVMe, it can't)
819 	 */
820 	xpt_register_async(AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
821 	    ndaasync, periph, periph->path);
822 
823 	softc->state = NDA_STATE_NORMAL;
824 	return(CAM_REQ_CMP);
825 }
826 
827 static void
828 ndastart(struct cam_periph *periph, union ccb *start_ccb)
829 {
830 	struct nda_softc *softc = (struct nda_softc *)periph->softc;
831 	struct ccb_nvmeio *nvmeio = &start_ccb->nvmeio;
832 
833 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart\n"));
834 
835 	switch (softc->state) {
836 	case NDA_STATE_NORMAL:
837 	{
838 		struct bio *bp;
839 
840 		bp = cam_iosched_next_bio(softc->cam_iosched);
841 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart: bio %p\n", bp));
842 		if (bp == NULL) {
843 			xpt_release_ccb(start_ccb);
844 			break;
845 		}
846 
847 		switch (bp->bio_cmd) {
848 		case BIO_WRITE:
849 			softc->flags |= NDA_FLAG_DIRTY;
850 			/* FALLTHROUGH */
851 		case BIO_READ:
852 		{
853 #ifdef NDA_TEST_FAILURE
854 			int fail = 0;
855 
856 			/*
857 			 * Support the failure ioctls.  If the command is a
858 			 * read, and there are pending forced read errors, or
859 			 * if a write and pending write errors, then fail this
860 			 * operation with EIO.  This is useful for testing
861 			 * purposes.  Also, support having every Nth read fail.
862 			 *
863 			 * This is a rather blunt tool.
864 			 */
865 			if (bp->bio_cmd == BIO_READ) {
866 				if (softc->force_read_error) {
867 					softc->force_read_error--;
868 					fail = 1;
869 				}
870 				if (softc->periodic_read_error > 0) {
871 					if (++softc->periodic_read_count >=
872 					    softc->periodic_read_error) {
873 						softc->periodic_read_count = 0;
874 						fail = 1;
875 					}
876 				}
877 			} else {
878 				if (softc->force_write_error) {
879 					softc->force_write_error--;
880 					fail = 1;
881 				}
882 			}
883 			if (fail) {
884 				biofinish(bp, NULL, EIO);
885 				xpt_release_ccb(start_ccb);
886 				ndaschedule(periph);
887 				return;
888 			}
889 #endif
890 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
891 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
892 			    PAGE_SIZE == bp->bio_ma_n,
893 			    ("Short bio %p", bp));
894 			nda_nvme_rw_bio(softc, &start_ccb->nvmeio, bp, bp->bio_cmd == BIO_READ ?
895 			    NVME_OPC_READ : NVME_OPC_WRITE);
896 			break;
897 		}
898 		case BIO_DELETE:
899 		{
900 			struct nvme_dsm_range *dsm_range;
901 
902 			dsm_range =
903 			    malloc(sizeof(*dsm_range), M_NVMEDA, M_ZERO | M_WAITOK);
904 			dsm_range->length =
905 			    bp->bio_bcount / softc->disk->d_sectorsize;
906 			dsm_range->starting_lba =
907 			    bp->bio_offset / softc->disk->d_sectorsize;
908 			bp->bio_driver2 = dsm_range;
909 			nda_nvme_trim(softc, &start_ccb->nvmeio, dsm_range, 1);
910 			start_ccb->ccb_h.ccb_state = NDA_CCB_TRIM;
911 			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
912 			/*
913 			 * Note: We can have multiple TRIMs in flight, so we don't call
914 			 * cam_iosched_submit_trim(softc->cam_iosched);
915 			 * since that forces the I/O scheduler to only schedule one at a time.
916 			 * On NVMe drives, this is a performance disaster.
917 			 */
918 			goto out;
919 		}
920 		case BIO_FLUSH:
921 			nda_nvme_flush(softc, nvmeio);
922 			break;
923 		}
924 		start_ccb->ccb_h.ccb_state = NDA_CCB_BUFFER_IO;
925 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
926 out:
927 		start_ccb->ccb_h.ccb_bp = bp;
928 		softc->outstanding_cmds++;
929 		softc->refcount++;
930 		cam_periph_unlock(periph);
931 		xpt_action(start_ccb);
932 		cam_periph_lock(periph);
933 		softc->refcount--;
934 
935 		/* May have more work to do, so ensure we stay scheduled */
936 		ndaschedule(periph);
937 		break;
938 		}
939 	}
940 }
941 
942 static void
943 ndadone(struct cam_periph *periph, union ccb *done_ccb)
944 {
945 	struct nda_softc *softc;
946 	struct ccb_nvmeio *nvmeio = &done_ccb->nvmeio;
947 	struct cam_path *path;
948 	int state;
949 
950 	softc = (struct nda_softc *)periph->softc;
951 	path = done_ccb->ccb_h.path;
952 
953 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("ndadone\n"));
954 
955 	state = nvmeio->ccb_h.ccb_state & NDA_CCB_TYPE_MASK;
956 	switch (state) {
957 	case NDA_CCB_BUFFER_IO:
958 	case NDA_CCB_TRIM:
959 	{
960 		struct bio *bp;
961 		int error;
962 
963 		cam_periph_lock(periph);
964 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
965 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
966 			error = ndaerror(done_ccb, 0, 0);
967 			if (error == ERESTART) {
968 				/* A retry was scheduled, so just return. */
969 				cam_periph_unlock(periph);
970 				return;
971 			}
972 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
973 				cam_release_devq(path,
974 						 /*relsim_flags*/0,
975 						 /*reduction*/0,
976 						 /*timeout*/0,
977 						 /*getcount_only*/0);
978 		} else {
979 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
980 				panic("REQ_CMP with QFRZN");
981 			error = 0;
982 		}
983 		bp->bio_error = error;
984 		if (error != 0) {
985 			bp->bio_resid = bp->bio_bcount;
986 			bp->bio_flags |= BIO_ERROR;
987 		} else {
988 			bp->bio_resid = 0;
989 		}
990 		if (state == NDA_CCB_TRIM)
991 			free(bp->bio_driver2, M_NVMEDA);
992 		softc->outstanding_cmds--;
993 
994 		/*
995 		 * We need to call cam_iosched before we call biodone so that we
996 		 * don't measure any activity that happens in the completion
997 		 * routine, which in the case of sendfile can be quite
998 		 * extensive.
999 		 */
1000 		cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
1001 		xpt_release_ccb(done_ccb);
1002 		if (state == NDA_CCB_TRIM) {
1003 #ifdef notyet
1004 			TAILQ_HEAD(, bio) queue;
1005 			struct bio *bp1;
1006 
1007 			TAILQ_INIT(&queue);
1008 			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
1009 #endif
1010 			/*
1011 			 * Since we can have multiple trims in flight, we don't
1012 			 * need to call this here.
1013 			 * cam_iosched_trim_done(softc->cam_iosched);
1014 			 */
1015 			ndaschedule(periph);
1016 			cam_periph_unlock(periph);
1017 #ifdef notyet
1018 /* Not yet collapsing several BIO_DELETE requests into one TRIM */
1019 			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
1020 				TAILQ_REMOVE(&queue, bp1, bio_queue);
1021 				bp1->bio_error = error;
1022 				if (error != 0) {
1023 					bp1->bio_flags |= BIO_ERROR;
1024 					bp1->bio_resid = bp1->bio_bcount;
1025 				} else
1026 					bp1->bio_resid = 0;
1027 				biodone(bp1);
1028 			}
1029 #else
1030 			biodone(bp);
1031 #endif
1032 		} else {
1033 			ndaschedule(periph);
1034 			cam_periph_unlock(periph);
1035 			biodone(bp);
1036 		}
1037 		return;
1038 	}
1039 	case NDA_CCB_DUMP:
1040 		/* No-op.  We're polling */
1041 		return;
1042 	default:
1043 		break;
1044 	}
1045 	xpt_release_ccb(done_ccb);
1046 }
1047 
1048 static int
1049 ndaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1050 {
1051 	struct nda_softc *softc;
1052 	struct cam_periph *periph;
1053 
1054 	periph = xpt_path_periph(ccb->ccb_h.path);
1055 	softc = (struct nda_softc *)periph->softc;
1056 
1057 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1058 	case CAM_CMD_TIMEOUT:
1059 #ifdef CAM_IO_STATS
1060 		softc->timeouts++;
1061 #endif
1062 		break;
1063 	case CAM_REQ_ABORTED:
1064 	case CAM_REQ_CMP_ERR:
1065 	case CAM_REQ_TERMIO:
1066 	case CAM_UNREC_HBA_ERROR:
1067 	case CAM_DATA_RUN_ERR:
1068 	case CAM_ATA_STATUS_ERROR:
1069 #ifdef CAM_IO_STATS
1070 		softc->errors++;
1071 #endif
1072 		break;
1073 	default:
1074 		break;
1075 	}
1076 
1077 	return(cam_periph_error(ccb, cam_flags, sense_flags));
1078 }
1079 
1080 /*
1081  * Step through all NDA peripheral drivers, and if the device is still open,
1082  * sync the disk cache to physical media.
1083  */
1084 static void
1085 ndaflush(void)
1086 {
1087 	struct cam_periph *periph;
1088 	struct nda_softc *softc;
1089 	union ccb *ccb;
1090 	int error;
1091 
1092 	CAM_PERIPH_FOREACH(periph, &ndadriver) {
1093 		softc = (struct nda_softc *)periph->softc;
1094 		if (SCHEDULER_STOPPED()) {
1095 			/* If we paniced with the lock held, do not recurse. */
1096 			if (!cam_periph_owned(periph) &&
1097 			    (softc->flags & NDA_FLAG_OPEN)) {
1098 				ndadump(softc->disk, NULL, 0, 0, 0);
1099 			}
1100 			continue;
1101 		}
1102 		cam_periph_lock(periph);
1103 		/*
1104 		 * We only sync the cache if the drive is still open, and
1105 		 * if the drive is capable of it..
1106 		 */
1107 		if ((softc->flags & NDA_FLAG_OPEN) == 0) {
1108 			cam_periph_unlock(periph);
1109 			continue;
1110 		}
1111 
1112 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1113 		nda_nvme_flush(softc, &ccb->nvmeio);
1114 		error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
1115 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
1116 		    softc->disk->d_devstat);
1117 		if (error != 0)
1118 			xpt_print(periph->path, "Synchronize cache failed\n");
1119 		xpt_release_ccb(ccb);
1120 		cam_periph_unlock(periph);
1121 	}
1122 }
1123 
1124 static void
1125 ndashutdown(void *arg, int howto)
1126 {
1127 
1128 	ndaflush();
1129 }
1130 
1131 static void
1132 ndasuspend(void *arg)
1133 {
1134 
1135 	ndaflush();
1136 }
1137