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