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