xref: /freebsd/sys/cam/nvme/nvme_da.c (revision 2b833162)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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  * 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 AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * 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_STATUS_MASK) == CAM_REQ_CMP ?
445 		    0 : EIO;
446 out:
447 		cam_periph_lock(periph);
448 		xpt_release_ccb(ccb);
449 		cam_periph_unlock(periph);
450 		return (error);
451 	}
452 	default:
453 		break;
454 	}
455 	return (ENOTTY);
456 }
457 
458 /*
459  * Actually translate the requested transfer into one the physical driver
460  * can understand.  The transfer is described by a buf and will include
461  * only one physical transfer.
462  */
463 static void
464 ndastrategy(struct bio *bp)
465 {
466 	struct cam_periph *periph;
467 	struct nda_softc *softc;
468 
469 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
470 	softc = (struct nda_softc *)periph->softc;
471 
472 	cam_periph_lock(periph);
473 
474 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastrategy(%p)\n", bp));
475 
476 	/*
477 	 * If the device has been made invalid, error out
478 	 */
479 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
480 		cam_periph_unlock(periph);
481 		biofinish(bp, NULL, ENXIO);
482 		return;
483 	}
484 
485 	if (bp->bio_cmd == BIO_DELETE)
486 		softc->deletes++;
487 
488 	/*
489 	 * Place it in the queue of disk activities for this disk
490 	 */
491 	cam_iosched_queue_work(softc->cam_iosched, bp);
492 
493 	/*
494 	 * Schedule ourselves for performing the work.
495 	 */
496 	ndaschedule(periph);
497 	cam_periph_unlock(periph);
498 
499 	return;
500 }
501 
502 static int
503 ndadump(void *arg, void *virtual, off_t offset, size_t length)
504 {
505 	struct	    cam_periph *periph;
506 	struct	    nda_softc *softc;
507 	u_int	    secsize;
508 	struct ccb_nvmeio nvmeio;
509 	struct	    disk *dp;
510 	uint64_t    lba;
511 	uint32_t    count;
512 	int	    error = 0;
513 
514 	dp = arg;
515 	periph = dp->d_drv1;
516 	softc = (struct nda_softc *)periph->softc;
517 	secsize = softc->disk->d_sectorsize;
518 	lba = offset / secsize;
519 	count = length / secsize;
520 
521 	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
522 		return (ENXIO);
523 
524 	/* xpt_get_ccb returns a zero'd allocation for the ccb, mimic that here */
525 	memset(&nvmeio, 0, sizeof(nvmeio));
526 	if (length > 0) {
527 		xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
528 		nvmeio.ccb_state = NDA_CCB_DUMP;
529 		nda_nvme_write(softc, &nvmeio, virtual, lba, length, count);
530 		error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
531 		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
532 		if (error != 0)
533 			printf("Aborting dump due to I/O error %d.\n", error);
534 
535 		return (error);
536 	}
537 
538 	/* Flush */
539 	xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
540 
541 	nvmeio.ccb_state = NDA_CCB_DUMP;
542 	nda_nvme_flush(softc, &nvmeio);
543 	error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
544 	    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
545 	if (error != 0)
546 		xpt_print(periph->path, "flush cmd failed\n");
547 	return (error);
548 }
549 
550 static void
551 ndainit(void)
552 {
553 	cam_status status;
554 
555 	/*
556 	 * Install a global async callback.  This callback will
557 	 * receive async callbacks like "new device found".
558 	 */
559 	status = xpt_register_async(AC_FOUND_DEVICE, ndaasync, NULL, NULL);
560 
561 	if (status != CAM_REQ_CMP) {
562 		printf("nda: Failed to attach master async callback "
563 		       "due to status 0x%x!\n", status);
564 	} else if (nda_send_ordered) {
565 		/* Register our event handlers */
566 		if ((EVENTHANDLER_REGISTER(power_suspend, ndasuspend,
567 					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
568 		    printf("ndainit: power event registration failed!\n");
569 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, ndashutdown,
570 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
571 		    printf("ndainit: shutdown event registration failed!\n");
572 	}
573 }
574 
575 /*
576  * Callback from GEOM, called when it has finished cleaning up its
577  * resources.
578  */
579 static void
580 ndadiskgonecb(struct disk *dp)
581 {
582 	struct cam_periph *periph;
583 
584 	periph = (struct cam_periph *)dp->d_drv1;
585 
586 	cam_periph_release(periph);
587 }
588 
589 static void
590 ndaoninvalidate(struct cam_periph *periph)
591 {
592 	struct nda_softc *softc;
593 
594 	softc = (struct nda_softc *)periph->softc;
595 
596 	/*
597 	 * De-register any async callbacks.
598 	 */
599 	xpt_register_async(0, ndaasync, periph, periph->path);
600 #ifdef CAM_IO_STATS
601 	softc->invalidations++;
602 #endif
603 
604 	/*
605 	 * Return all queued I/O with ENXIO. Transactions may be queued up here
606 	 * for retry (since we are called while there's other transactions
607 	 * pending). Any requests in the hardware will drain before ndacleanup
608 	 * is called.
609 	 */
610 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
611 
612 	/*
613 	 * Tell GEOM that we've gone away, we'll get a callback when it is
614 	 * done cleaning up its resources.
615 	 */
616 	disk_gone(softc->disk);
617 }
618 
619 static void
620 ndacleanup(struct cam_periph *periph)
621 {
622 	struct nda_softc *softc;
623 
624 	softc = (struct nda_softc *)periph->softc;
625 
626 	cam_periph_unlock(periph);
627 
628 	cam_iosched_fini(softc->cam_iosched);
629 
630 	/*
631 	 * If we can't free the sysctl tree, oh well...
632 	 */
633 	if ((softc->flags & NDA_FLAG_SCTX_INIT) != 0) {
634 #ifdef CAM_IO_STATS
635 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
636 			xpt_print(periph->path,
637 			    "can't remove sysctl stats context\n");
638 #endif
639 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
640 			xpt_print(periph->path,
641 			    "can't remove sysctl context\n");
642 	}
643 
644 	disk_destroy(softc->disk);
645 	free(softc, M_DEVBUF);
646 	cam_periph_lock(periph);
647 }
648 
649 static void
650 ndaasync(void *callback_arg, u_int32_t code,
651 	struct cam_path *path, void *arg)
652 {
653 	struct cam_periph *periph;
654 
655 	periph = (struct cam_periph *)callback_arg;
656 	switch (code) {
657 	case AC_FOUND_DEVICE:
658 	{
659 		struct ccb_getdev *cgd;
660 		cam_status status;
661 
662 		cgd = (struct ccb_getdev *)arg;
663 		if (cgd == NULL)
664 			break;
665 
666 		if (cgd->protocol != PROTO_NVME)
667 			break;
668 
669 		/*
670 		 * Allocate a peripheral instance for
671 		 * this device and start the probe
672 		 * process.
673 		 */
674 		status = cam_periph_alloc(ndaregister, ndaoninvalidate,
675 					  ndacleanup, ndastart,
676 					  "nda", CAM_PERIPH_BIO,
677 					  path, ndaasync,
678 					  AC_FOUND_DEVICE, cgd);
679 
680 		if (status != CAM_REQ_CMP
681 		 && status != CAM_REQ_INPROG)
682 			printf("ndaasync: Unable to attach to new device "
683 				"due to status 0x%x\n", status);
684 		break;
685 	}
686 	case AC_ADVINFO_CHANGED:
687 	{
688 		uintptr_t buftype;
689 
690 		buftype = (uintptr_t)arg;
691 		if (buftype == CDAI_TYPE_PHYS_PATH) {
692 			struct nda_softc *softc;
693 
694 			softc = periph->softc;
695 			disk_attr_changed(softc->disk, "GEOM::physpath",
696 					  M_NOWAIT);
697 		}
698 		break;
699 	}
700 	case AC_LOST_DEVICE:
701 	default:
702 		break;
703 	}
704 	cam_periph_async(periph, code, path, arg);
705 }
706 
707 static void
708 ndasysctlinit(void *context, int pending)
709 {
710 	struct cam_periph *periph;
711 	struct nda_softc *softc;
712 	char tmpstr[32], tmpstr2[16];
713 
714 	periph = (struct cam_periph *)context;
715 
716 	/* periph was held for us when this task was enqueued */
717 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
718 		cam_periph_release(periph);
719 		return;
720 	}
721 
722 	softc = (struct nda_softc *)periph->softc;
723 	snprintf(tmpstr, sizeof(tmpstr), "CAM NDA unit %d", periph->unit_number);
724 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
725 
726 	sysctl_ctx_init(&softc->sysctl_ctx);
727 	softc->flags |= NDA_FLAG_SCTX_INIT;
728 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
729 		SYSCTL_STATIC_CHILDREN(_kern_cam_nda), OID_AUTO, tmpstr2,
730 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
731 	if (softc->sysctl_tree == NULL) {
732 		printf("ndasysctlinit: unable to allocate sysctl tree\n");
733 		cam_periph_release(periph);
734 		return;
735 	}
736 
737 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
738 	    OID_AUTO, "unmapped_io", CTLFLAG_RD,
739 	    &softc->unmappedio, 0, "Unmapped I/O leaf");
740 
741 	SYSCTL_ADD_QUAD(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
742 	    OID_AUTO, "deletes", CTLFLAG_RD,
743 	    &softc->deletes, "Number of BIO_DELETE requests");
744 
745 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
746 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
747 		"trim_count", CTLFLAG_RD, &softc->trim_count,
748 		"Total number of unmap/dsm commands sent");
749 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
750 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
751 		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
752 		"Total number of ranges in unmap/dsm commands");
753 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
754 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
755 		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
756 		"Total lbas in the unmap/dsm commands sent");
757 
758 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
759 	    OID_AUTO, "rotating", CTLFLAG_RD, &nda_rotating_media, 1,
760 	    "Rotating media");
761 
762 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
763 	    OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
764 	    softc, 0, ndaflagssysctl, "A",
765 	    "Flags for drive");
766 
767 #ifdef CAM_IO_STATS
768 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
769 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
770 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
771 	if (softc->sysctl_stats_tree == NULL) {
772 		printf("ndasysctlinit: unable to allocate sysctl tree for stats\n");
773 		cam_periph_release(periph);
774 		return;
775 	}
776 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
777 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
778 		OID_AUTO, "timeouts", CTLFLAG_RD,
779 		&softc->timeouts, 0,
780 		"Device timeouts reported by the SIM");
781 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
782 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
783 		OID_AUTO, "errors", CTLFLAG_RD,
784 		&softc->errors, 0,
785 		"Transport errors reported by the SIM.");
786 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
787 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
788 		OID_AUTO, "pack_invalidations", CTLFLAG_RD,
789 		&softc->invalidations, 0,
790 		"Device pack invalidations.");
791 #endif
792 
793 #ifdef CAM_TEST_FAILURE
794 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
795 		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
796 		periph, 0, cam_periph_invalidate_sysctl, "I",
797 		"Write 1 to invalidate the drive immediately");
798 #endif
799 
800 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
801 	    softc->sysctl_tree);
802 
803 	cam_periph_release(periph);
804 }
805 
806 static int
807 ndaflagssysctl(SYSCTL_HANDLER_ARGS)
808 {
809 	struct sbuf sbuf;
810 	struct nda_softc *softc = arg1;
811 	int error;
812 
813 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
814 	if (softc->flags != 0)
815 		sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, NDA_FLAG_STRING);
816 	else
817 		sbuf_printf(&sbuf, "0");
818 	error = sbuf_finish(&sbuf);
819 	sbuf_delete(&sbuf);
820 
821 	return (error);
822 }
823 
824 static int
825 ndagetattr(struct bio *bp)
826 {
827 	int ret;
828 	struct cam_periph *periph;
829 
830 	if (g_handleattr_int(bp, "GEOM::canspeedup", nda_enable_biospeedup))
831 		return (EJUSTRETURN);
832 
833 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
834 	cam_periph_lock(periph);
835 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
836 	    periph->path);
837 	cam_periph_unlock(periph);
838 	if (ret == 0)
839 		bp->bio_completed = bp->bio_length;
840 	return ret;
841 }
842 
843 static cam_status
844 ndaregister(struct cam_periph *periph, void *arg)
845 {
846 	struct nda_softc *softc;
847 	struct disk *disk;
848 	struct ccb_pathinq cpi;
849 	const struct nvme_namespace_data *nsd;
850 	const struct nvme_controller_data *cd;
851 	char   announce_buf[80];
852 	uint8_t flbas_fmt, lbads, vwc_present;
853 	u_int maxio;
854 	int quirks;
855 
856 	nsd = nvme_get_identify_ns(periph);
857 	cd = nvme_get_identify_cntrl(periph);
858 
859 	softc = (struct nda_softc *)malloc(sizeof(*softc), M_DEVBUF,
860 	    M_NOWAIT | M_ZERO);
861 
862 	if (softc == NULL) {
863 		printf("ndaregister: Unable to probe new device. "
864 		    "Unable to allocate softc\n");
865 		return(CAM_REQ_CMP_ERR);
866 	}
867 
868 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
869 		printf("ndaregister: Unable to probe new device. "
870 		       "Unable to allocate iosched memory\n");
871 		free(softc, M_DEVBUF);
872 		return(CAM_REQ_CMP_ERR);
873 	}
874 
875 	/* ident_data parsing */
876 
877 	periph->softc = softc;
878 	softc->quirks = NDA_Q_NONE;
879 	xpt_path_inq(&cpi, periph->path);
880 	TASK_INIT(&softc->sysctl_task, 0, ndasysctlinit, periph);
881 
882 	/*
883 	 * The name space ID is the lun, save it for later I/O
884 	 */
885 	softc->nsid = (uint32_t)xpt_path_lun_id(periph->path);
886 
887 	/*
888 	 * Register this media as a disk
889 	 */
890 	(void)cam_periph_acquire(periph);
891 	cam_periph_unlock(periph);
892 	snprintf(announce_buf, sizeof(announce_buf),
893 	    "kern.cam.nda.%d.quirks", periph->unit_number);
894 	quirks = softc->quirks;
895 	TUNABLE_INT_FETCH(announce_buf, &quirks);
896 	softc->quirks = quirks;
897 	cam_iosched_set_sort_queue(softc->cam_iosched, 0);
898 	softc->disk = disk = disk_alloc();
899 	disk->d_rotation_rate = DISK_RR_NON_ROTATING;
900 	disk->d_open = ndaopen;
901 	disk->d_close = ndaclose;
902 	disk->d_strategy = ndastrategy;
903 	disk->d_ioctl = ndaioctl;
904 	disk->d_getattr = ndagetattr;
905 	if (cam_sim_pollable(periph->sim))
906 		disk->d_dump = ndadump;
907 	disk->d_gone = ndadiskgonecb;
908 	disk->d_name = "nda";
909 	disk->d_drv1 = periph;
910 	disk->d_unit = periph->unit_number;
911 	maxio = cpi.maxio;		/* Honor max I/O size of SIM */
912 	if (maxio == 0)
913 		maxio = DFLTPHYS;	/* traditional default */
914 	else if (maxio > maxphys)
915 		maxio = maxphys;	/* for safety */
916 	disk->d_maxsize = maxio;
917 	flbas_fmt = (nsd->flbas >> NVME_NS_DATA_FLBAS_FORMAT_SHIFT) &
918 		NVME_NS_DATA_FLBAS_FORMAT_MASK;
919 	lbads = (nsd->lbaf[flbas_fmt] >> NVME_NS_DATA_LBAF_LBADS_SHIFT) &
920 		NVME_NS_DATA_LBAF_LBADS_MASK;
921 	disk->d_sectorsize = 1 << lbads;
922 	disk->d_mediasize = (off_t)(disk->d_sectorsize * nsd->nsze);
923 	disk->d_delmaxsize = disk->d_mediasize;
924 	disk->d_flags = DISKFLAG_DIRECT_COMPLETION;
925 	if (nvme_ctrlr_has_dataset_mgmt(cd))
926 		disk->d_flags |= DISKFLAG_CANDELETE;
927 	vwc_present = (cd->vwc >> NVME_CTRLR_DATA_VWC_PRESENT_SHIFT) &
928 		NVME_CTRLR_DATA_VWC_PRESENT_MASK;
929 	if (vwc_present)
930 		disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
931 	if ((cpi.hba_misc & PIM_UNMAPPED) != 0) {
932 		disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
933 		softc->unmappedio = 1;
934 	}
935 	/*
936 	 * d_ident and d_descr are both far bigger than the length of either
937 	 *  the serial or model number strings.
938 	 */
939 	cam_strvis_flag(disk->d_descr, cd->mn, NVME_MODEL_NUMBER_LENGTH,
940 	    sizeof(disk->d_descr), CAM_STRVIS_FLAG_NONASCII_SPC);
941 
942 	cam_strvis_flag(disk->d_ident, cd->sn, NVME_SERIAL_NUMBER_LENGTH,
943 	    sizeof(disk->d_ident), CAM_STRVIS_FLAG_NONASCII_SPC);
944 
945 	disk->d_hba_vendor = cpi.hba_vendor;
946 	disk->d_hba_device = cpi.hba_device;
947 	disk->d_hba_subvendor = cpi.hba_subvendor;
948 	disk->d_hba_subdevice = cpi.hba_subdevice;
949 	snprintf(disk->d_attachment, sizeof(disk->d_attachment),
950 	    "%s%d", cpi.dev_name, cpi.unit_number);
951 	if (((nsd->nsfeat >> NVME_NS_DATA_NSFEAT_NPVALID_SHIFT) &
952 	    NVME_NS_DATA_NSFEAT_NPVALID_MASK) != 0 && nsd->npwg != 0)
953 		disk->d_stripesize = ((nsd->npwg + 1) * disk->d_sectorsize);
954 	else
955 		disk->d_stripesize = nsd->noiob * disk->d_sectorsize;
956 	disk->d_stripeoffset = 0;
957 	disk->d_devstat = devstat_new_entry(periph->periph_name,
958 	    periph->unit_number, disk->d_sectorsize,
959 	    DEVSTAT_ALL_SUPPORTED,
960 	    DEVSTAT_TYPE_DIRECT | XPORT_DEVSTAT_TYPE(cpi.transport),
961 	    DEVSTAT_PRIORITY_DISK);
962 	/*
963 	 * Add alias for older nvd drives to ease transition.
964 	 */
965 	if (nda_nvd_compat)
966 		disk_add_alias(disk, "nvd");
967 
968 	cam_periph_lock(periph);
969 
970 	snprintf(announce_buf, sizeof(announce_buf),
971 		"%juMB (%ju %u byte sectors)",
972 	    (uintmax_t)((uintmax_t)disk->d_mediasize / (1024*1024)),
973 		(uintmax_t)disk->d_mediasize / disk->d_sectorsize,
974 		disk->d_sectorsize);
975 	xpt_announce_periph(periph, announce_buf);
976 	xpt_announce_quirks(periph, softc->quirks, NDA_Q_BIT_STRING);
977 
978 	/*
979 	 * Create our sysctl variables, now that we know
980 	 * we have successfully attached.
981 	 */
982 	if (cam_periph_acquire(periph) == 0)
983 		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
984 
985 	/*
986 	 * Register for device going away and info about the drive
987 	 * changing (though with NVMe, it can't)
988 	 */
989 	xpt_register_async(AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
990 	    ndaasync, periph, periph->path);
991 
992 	softc->state = NDA_STATE_NORMAL;
993 
994 	/*
995 	 * We'll release this reference once GEOM calls us back via
996 	 * ndadiskgonecb(), telling us that our provider has been freed.
997 	 */
998 	if (cam_periph_acquire(periph) == 0)
999 		disk_create(softc->disk, DISK_VERSION);
1000 
1001 	cam_periph_release_locked(periph);
1002 	return(CAM_REQ_CMP);
1003 }
1004 
1005 static void
1006 ndastart(struct cam_periph *periph, union ccb *start_ccb)
1007 {
1008 	struct nda_softc *softc = (struct nda_softc *)periph->softc;
1009 	struct ccb_nvmeio *nvmeio = &start_ccb->nvmeio;
1010 
1011 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart\n"));
1012 
1013 	switch (softc->state) {
1014 	case NDA_STATE_NORMAL:
1015 	{
1016 		struct bio *bp;
1017 
1018 		bp = cam_iosched_next_bio(softc->cam_iosched);
1019 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart: bio %p\n", bp));
1020 		if (bp == NULL) {
1021 			xpt_release_ccb(start_ccb);
1022 			break;
1023 		}
1024 
1025 		switch (bp->bio_cmd) {
1026 		case BIO_WRITE:
1027 			softc->flags |= NDA_FLAG_DIRTY;
1028 			/* FALLTHROUGH */
1029 		case BIO_READ:
1030 		{
1031 #ifdef CAM_TEST_FAILURE
1032 			int fail = 0;
1033 
1034 			/*
1035 			 * Support the failure ioctls.  If the command is a
1036 			 * read, and there are pending forced read errors, or
1037 			 * if a write and pending write errors, then fail this
1038 			 * operation with EIO.  This is useful for testing
1039 			 * purposes.  Also, support having every Nth read fail.
1040 			 *
1041 			 * This is a rather blunt tool.
1042 			 */
1043 			if (bp->bio_cmd == BIO_READ) {
1044 				if (softc->force_read_error) {
1045 					softc->force_read_error--;
1046 					fail = 1;
1047 				}
1048 				if (softc->periodic_read_error > 0) {
1049 					if (++softc->periodic_read_count >=
1050 					    softc->periodic_read_error) {
1051 						softc->periodic_read_count = 0;
1052 						fail = 1;
1053 					}
1054 				}
1055 			} else {
1056 				if (softc->force_write_error) {
1057 					softc->force_write_error--;
1058 					fail = 1;
1059 				}
1060 			}
1061 			if (fail) {
1062 				biofinish(bp, NULL, EIO);
1063 				xpt_release_ccb(start_ccb);
1064 				ndaschedule(periph);
1065 				return;
1066 			}
1067 #endif
1068 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
1069 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
1070 			    PAGE_SIZE == bp->bio_ma_n,
1071 			    ("Short bio %p", bp));
1072 			nda_nvme_rw_bio(softc, &start_ccb->nvmeio, bp, bp->bio_cmd == BIO_READ ?
1073 			    NVME_OPC_READ : NVME_OPC_WRITE);
1074 			break;
1075 		}
1076 		case BIO_DELETE:
1077 		{
1078 			struct nvme_dsm_range *dsm_range, *dsm_end;
1079 			struct nda_trim_request *trim;
1080 			struct bio *bp1;
1081 			int ents;
1082 			uint32_t totalcount = 0, ranges = 0;
1083 
1084 			trim = malloc(sizeof(*trim), M_NVMEDA, M_ZERO | M_NOWAIT);
1085 			if (trim == NULL) {
1086 				biofinish(bp, NULL, ENOMEM);
1087 				xpt_release_ccb(start_ccb);
1088 				ndaschedule(periph);
1089 				return;
1090 			}
1091 			TAILQ_INIT(&trim->bps);
1092 			bp1 = bp;
1093 			ents = min(nitems(trim->dsm), nda_max_trim_entries);
1094 			ents = max(ents, 1);
1095 			dsm_range = trim->dsm;
1096 			dsm_end = dsm_range + ents;
1097 			do {
1098 				TAILQ_INSERT_TAIL(&trim->bps, bp1, bio_queue);
1099 				dsm_range->length =
1100 				    htole32(bp1->bio_bcount / softc->disk->d_sectorsize);
1101 				dsm_range->starting_lba =
1102 				    htole64(bp1->bio_offset / softc->disk->d_sectorsize);
1103 				ranges++;
1104 				totalcount += dsm_range->length;
1105 				dsm_range++;
1106 				if (dsm_range >= dsm_end)
1107 					break;
1108 				bp1 = cam_iosched_next_trim(softc->cam_iosched);
1109 				/* XXX -- Could collapse adjacent ranges, but we don't for now */
1110 				/* XXX -- Could limit based on total payload size */
1111 			} while (bp1 != NULL);
1112 			start_ccb->ccb_trim = trim;
1113 			nda_nvme_trim(softc, &start_ccb->nvmeio, trim->dsm,
1114 			    dsm_range - trim->dsm);
1115 			start_ccb->ccb_state = NDA_CCB_TRIM;
1116 			softc->trim_count++;
1117 			softc->trim_ranges += ranges;
1118 			softc->trim_lbas += totalcount;
1119 			/*
1120 			 * Note: We can have multiple TRIMs in flight, so we don't call
1121 			 * cam_iosched_submit_trim(softc->cam_iosched);
1122 			 * since that forces the I/O scheduler to only schedule one at a time.
1123 			 * On NVMe drives, this is a performance disaster.
1124 			 */
1125 			goto out;
1126 		}
1127 		case BIO_FLUSH:
1128 			nda_nvme_flush(softc, nvmeio);
1129 			break;
1130 		default:
1131 			biofinish(bp, NULL, EOPNOTSUPP);
1132 			xpt_release_ccb(start_ccb);
1133 			ndaschedule(periph);
1134 			return;
1135 		}
1136 		start_ccb->ccb_state = NDA_CCB_BUFFER_IO;
1137 		start_ccb->ccb_bp = bp;
1138 out:
1139 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
1140 		softc->outstanding_cmds++;
1141 		softc->refcount++;			/* For submission only */
1142 		cam_periph_unlock(periph);
1143 		xpt_action(start_ccb);
1144 		cam_periph_lock(periph);
1145 		softc->refcount--;			/* Submission done */
1146 
1147 		/* May have more work to do, so ensure we stay scheduled */
1148 		ndaschedule(periph);
1149 		break;
1150 		}
1151 	}
1152 }
1153 
1154 static void
1155 ndadone(struct cam_periph *periph, union ccb *done_ccb)
1156 {
1157 	struct nda_softc *softc;
1158 	struct ccb_nvmeio *nvmeio = &done_ccb->nvmeio;
1159 	struct cam_path *path;
1160 	int state;
1161 
1162 	softc = (struct nda_softc *)periph->softc;
1163 	path = done_ccb->ccb_h.path;
1164 
1165 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("ndadone\n"));
1166 
1167 	state = nvmeio->ccb_state & NDA_CCB_TYPE_MASK;
1168 	switch (state) {
1169 	case NDA_CCB_BUFFER_IO:
1170 	case NDA_CCB_TRIM:
1171 	{
1172 		int error;
1173 
1174 		cam_periph_lock(periph);
1175 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1176 			error = ndaerror(done_ccb, 0, 0);
1177 			if (error == ERESTART) {
1178 				/* A retry was scheduled, so just return. */
1179 				cam_periph_unlock(periph);
1180 				return;
1181 			}
1182 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1183 				cam_release_devq(path,
1184 						 /*relsim_flags*/0,
1185 						 /*reduction*/0,
1186 						 /*timeout*/0,
1187 						 /*getcount_only*/0);
1188 		} else {
1189 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1190 				panic("REQ_CMP with QFRZN");
1191 			error = 0;
1192 		}
1193 		if (state == NDA_CCB_BUFFER_IO) {
1194 			struct bio *bp;
1195 
1196 			bp = (struct bio *)done_ccb->ccb_bp;
1197 			bp->bio_error = error;
1198 			if (error != 0) {
1199 				bp->bio_resid = bp->bio_bcount;
1200 				bp->bio_flags |= BIO_ERROR;
1201 			} else {
1202 				bp->bio_resid = 0;
1203 			}
1204 			softc->outstanding_cmds--;
1205 
1206 			/*
1207 			 * We need to call cam_iosched before we call biodone so that we
1208 			 * don't measure any activity that happens in the completion
1209 			 * routine, which in the case of sendfile can be quite
1210 			 * extensive.
1211 			 */
1212 			cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
1213 			xpt_release_ccb(done_ccb);
1214 			ndaschedule(periph);
1215 			cam_periph_unlock(periph);
1216 			biodone(bp);
1217 		} else { /* state == NDA_CCB_TRIM */
1218 			struct nda_trim_request *trim;
1219 			struct bio *bp1, *bp2;
1220 			TAILQ_HEAD(, bio) queue;
1221 
1222 			trim = nvmeio->ccb_trim;
1223 			TAILQ_INIT(&queue);
1224 			TAILQ_CONCAT(&queue, &trim->bps, bio_queue);
1225 			free(trim, M_NVMEDA);
1226 
1227 			/*
1228 			 * Since we can have multiple trims in flight, we don't
1229 			 * need to call this here.
1230 			 * cam_iosched_trim_done(softc->cam_iosched);
1231 			 */
1232 			/*
1233 			 * The the I/O scheduler that we're finishing the I/O
1234 			 * so we can keep book. The first one we pass in the CCB
1235 			 * which has the timing information. The rest we pass in NULL
1236 			 * so we can keep proper counts.
1237 			 */
1238 			bp1 = TAILQ_FIRST(&queue);
1239 			cam_iosched_bio_complete(softc->cam_iosched, bp1, done_ccb);
1240 			xpt_release_ccb(done_ccb);
1241 			softc->outstanding_cmds--;
1242 			ndaschedule(periph);
1243 			cam_periph_unlock(periph);
1244 			while ((bp2 = TAILQ_FIRST(&queue)) != NULL) {
1245 				TAILQ_REMOVE(&queue, bp2, bio_queue);
1246 				bp2->bio_error = error;
1247 				if (error != 0) {
1248 					bp2->bio_flags |= BIO_ERROR;
1249 					bp2->bio_resid = bp1->bio_bcount;
1250 				} else
1251 					bp2->bio_resid = 0;
1252 				if (bp1 != bp2)
1253 					cam_iosched_bio_complete(softc->cam_iosched, bp2, NULL);
1254 				biodone(bp2);
1255 			}
1256 		}
1257 		return;
1258 	}
1259 	case NDA_CCB_DUMP:
1260 		/* No-op.  We're polling */
1261 		return;
1262 	case NDA_CCB_PASS:
1263 		/* NVME_PASSTHROUGH_CMD runs this CCB and releases it */
1264 		return;
1265 	default:
1266 		break;
1267 	}
1268 	xpt_release_ccb(done_ccb);
1269 }
1270 
1271 static int
1272 ndaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1273 {
1274 #ifdef CAM_IO_STATS
1275 	struct nda_softc *softc;
1276 	struct cam_periph *periph;
1277 
1278 	periph = xpt_path_periph(ccb->ccb_h.path);
1279 	softc = (struct nda_softc *)periph->softc;
1280 #endif
1281 
1282 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1283 	case CAM_CMD_TIMEOUT:
1284 #ifdef CAM_IO_STATS
1285 		softc->timeouts++;
1286 #endif
1287 		break;
1288 	case CAM_REQ_ABORTED:
1289 	case CAM_REQ_CMP_ERR:
1290 	case CAM_REQ_TERMIO:
1291 	case CAM_UNREC_HBA_ERROR:
1292 	case CAM_DATA_RUN_ERR:
1293 	case CAM_ATA_STATUS_ERROR:
1294 #ifdef CAM_IO_STATS
1295 		softc->errors++;
1296 #endif
1297 		break;
1298 	default:
1299 		break;
1300 	}
1301 
1302 	return(cam_periph_error(ccb, cam_flags, sense_flags));
1303 }
1304 
1305 /*
1306  * Step through all NDA peripheral drivers, and if the device is still open,
1307  * sync the disk cache to physical media.
1308  */
1309 static void
1310 ndaflush(void)
1311 {
1312 	struct cam_periph *periph;
1313 	struct nda_softc *softc;
1314 	union ccb *ccb;
1315 	int error;
1316 
1317 	CAM_PERIPH_FOREACH(periph, &ndadriver) {
1318 		softc = (struct nda_softc *)periph->softc;
1319 
1320 		if (SCHEDULER_STOPPED()) {
1321 			/*
1322 			 * If we panicked with the lock held or the periph is not
1323 			 * open, do not recurse.  Otherwise, call ndadump since
1324 			 * that avoids the sleeping cam_periph_getccb does if no
1325 			 * CCBs are available.
1326 			 */
1327 			if (!cam_periph_owned(periph) &&
1328 			    (softc->flags & NDA_FLAG_OPEN)) {
1329 				ndadump(softc->disk, NULL, 0, 0);
1330 			}
1331 			continue;
1332 		}
1333 
1334 		/*
1335 		 * We only sync the cache if the drive is still open
1336 		 */
1337 		cam_periph_lock(periph);
1338 		if ((softc->flags & NDA_FLAG_OPEN) == 0) {
1339 			cam_periph_unlock(periph);
1340 			continue;
1341 		}
1342 
1343 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1344 		nda_nvme_flush(softc, &ccb->nvmeio);
1345 		error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
1346 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
1347 		    softc->disk->d_devstat);
1348 		if (error != 0)
1349 			xpt_print(periph->path, "Synchronize cache failed\n");
1350 		xpt_release_ccb(ccb);
1351 		cam_periph_unlock(periph);
1352 	}
1353 }
1354 
1355 static void
1356 ndashutdown(void *arg, int howto)
1357 {
1358 
1359 	if ((howto & RB_NOSYNC) != 0)
1360 		return;
1361 
1362 	ndaflush();
1363 }
1364 
1365 static void
1366 ndasuspend(void *arg)
1367 {
1368 
1369 	ndaflush();
1370 }
1371