xref: /freebsd/sys/cam/nvme/nvme_da.c (revision b13788e396c2b24f88697e7d4a74bab429ef4d0c)
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 SYSCTL_INT(_kern_cam_nda, OID_AUTO, max_trim, CTLFLAG_RDTUN,
189     &nda_max_trim_entries, NDA_MAX_TRIM_ENTRIES,
190     "Maximum number of BIO_DELETE to send down as a DSM TRIM.");
191 SYSCTL_INT(_kern_cam_nda, OID_AUTO, enable_biospeedup, CTLFLAG_RDTUN,
192     &nda_enable_biospeedup, 0, "Enable BIO_SPEEDUP processing");
193 
194 /*
195  * All NVMe media is non-rotational, so all nvme device instances
196  * share this to implement the sysctl.
197  */
198 static int nda_rotating_media = 0;
199 
200 static struct periph_driver ndadriver =
201 {
202 	ndainit, "nda",
203 	TAILQ_HEAD_INITIALIZER(ndadriver.units), /* generation */ 0
204 };
205 
206 PERIPHDRIVER_DECLARE(nda, ndadriver);
207 
208 static MALLOC_DEFINE(M_NVMEDA, "nvme_da", "nvme_da buffers");
209 
210 /*
211  * nice wrappers. Maybe these belong in nvme_all.c instead of
212  * here, but this is the only place that uses these. Should
213  * we ever grow another NVME periph, we should move them
214  * all there wholesale.
215  */
216 
217 static void
218 nda_nvme_flush(struct nda_softc *softc, struct ccb_nvmeio *nvmeio)
219 {
220 	cam_fill_nvmeio(nvmeio,
221 	    0,			/* retries */
222 	    ndadone,		/* cbfcnp */
223 	    CAM_DIR_NONE,	/* flags */
224 	    NULL,		/* data_ptr */
225 	    0,			/* dxfer_len */
226 	    nda_default_timeout * 1000); /* timeout 30s */
227 	nvme_ns_flush_cmd(&nvmeio->cmd, softc->nsid);
228 }
229 
230 static void
231 nda_nvme_trim(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
232     void *payload, uint32_t num_ranges)
233 {
234 	cam_fill_nvmeio(nvmeio,
235 	    0,			/* retries */
236 	    ndadone,		/* cbfcnp */
237 	    CAM_DIR_OUT,	/* flags */
238 	    payload,		/* data_ptr */
239 	    num_ranges * sizeof(struct nvme_dsm_range), /* dxfer_len */
240 	    nda_default_timeout * 1000); /* timeout 30s */
241 	nvme_ns_trim_cmd(&nvmeio->cmd, softc->nsid, num_ranges);
242 }
243 
244 static void
245 nda_nvme_write(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
246     void *payload, uint64_t lba, uint32_t len, uint32_t count)
247 {
248 	cam_fill_nvmeio(nvmeio,
249 	    0,			/* retries */
250 	    ndadone,		/* cbfcnp */
251 	    CAM_DIR_OUT,	/* flags */
252 	    payload,		/* data_ptr */
253 	    len,		/* dxfer_len */
254 	    nda_default_timeout * 1000); /* timeout 30s */
255 	nvme_ns_write_cmd(&nvmeio->cmd, softc->nsid, lba, count);
256 }
257 
258 static void
259 nda_nvme_rw_bio(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
260     struct bio *bp, uint32_t rwcmd)
261 {
262 	int flags = rwcmd == NVME_OPC_READ ? CAM_DIR_IN : CAM_DIR_OUT;
263 	void *payload;
264 	uint64_t lba;
265 	uint32_t count;
266 
267 	if (bp->bio_flags & BIO_UNMAPPED) {
268 		flags |= CAM_DATA_BIO;
269 		payload = bp;
270 	} else {
271 		payload = bp->bio_data;
272 	}
273 
274 	lba = bp->bio_pblkno;
275 	count = bp->bio_bcount / softc->disk->d_sectorsize;
276 
277 	cam_fill_nvmeio(nvmeio,
278 	    0,			/* retries */
279 	    ndadone,		/* cbfcnp */
280 	    flags,		/* flags */
281 	    payload,		/* data_ptr */
282 	    bp->bio_bcount,	/* dxfer_len */
283 	    nda_default_timeout * 1000); /* timeout 30s */
284 	nvme_ns_rw_cmd(&nvmeio->cmd, rwcmd, softc->nsid, lba, count);
285 }
286 
287 static int
288 ndaopen(struct disk *dp)
289 {
290 	struct cam_periph *periph;
291 	struct nda_softc *softc;
292 	int error;
293 
294 	periph = (struct cam_periph *)dp->d_drv1;
295 	if (cam_periph_acquire(periph) != 0) {
296 		return(ENXIO);
297 	}
298 
299 	cam_periph_lock(periph);
300 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
301 		cam_periph_unlock(periph);
302 		cam_periph_release(periph);
303 		return (error);
304 	}
305 
306 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
307 	    ("ndaopen\n"));
308 
309 	softc = (struct nda_softc *)periph->softc;
310 	softc->flags |= NDA_FLAG_OPEN;
311 
312 	cam_periph_unhold(periph);
313 	cam_periph_unlock(periph);
314 	return (0);
315 }
316 
317 static int
318 ndaclose(struct disk *dp)
319 {
320 	struct	cam_periph *periph;
321 	struct	nda_softc *softc;
322 	union ccb *ccb;
323 	int error;
324 
325 	periph = (struct cam_periph *)dp->d_drv1;
326 	softc = (struct nda_softc *)periph->softc;
327 	cam_periph_lock(periph);
328 
329 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
330 	    ("ndaclose\n"));
331 
332 	if ((softc->flags & NDA_FLAG_DIRTY) != 0 &&
333 	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
334 	    cam_periph_hold(periph, PRIBIO) == 0) {
335 
336 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
337 		nda_nvme_flush(softc, &ccb->nvmeio);
338 		error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
339 		    /*sense_flags*/0, softc->disk->d_devstat);
340 
341 		if (error != 0)
342 			xpt_print(periph->path, "Synchronize cache failed\n");
343 		else
344 			softc->flags &= ~NDA_FLAG_DIRTY;
345 		xpt_release_ccb(ccb);
346 		cam_periph_unhold(periph);
347 	}
348 
349 	softc->flags &= ~NDA_FLAG_OPEN;
350 
351 	while (softc->refcount != 0)
352 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "ndaclose", 1);
353 	KASSERT(softc->outstanding_cmds == 0,
354 	    ("nda %d outstanding commands", softc->outstanding_cmds));
355 	cam_periph_unlock(periph);
356 	cam_periph_release(periph);
357 	return (0);
358 }
359 
360 static void
361 ndaschedule(struct cam_periph *periph)
362 {
363 	struct nda_softc *softc = (struct nda_softc *)periph->softc;
364 
365 	if (softc->state != NDA_STATE_NORMAL)
366 		return;
367 
368 	cam_iosched_schedule(softc->cam_iosched, periph);
369 }
370 
371 static int
372 ndaioctl(struct disk *dp, u_long cmd, void *data, int fflag,
373     struct thread *td)
374 {
375 	struct cam_periph *periph;
376 	struct nda_softc *softc;
377 
378 	periph = (struct cam_periph *)dp->d_drv1;
379 	softc = (struct nda_softc *)periph->softc;
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 
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.
606 	 * XXX Handle any transactions queued to the card
607 	 *     with XPT_ABORT_CCB.
608 	 */
609 	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
610 
611 	disk_gone(softc->disk);
612 }
613 
614 static void
615 ndacleanup(struct cam_periph *periph)
616 {
617 	struct nda_softc *softc;
618 
619 	softc = (struct nda_softc *)periph->softc;
620 
621 	cam_periph_unlock(periph);
622 
623 	cam_iosched_fini(softc->cam_iosched);
624 
625 	/*
626 	 * If we can't free the sysctl tree, oh well...
627 	 */
628 	if ((softc->flags & NDA_FLAG_SCTX_INIT) != 0) {
629 #ifdef CAM_IO_STATS
630 		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
631 			xpt_print(periph->path,
632 			    "can't remove sysctl stats context\n");
633 #endif
634 		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
635 			xpt_print(periph->path,
636 			    "can't remove sysctl context\n");
637 	}
638 
639 	disk_destroy(softc->disk);
640 	free(softc, M_DEVBUF);
641 	cam_periph_lock(periph);
642 }
643 
644 static void
645 ndaasync(void *callback_arg, u_int32_t code,
646 	struct cam_path *path, void *arg)
647 {
648 	struct cam_periph *periph;
649 
650 	periph = (struct cam_periph *)callback_arg;
651 	switch (code) {
652 	case AC_FOUND_DEVICE:
653 	{
654 		struct ccb_getdev *cgd;
655 		cam_status status;
656 
657 		cgd = (struct ccb_getdev *)arg;
658 		if (cgd == NULL)
659 			break;
660 
661 		if (cgd->protocol != PROTO_NVME)
662 			break;
663 
664 		/*
665 		 * Allocate a peripheral instance for
666 		 * this device and start the probe
667 		 * process.
668 		 */
669 		status = cam_periph_alloc(ndaregister, ndaoninvalidate,
670 					  ndacleanup, ndastart,
671 					  "nda", CAM_PERIPH_BIO,
672 					  path, ndaasync,
673 					  AC_FOUND_DEVICE, cgd);
674 
675 		if (status != CAM_REQ_CMP
676 		 && status != CAM_REQ_INPROG)
677 			printf("ndaasync: Unable to attach to new device "
678 				"due to status 0x%x\n", status);
679 		break;
680 	}
681 	case AC_ADVINFO_CHANGED:
682 	{
683 		uintptr_t buftype;
684 
685 		buftype = (uintptr_t)arg;
686 		if (buftype == CDAI_TYPE_PHYS_PATH) {
687 			struct nda_softc *softc;
688 
689 			softc = periph->softc;
690 			disk_attr_changed(softc->disk, "GEOM::physpath",
691 					  M_NOWAIT);
692 		}
693 		break;
694 	}
695 	case AC_LOST_DEVICE:
696 	default:
697 		cam_periph_async(periph, code, path, arg);
698 		break;
699 	}
700 }
701 
702 static void
703 ndasysctlinit(void *context, int pending)
704 {
705 	struct cam_periph *periph;
706 	struct nda_softc *softc;
707 	char tmpstr[32], tmpstr2[16];
708 
709 	periph = (struct cam_periph *)context;
710 
711 	/* periph was held for us when this task was enqueued */
712 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
713 		cam_periph_release(periph);
714 		return;
715 	}
716 
717 	softc = (struct nda_softc *)periph->softc;
718 	snprintf(tmpstr, sizeof(tmpstr), "CAM NDA unit %d", periph->unit_number);
719 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
720 
721 	sysctl_ctx_init(&softc->sysctl_ctx);
722 	softc->flags |= NDA_FLAG_SCTX_INIT;
723 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
724 		SYSCTL_STATIC_CHILDREN(_kern_cam_nda), OID_AUTO, tmpstr2,
725 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
726 	if (softc->sysctl_tree == NULL) {
727 		printf("ndasysctlinit: unable to allocate sysctl tree\n");
728 		cam_periph_release(periph);
729 		return;
730 	}
731 
732 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
733 	    OID_AUTO, "unmapped_io", CTLFLAG_RD,
734 	    &softc->unmappedio, 0, "Unmapped I/O leaf");
735 
736 	SYSCTL_ADD_QUAD(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
737 	    OID_AUTO, "deletes", CTLFLAG_RD,
738 	    &softc->deletes, "Number of BIO_DELETE requests");
739 
740 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
741 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
742 		"trim_count", CTLFLAG_RD, &softc->trim_count,
743 		"Total number of unmap/dsm commands sent");
744 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
745 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
746 		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
747 		"Total number of ranges in unmap/dsm commands");
748 	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
749 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
750 		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
751 		"Total lbas in the unmap/dsm commands sent");
752 
753 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
754 	    OID_AUTO, "rotating", CTLFLAG_RD, &nda_rotating_media, 1,
755 	    "Rotating media");
756 
757 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
758 	    OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
759 	    softc, 0, ndaflagssysctl, "A",
760 	    "Flags for drive");
761 
762 #ifdef CAM_IO_STATS
763 	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
764 		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
765 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
766 	if (softc->sysctl_stats_tree == NULL) {
767 		printf("ndasysctlinit: unable to allocate sysctl tree for stats\n");
768 		cam_periph_release(periph);
769 		return;
770 	}
771 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
772 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
773 		OID_AUTO, "timeouts", CTLFLAG_RD,
774 		&softc->timeouts, 0,
775 		"Device timeouts reported by the SIM");
776 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
777 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
778 		OID_AUTO, "errors", CTLFLAG_RD,
779 		&softc->errors, 0,
780 		"Transport errors reported by the SIM.");
781 	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
782 		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
783 		OID_AUTO, "pack_invalidations", CTLFLAG_RD,
784 		&softc->invalidations, 0,
785 		"Device pack invalidations.");
786 #endif
787 
788 #ifdef CAM_TEST_FAILURE
789 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
790 		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
791 		periph, 0, cam_periph_invalidate_sysctl, "I",
792 		"Write 1 to invalidate the drive immediately");
793 #endif
794 
795 	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
796 	    softc->sysctl_tree);
797 
798 	cam_periph_release(periph);
799 }
800 
801 static int
802 ndaflagssysctl(SYSCTL_HANDLER_ARGS)
803 {
804 	struct sbuf sbuf;
805 	struct nda_softc *softc = arg1;
806 	int error;
807 
808 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
809 	if (softc->flags != 0)
810 		sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, NDA_FLAG_STRING);
811 	else
812 		sbuf_printf(&sbuf, "0");
813 	error = sbuf_finish(&sbuf);
814 	sbuf_delete(&sbuf);
815 
816 	return (error);
817 }
818 
819 static int
820 ndagetattr(struct bio *bp)
821 {
822 	int ret;
823 	struct cam_periph *periph;
824 
825 	if (g_handleattr_int(bp, "GEOM::canspeedup", nda_enable_biospeedup))
826 		return (EJUSTRETURN);
827 
828 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
829 	cam_periph_lock(periph);
830 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
831 	    periph->path);
832 	cam_periph_unlock(periph);
833 	if (ret == 0)
834 		bp->bio_completed = bp->bio_length;
835 	return ret;
836 }
837 
838 static cam_status
839 ndaregister(struct cam_periph *periph, void *arg)
840 {
841 	struct nda_softc *softc;
842 	struct disk *disk;
843 	struct ccb_pathinq cpi;
844 	const struct nvme_namespace_data *nsd;
845 	const struct nvme_controller_data *cd;
846 	char   announce_buf[80];
847 	uint8_t flbas_fmt, lbads, vwc_present;
848 	u_int maxio;
849 	int quirks;
850 
851 	nsd = nvme_get_identify_ns(periph);
852 	cd = nvme_get_identify_cntrl(periph);
853 
854 	softc = (struct nda_softc *)malloc(sizeof(*softc), M_DEVBUF,
855 	    M_NOWAIT | M_ZERO);
856 
857 	if (softc == NULL) {
858 		printf("ndaregister: Unable to probe new device. "
859 		    "Unable to allocate softc\n");
860 		return(CAM_REQ_CMP_ERR);
861 	}
862 
863 	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
864 		printf("ndaregister: Unable to probe new device. "
865 		       "Unable to allocate iosched memory\n");
866 		free(softc, M_DEVBUF);
867 		return(CAM_REQ_CMP_ERR);
868 	}
869 
870 	/* ident_data parsing */
871 
872 	periph->softc = softc;
873 	softc->quirks = NDA_Q_NONE;
874 	xpt_path_inq(&cpi, periph->path);
875 	TASK_INIT(&softc->sysctl_task, 0, ndasysctlinit, periph);
876 
877 	/*
878 	 * The name space ID is the lun, save it for later I/O
879 	 */
880 	softc->nsid = (uint32_t)xpt_path_lun_id(periph->path);
881 
882 	/*
883 	 * Register this media as a disk
884 	 */
885 	(void)cam_periph_hold(periph, PRIBIO);
886 	cam_periph_unlock(periph);
887 	snprintf(announce_buf, sizeof(announce_buf),
888 	    "kern.cam.nda.%d.quirks", periph->unit_number);
889 	quirks = softc->quirks;
890 	TUNABLE_INT_FETCH(announce_buf, &quirks);
891 	softc->quirks = quirks;
892 	cam_iosched_set_sort_queue(softc->cam_iosched, 0);
893 	softc->disk = disk = disk_alloc();
894 	disk->d_rotation_rate = DISK_RR_NON_ROTATING;
895 	disk->d_open = ndaopen;
896 	disk->d_close = ndaclose;
897 	disk->d_strategy = ndastrategy;
898 	disk->d_ioctl = ndaioctl;
899 	disk->d_getattr = ndagetattr;
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(disk->d_descr, cd->mn,
934 	    NVME_MODEL_NUMBER_LENGTH, sizeof(disk->d_descr));
935 	cam_strvis(disk->d_ident, cd->sn,
936 	    NVME_SERIAL_NUMBER_LENGTH, sizeof(disk->d_ident));
937 	disk->d_hba_vendor = cpi.hba_vendor;
938 	disk->d_hba_device = cpi.hba_device;
939 	disk->d_hba_subvendor = cpi.hba_subvendor;
940 	disk->d_hba_subdevice = cpi.hba_subdevice;
941 	snprintf(disk->d_attachment, sizeof(disk->d_attachment),
942 	    "%s%d", cpi.dev_name, cpi.unit_number);
943 	disk->d_stripesize = disk->d_sectorsize;
944 	disk->d_stripeoffset = 0;
945 	disk->d_devstat = devstat_new_entry(periph->periph_name,
946 	    periph->unit_number, disk->d_sectorsize,
947 	    DEVSTAT_ALL_SUPPORTED,
948 	    DEVSTAT_TYPE_DIRECT | XPORT_DEVSTAT_TYPE(cpi.transport),
949 	    DEVSTAT_PRIORITY_DISK);
950 	/*
951 	 * Add alias for older nvd drives to ease transition.
952 	 */
953 	disk_add_alias(disk, "nvd");
954 
955 	/*
956 	 * Acquire a reference to the periph before we register with GEOM.
957 	 * We'll release this reference once GEOM calls us back (via
958 	 * ndadiskgonecb()) telling us that our provider has been freed.
959 	 */
960 	if (cam_periph_acquire(periph) != 0) {
961 		xpt_print(periph->path, "%s: lost periph during "
962 			  "registration!\n", __func__);
963 		cam_periph_lock(periph);
964 		return (CAM_REQ_CMP_ERR);
965 	}
966 	disk_create(softc->disk, DISK_VERSION);
967 	cam_periph_lock(periph);
968 	cam_periph_unhold(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 	return(CAM_REQ_CMP);
994 }
995 
996 static void
997 ndastart(struct cam_periph *periph, union ccb *start_ccb)
998 {
999 	struct nda_softc *softc = (struct nda_softc *)periph->softc;
1000 	struct ccb_nvmeio *nvmeio = &start_ccb->nvmeio;
1001 
1002 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart\n"));
1003 
1004 	switch (softc->state) {
1005 	case NDA_STATE_NORMAL:
1006 	{
1007 		struct bio *bp;
1008 
1009 		bp = cam_iosched_next_bio(softc->cam_iosched);
1010 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart: bio %p\n", bp));
1011 		if (bp == NULL) {
1012 			xpt_release_ccb(start_ccb);
1013 			break;
1014 		}
1015 
1016 		switch (bp->bio_cmd) {
1017 		case BIO_WRITE:
1018 			softc->flags |= NDA_FLAG_DIRTY;
1019 			/* FALLTHROUGH */
1020 		case BIO_READ:
1021 		{
1022 #ifdef CAM_TEST_FAILURE
1023 			int fail = 0;
1024 
1025 			/*
1026 			 * Support the failure ioctls.  If the command is a
1027 			 * read, and there are pending forced read errors, or
1028 			 * if a write and pending write errors, then fail this
1029 			 * operation with EIO.  This is useful for testing
1030 			 * purposes.  Also, support having every Nth read fail.
1031 			 *
1032 			 * This is a rather blunt tool.
1033 			 */
1034 			if (bp->bio_cmd == BIO_READ) {
1035 				if (softc->force_read_error) {
1036 					softc->force_read_error--;
1037 					fail = 1;
1038 				}
1039 				if (softc->periodic_read_error > 0) {
1040 					if (++softc->periodic_read_count >=
1041 					    softc->periodic_read_error) {
1042 						softc->periodic_read_count = 0;
1043 						fail = 1;
1044 					}
1045 				}
1046 			} else {
1047 				if (softc->force_write_error) {
1048 					softc->force_write_error--;
1049 					fail = 1;
1050 				}
1051 			}
1052 			if (fail) {
1053 				biofinish(bp, NULL, EIO);
1054 				xpt_release_ccb(start_ccb);
1055 				ndaschedule(periph);
1056 				return;
1057 			}
1058 #endif
1059 			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
1060 			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
1061 			    PAGE_SIZE == bp->bio_ma_n,
1062 			    ("Short bio %p", bp));
1063 			nda_nvme_rw_bio(softc, &start_ccb->nvmeio, bp, bp->bio_cmd == BIO_READ ?
1064 			    NVME_OPC_READ : NVME_OPC_WRITE);
1065 			break;
1066 		}
1067 		case BIO_DELETE:
1068 		{
1069 			struct nvme_dsm_range *dsm_range, *dsm_end;
1070 			struct nda_trim_request *trim;
1071 			struct bio *bp1;
1072 			int ents;
1073 			uint32_t totalcount = 0, ranges = 0;
1074 
1075 			trim = malloc(sizeof(*trim), M_NVMEDA, M_ZERO | M_NOWAIT);
1076 			if (trim == NULL) {
1077 				biofinish(bp, NULL, ENOMEM);
1078 				xpt_release_ccb(start_ccb);
1079 				ndaschedule(periph);
1080 				return;
1081 			}
1082 			TAILQ_INIT(&trim->bps);
1083 			bp1 = bp;
1084 			ents = min(nitems(trim->dsm), nda_max_trim_entries);
1085 			dsm_range = trim->dsm;
1086 			dsm_end = dsm_range + ents;
1087 			do {
1088 				TAILQ_INSERT_TAIL(&trim->bps, bp1, bio_queue);
1089 				dsm_range->length =
1090 				    htole32(bp1->bio_bcount / softc->disk->d_sectorsize);
1091 				dsm_range->starting_lba =
1092 				    htole64(bp1->bio_offset / softc->disk->d_sectorsize);
1093 				ranges++;
1094 				totalcount += dsm_range->length;
1095 				dsm_range++;
1096 				if (dsm_range >= dsm_end)
1097 					break;
1098 				bp1 = cam_iosched_next_trim(softc->cam_iosched);
1099 				/* XXX -- Could collapse adjacent ranges, but we don't for now */
1100 				/* XXX -- Could limit based on total payload size */
1101 			} while (bp1 != NULL);
1102 			start_ccb->ccb_trim = trim;
1103 			nda_nvme_trim(softc, &start_ccb->nvmeio, trim->dsm,
1104 			    dsm_range - trim->dsm);
1105 			start_ccb->ccb_state = NDA_CCB_TRIM;
1106 			softc->trim_count++;
1107 			softc->trim_ranges += ranges;
1108 			softc->trim_lbas += totalcount;
1109 			/*
1110 			 * Note: We can have multiple TRIMs in flight, so we don't call
1111 			 * cam_iosched_submit_trim(softc->cam_iosched);
1112 			 * since that forces the I/O scheduler to only schedule one at a time.
1113 			 * On NVMe drives, this is a performance disaster.
1114 			 */
1115 			goto out;
1116 		}
1117 		case BIO_FLUSH:
1118 			nda_nvme_flush(softc, nvmeio);
1119 			break;
1120 		default:
1121 			biofinish(bp, NULL, EOPNOTSUPP);
1122 			xpt_release_ccb(start_ccb);
1123 			ndaschedule(periph);
1124 			return;
1125 		}
1126 		start_ccb->ccb_state = NDA_CCB_BUFFER_IO;
1127 		start_ccb->ccb_bp = bp;
1128 out:
1129 		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
1130 		softc->outstanding_cmds++;
1131 		softc->refcount++;			/* For submission only */
1132 		cam_periph_unlock(periph);
1133 		xpt_action(start_ccb);
1134 		cam_periph_lock(periph);
1135 		softc->refcount--;			/* Submission done */
1136 
1137 		/* May have more work to do, so ensure we stay scheduled */
1138 		ndaschedule(periph);
1139 		break;
1140 		}
1141 	}
1142 }
1143 
1144 static void
1145 ndadone(struct cam_periph *periph, union ccb *done_ccb)
1146 {
1147 	struct nda_softc *softc;
1148 	struct ccb_nvmeio *nvmeio = &done_ccb->nvmeio;
1149 	struct cam_path *path;
1150 	int state;
1151 
1152 	softc = (struct nda_softc *)periph->softc;
1153 	path = done_ccb->ccb_h.path;
1154 
1155 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("ndadone\n"));
1156 
1157 	state = nvmeio->ccb_state & NDA_CCB_TYPE_MASK;
1158 	switch (state) {
1159 	case NDA_CCB_BUFFER_IO:
1160 	case NDA_CCB_TRIM:
1161 	{
1162 		int error;
1163 
1164 		cam_periph_lock(periph);
1165 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1166 			error = ndaerror(done_ccb, 0, 0);
1167 			if (error == ERESTART) {
1168 				/* A retry was scheduled, so just return. */
1169 				cam_periph_unlock(periph);
1170 				return;
1171 			}
1172 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1173 				cam_release_devq(path,
1174 						 /*relsim_flags*/0,
1175 						 /*reduction*/0,
1176 						 /*timeout*/0,
1177 						 /*getcount_only*/0);
1178 		} else {
1179 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1180 				panic("REQ_CMP with QFRZN");
1181 			error = 0;
1182 		}
1183 		if (state == NDA_CCB_BUFFER_IO) {
1184 			struct bio *bp;
1185 
1186 			bp = (struct bio *)done_ccb->ccb_bp;
1187 			bp->bio_error = error;
1188 			if (error != 0) {
1189 				bp->bio_resid = bp->bio_bcount;
1190 				bp->bio_flags |= BIO_ERROR;
1191 			} else {
1192 				bp->bio_resid = 0;
1193 			}
1194 			softc->outstanding_cmds--;
1195 
1196 			/*
1197 			 * We need to call cam_iosched before we call biodone so that we
1198 			 * don't measure any activity that happens in the completion
1199 			 * routine, which in the case of sendfile can be quite
1200 			 * extensive.
1201 			 */
1202 			cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
1203 			xpt_release_ccb(done_ccb);
1204 			ndaschedule(periph);
1205 			cam_periph_unlock(periph);
1206 			biodone(bp);
1207 		} else { /* state == NDA_CCB_TRIM */
1208 			struct nda_trim_request *trim;
1209 			struct bio *bp1, *bp2;
1210 			TAILQ_HEAD(, bio) queue;
1211 
1212 			trim = nvmeio->ccb_trim;
1213 			TAILQ_INIT(&queue);
1214 			TAILQ_CONCAT(&queue, &trim->bps, bio_queue);
1215 			free(trim, M_NVMEDA);
1216 
1217 			/*
1218 			 * Since we can have multiple trims in flight, we don't
1219 			 * need to call this here.
1220 			 * cam_iosched_trim_done(softc->cam_iosched);
1221 			 */
1222 			/*
1223 			 * The the I/O scheduler that we're finishing the I/O
1224 			 * so we can keep book. The first one we pass in the CCB
1225 			 * which has the timing information. The rest we pass in NULL
1226 			 * so we can keep proper counts.
1227 			 */
1228 			bp1 = TAILQ_FIRST(&queue);
1229 			cam_iosched_bio_complete(softc->cam_iosched, bp1, done_ccb);
1230 			xpt_release_ccb(done_ccb);
1231 			softc->outstanding_cmds--;
1232 			ndaschedule(periph);
1233 			cam_periph_unlock(periph);
1234 			while ((bp2 = TAILQ_FIRST(&queue)) != NULL) {
1235 				TAILQ_REMOVE(&queue, bp2, bio_queue);
1236 				bp2->bio_error = error;
1237 				if (error != 0) {
1238 					bp2->bio_flags |= BIO_ERROR;
1239 					bp2->bio_resid = bp1->bio_bcount;
1240 				} else
1241 					bp2->bio_resid = 0;
1242 				if (bp1 != bp2)
1243 					cam_iosched_bio_complete(softc->cam_iosched, bp2, NULL);
1244 				biodone(bp2);
1245 			}
1246 		}
1247 		return;
1248 	}
1249 	case NDA_CCB_DUMP:
1250 		/* No-op.  We're polling */
1251 		return;
1252 	case NDA_CCB_PASS:
1253 		return;
1254 	default:
1255 		break;
1256 	}
1257 	xpt_release_ccb(done_ccb);
1258 }
1259 
1260 static int
1261 ndaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1262 {
1263 	struct nda_softc *softc;
1264 	struct cam_periph *periph;
1265 
1266 	periph = xpt_path_periph(ccb->ccb_h.path);
1267 	softc = (struct nda_softc *)periph->softc;
1268 
1269 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1270 	case CAM_CMD_TIMEOUT:
1271 #ifdef CAM_IO_STATS
1272 		softc->timeouts++;
1273 #endif
1274 		break;
1275 	case CAM_REQ_ABORTED:
1276 	case CAM_REQ_CMP_ERR:
1277 	case CAM_REQ_TERMIO:
1278 	case CAM_UNREC_HBA_ERROR:
1279 	case CAM_DATA_RUN_ERR:
1280 	case CAM_ATA_STATUS_ERROR:
1281 #ifdef CAM_IO_STATS
1282 		softc->errors++;
1283 #endif
1284 		break;
1285 	default:
1286 		break;
1287 	}
1288 
1289 	return(cam_periph_error(ccb, cam_flags, sense_flags));
1290 }
1291 
1292 /*
1293  * Step through all NDA peripheral drivers, and if the device is still open,
1294  * sync the disk cache to physical media.
1295  */
1296 static void
1297 ndaflush(void)
1298 {
1299 	struct cam_periph *periph;
1300 	struct nda_softc *softc;
1301 	union ccb *ccb;
1302 	int error;
1303 
1304 	CAM_PERIPH_FOREACH(periph, &ndadriver) {
1305 		softc = (struct nda_softc *)periph->softc;
1306 
1307 		if (SCHEDULER_STOPPED()) {
1308 			/*
1309 			 * If we paniced with the lock held or the periph is not
1310 			 * open, do not recurse.  Otherwise, call ndadump since
1311 			 * that avoids the sleeping cam_periph_getccb does if no
1312 			 * CCBs are available.
1313 			 */
1314 			if (!cam_periph_owned(periph) &&
1315 			    (softc->flags & NDA_FLAG_OPEN)) {
1316 				ndadump(softc->disk, NULL, 0, 0, 0);
1317 			}
1318 			continue;
1319 		}
1320 
1321 		/*
1322 		 * We only sync the cache if the drive is still open
1323 		 */
1324 		cam_periph_lock(periph);
1325 		if ((softc->flags & NDA_FLAG_OPEN) == 0) {
1326 			cam_periph_unlock(periph);
1327 			continue;
1328 		}
1329 
1330 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1331 		nda_nvme_flush(softc, &ccb->nvmeio);
1332 		error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
1333 		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
1334 		    softc->disk->d_devstat);
1335 		if (error != 0)
1336 			xpt_print(periph->path, "Synchronize cache failed\n");
1337 		xpt_release_ccb(ccb);
1338 		cam_periph_unlock(periph);
1339 	}
1340 }
1341 
1342 static void
1343 ndashutdown(void *arg, int howto)
1344 {
1345 
1346 	ndaflush();
1347 }
1348 
1349 static void
1350 ndasuspend(void *arg)
1351 {
1352 
1353 	ndaflush();
1354 }
1355