2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2015 Netflix, Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
27 * Derived from ata_da.c:
28 * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
40 #include <sys/sysctl.h>
41 #include <sys/taskqueue.h>
43 #include <sys/mutex.h>
45 #include <sys/devicestat.h>
46 #include <sys/eventhandler.h>
47 #include <sys/malloc.h>
50 #include <sys/reboot.h>
52 #include <geom/geom.h>
53 #include <geom/geom_disk.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>
68 #include <cam/nvme/nvme_all.h>
75 NDA_FLAG_OPEN = 0x0001,
76 NDA_FLAG_DIRTY = 0x0002,
77 NDA_FLAG_SCTX_INIT = 0x0004,
79 #define NDA_FLAG_STRING \
90 #define NDA_Q_BIT_STRING \
95 NDA_CCB_BUFFER_IO = 0x01,
99 NDA_CCB_TYPE_MASK = 0x0F,
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 */
108 struct cam_iosched_softc *cam_iosched;
109 int outstanding_cmds; /* Number of active commands */
110 int refcount; /* Active xpt_action() calls */
116 uint32_t nsid; /* Namespace ID for this nda device */
118 struct task sysctl_task;
119 struct sysctl_ctx_list sysctl_ctx;
120 struct sysctl_oid *sysctl_tree;
122 uint64_t trim_ranges;
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;
131 struct sysctl_ctx_list sysctl_stats_ctx;
132 struct sysctl_oid *sysctl_stats_tree;
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;
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");
146 /* Need quirk table */
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);
167 #ifndef NDA_DEFAULT_SEND_ORDERED
168 #define NDA_DEFAULT_SEND_ORDERED 1
170 #ifndef NDA_DEFAULT_TIMEOUT
171 #define NDA_DEFAULT_TIMEOUT 30 /* Timeout in seconds */
173 #ifndef NDA_DEFAULT_RETRY
174 #define NDA_DEFAULT_RETRY 4
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 */
180 static SYSCTL_NODE(_kern_cam, OID_AUTO, nda, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
181 "CAM Direct Access Disk driver");
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.");
198 * All NVMe media is non-rotational, so all nvme device instances
199 * share this to implement the sysctl.
201 static int nda_rotating_media = 0;
203 static struct periph_driver ndadriver =
206 TAILQ_HEAD_INITIALIZER(ndadriver.units), /* generation */ 0
209 PERIPHDRIVER_DECLARE(nda, ndadriver);
211 static MALLOC_DEFINE(M_NVMEDA, "nvme_da", "nvme_da buffers");
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.
221 nda_nvme_flush(struct nda_softc *softc, struct ccb_nvmeio *nvmeio)
223 cam_fill_nvmeio(nvmeio,
225 ndadone, /* cbfcnp */
226 CAM_DIR_NONE, /* flags */
229 nda_default_timeout * 1000); /* timeout 30s */
230 nvme_ns_flush_cmd(&nvmeio->cmd, softc->nsid);
234 nda_nvme_trim(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
235 void *payload, uint32_t num_ranges)
237 cam_fill_nvmeio(nvmeio,
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);
248 nda_nvme_write(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
249 void *payload, uint64_t lba, uint32_t len, uint32_t count)
251 cam_fill_nvmeio(nvmeio,
253 ndadone, /* cbfcnp */
254 CAM_DIR_OUT, /* flags */
255 payload, /* data_ptr */
257 nda_default_timeout * 1000); /* timeout 30s */
258 nvme_ns_write_cmd(&nvmeio->cmd, softc->nsid, lba, count);
262 nda_nvme_rw_bio(struct nda_softc *softc, struct ccb_nvmeio *nvmeio,
263 struct bio *bp, uint32_t rwcmd)
265 int flags = rwcmd == NVME_OPC_READ ? CAM_DIR_IN : CAM_DIR_OUT;
270 if (bp->bio_flags & BIO_UNMAPPED) {
271 flags |= CAM_DATA_BIO;
274 payload = bp->bio_data;
277 lba = bp->bio_pblkno;
278 count = bp->bio_bcount / softc->disk->d_sectorsize;
280 cam_fill_nvmeio(nvmeio,
282 ndadone, /* cbfcnp */
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);
291 ndaopen(struct disk *dp)
293 struct cam_periph *periph;
294 struct nda_softc *softc;
297 periph = (struct cam_periph *)dp->d_drv1;
298 if (cam_periph_acquire(periph) != 0) {
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);
309 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
312 softc = (struct nda_softc *)periph->softc;
313 softc->flags |= NDA_FLAG_OPEN;
315 cam_periph_unhold(periph);
316 cam_periph_unlock(periph);
321 ndaclose(struct disk *dp)
323 struct cam_periph *periph;
324 struct nda_softc *softc;
328 periph = (struct cam_periph *)dp->d_drv1;
329 softc = (struct nda_softc *)periph->softc;
330 cam_periph_lock(periph);
332 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
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);
344 xpt_print(periph->path, "Synchronize cache failed\n");
346 softc->flags &= ~NDA_FLAG_DIRTY;
347 xpt_release_ccb(ccb);
348 cam_periph_unhold(periph);
351 softc->flags &= ~NDA_FLAG_OPEN;
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);
363 ndaschedule(struct cam_periph *periph)
365 struct nda_softc *softc = (struct nda_softc *)periph->softc;
367 if (softc->state != NDA_STATE_NORMAL)
370 cam_iosched_schedule(softc->cam_iosched, periph);
374 ndaioctl(struct disk *dp, u_long cmd, void *data, int fflag,
377 struct cam_periph *periph;
378 struct nda_softc *softc;
380 periph = (struct cam_periph *)dp->d_drv1;
381 softc = (struct nda_softc *)periph->softc;
387 * These don't map well to the underlying CCBs, so
388 * they are usupported via CAM.
393 struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)data;
394 struct ccb_pathinq cpi;
396 xpt_path_inq(&cpi, periph->path);
397 strncpy(gnsid->cdev, cpi.xport_specific.nvme.dev_name,
398 sizeof(gnsid->cdev));
399 gnsid->nsid = cpi.xport_specific.nvme.nsid;
402 case NVME_PASSTHROUGH_CMD:
404 struct nvme_pt_command *pt;
406 struct cam_periph_map_info mapinfo;
407 u_int maxmap = dp->d_maxsize;
411 * Create a NVME_IO CCB to do the passthrough command.
413 pt = (struct nvme_pt_command *)data;
414 ccb = xpt_alloc_ccb();
415 xpt_setup_ccb(&ccb->ccb_h, periph->path, CAM_PRIORITY_NORMAL);
416 ccb->ccb_state = NDA_CCB_PASS;
417 cam_fill_nvmeio(&ccb->nvmeio,
420 (pt->is_read ? CAM_DIR_IN : CAM_DIR_OUT) | CAM_DATA_VADDR,
423 nda_default_timeout * 1000);
424 memcpy(&ccb->nvmeio.cmd, &pt->cmd, sizeof(pt->cmd));
427 * Wire the user memory in this request for the I/O
429 memset(&mapinfo, 0, sizeof(mapinfo));
430 error = cam_periph_mapmem(ccb, &mapinfo, maxmap);
435 * Lock the periph and run the command.
437 cam_periph_lock(periph);
438 cam_periph_runccb(ccb, NULL, CAM_RETRY_SELTO,
439 SF_RETRY_UA | SF_NO_PRINT, NULL);
442 * Tear down mapping and return status.
444 cam_periph_unlock(periph);
445 cam_periph_unmapmem(ccb, &mapinfo);
446 error = (ccb->ccb_h.status == CAM_REQ_CMP) ? 0 : EIO;
448 cam_periph_lock(periph);
449 xpt_release_ccb(ccb);
450 cam_periph_unlock(periph);
460 * Actually translate the requested transfer into one the physical driver
461 * can understand. The transfer is described by a buf and will include
462 * only one physical transfer.
465 ndastrategy(struct bio *bp)
467 struct cam_periph *periph;
468 struct nda_softc *softc;
470 periph = (struct cam_periph *)bp->bio_disk->d_drv1;
471 softc = (struct nda_softc *)periph->softc;
473 cam_periph_lock(periph);
475 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastrategy(%p)\n", bp));
478 * If the device has been made invalid, error out
480 if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
481 cam_periph_unlock(periph);
482 biofinish(bp, NULL, ENXIO);
486 if (bp->bio_cmd == BIO_DELETE)
490 * Place it in the queue of disk activities for this disk
492 cam_iosched_queue_work(softc->cam_iosched, bp);
495 * Schedule ourselves for performing the work.
498 cam_periph_unlock(periph);
504 ndadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
506 struct cam_periph *periph;
507 struct nda_softc *softc;
509 struct ccb_nvmeio nvmeio;
517 softc = (struct nda_softc *)periph->softc;
518 secsize = softc->disk->d_sectorsize;
519 lba = offset / secsize;
520 count = length / secsize;
522 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
525 /* xpt_get_ccb returns a zero'd allocation for the ccb, mimic that here */
526 memset(&nvmeio, 0, sizeof(nvmeio));
528 xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
529 nvmeio.ccb_state = NDA_CCB_DUMP;
530 nda_nvme_write(softc, &nvmeio, virtual, lba, length, count);
531 error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
532 0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
534 printf("Aborting dump due to I/O error %d.\n", error);
540 xpt_setup_ccb(&nvmeio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
542 nvmeio.ccb_state = NDA_CCB_DUMP;
543 nda_nvme_flush(softc, &nvmeio);
544 error = cam_periph_runccb((union ccb *)&nvmeio, cam_periph_error,
545 0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
547 xpt_print(periph->path, "flush cmd failed\n");
557 * Install a global async callback. This callback will
558 * receive async callbacks like "new device found".
560 status = xpt_register_async(AC_FOUND_DEVICE, ndaasync, NULL, NULL);
562 if (status != CAM_REQ_CMP) {
563 printf("nda: Failed to attach master async callback "
564 "due to status 0x%x!\n", status);
565 } else if (nda_send_ordered) {
566 /* Register our event handlers */
567 if ((EVENTHANDLER_REGISTER(power_suspend, ndasuspend,
568 NULL, EVENTHANDLER_PRI_LAST)) == NULL)
569 printf("ndainit: power event registration failed!\n");
570 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, ndashutdown,
571 NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
572 printf("ndainit: shutdown event registration failed!\n");
577 * Callback from GEOM, called when it has finished cleaning up its
581 ndadiskgonecb(struct disk *dp)
583 struct cam_periph *periph;
585 periph = (struct cam_periph *)dp->d_drv1;
587 cam_periph_release(periph);
591 ndaoninvalidate(struct cam_periph *periph)
593 struct nda_softc *softc;
595 softc = (struct nda_softc *)periph->softc;
598 * De-register any async callbacks.
600 xpt_register_async(0, ndaasync, periph, periph->path);
602 softc->invalidations++;
606 * Return all queued I/O with ENXIO.
607 * XXX Handle any transactions queued to the card
608 * with XPT_ABORT_CCB.
610 cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);
612 disk_gone(softc->disk);
616 ndacleanup(struct cam_periph *periph)
618 struct nda_softc *softc;
620 softc = (struct nda_softc *)periph->softc;
622 cam_periph_unlock(periph);
624 cam_iosched_fini(softc->cam_iosched);
627 * If we can't free the sysctl tree, oh well...
629 if ((softc->flags & NDA_FLAG_SCTX_INIT) != 0) {
631 if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
632 xpt_print(periph->path,
633 "can't remove sysctl stats context\n");
635 if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
636 xpt_print(periph->path,
637 "can't remove sysctl context\n");
640 disk_destroy(softc->disk);
641 free(softc, M_DEVBUF);
642 cam_periph_lock(periph);
646 ndaasync(void *callback_arg, u_int32_t code,
647 struct cam_path *path, void *arg)
649 struct cam_periph *periph;
651 periph = (struct cam_periph *)callback_arg;
653 case AC_FOUND_DEVICE:
655 struct ccb_getdev *cgd;
658 cgd = (struct ccb_getdev *)arg;
662 if (cgd->protocol != PROTO_NVME)
666 * Allocate a peripheral instance for
667 * this device and start the probe
670 status = cam_periph_alloc(ndaregister, ndaoninvalidate,
671 ndacleanup, ndastart,
672 "nda", CAM_PERIPH_BIO,
674 AC_FOUND_DEVICE, cgd);
676 if (status != CAM_REQ_CMP
677 && status != CAM_REQ_INPROG)
678 printf("ndaasync: Unable to attach to new device "
679 "due to status 0x%x\n", status);
682 case AC_ADVINFO_CHANGED:
686 buftype = (uintptr_t)arg;
687 if (buftype == CDAI_TYPE_PHYS_PATH) {
688 struct nda_softc *softc;
690 softc = periph->softc;
691 disk_attr_changed(softc->disk, "GEOM::physpath",
698 cam_periph_async(periph, code, path, arg);
704 ndasysctlinit(void *context, int pending)
706 struct cam_periph *periph;
707 struct nda_softc *softc;
708 char tmpstr[32], tmpstr2[16];
710 periph = (struct cam_periph *)context;
712 /* periph was held for us when this task was enqueued */
713 if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
714 cam_periph_release(periph);
718 softc = (struct nda_softc *)periph->softc;
719 snprintf(tmpstr, sizeof(tmpstr), "CAM NDA unit %d", periph->unit_number);
720 snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
722 sysctl_ctx_init(&softc->sysctl_ctx);
723 softc->flags |= NDA_FLAG_SCTX_INIT;
724 softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
725 SYSCTL_STATIC_CHILDREN(_kern_cam_nda), OID_AUTO, tmpstr2,
726 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
727 if (softc->sysctl_tree == NULL) {
728 printf("ndasysctlinit: unable to allocate sysctl tree\n");
729 cam_periph_release(periph);
733 SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
734 OID_AUTO, "unmapped_io", CTLFLAG_RD,
735 &softc->unmappedio, 0, "Unmapped I/O leaf");
737 SYSCTL_ADD_QUAD(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
738 OID_AUTO, "deletes", CTLFLAG_RD,
739 &softc->deletes, "Number of BIO_DELETE requests");
741 SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
742 SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
743 "trim_count", CTLFLAG_RD, &softc->trim_count,
744 "Total number of unmap/dsm commands sent");
745 SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
746 SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
747 "trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
748 "Total number of ranges in unmap/dsm commands");
749 SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
750 SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
751 "trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
752 "Total lbas in the unmap/dsm commands sent");
754 SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
755 OID_AUTO, "rotating", CTLFLAG_RD, &nda_rotating_media, 1,
758 SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
759 OID_AUTO, "flags", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
760 softc, 0, ndaflagssysctl, "A",
764 softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
765 SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
766 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Statistics");
767 if (softc->sysctl_stats_tree == NULL) {
768 printf("ndasysctlinit: unable to allocate sysctl tree for stats\n");
769 cam_periph_release(periph);
772 SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
773 SYSCTL_CHILDREN(softc->sysctl_stats_tree),
774 OID_AUTO, "timeouts", CTLFLAG_RD,
776 "Device timeouts reported by the SIM");
777 SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
778 SYSCTL_CHILDREN(softc->sysctl_stats_tree),
779 OID_AUTO, "errors", CTLFLAG_RD,
781 "Transport errors reported by the SIM.");
782 SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
783 SYSCTL_CHILDREN(softc->sysctl_stats_tree),
784 OID_AUTO, "pack_invalidations", CTLFLAG_RD,
785 &softc->invalidations, 0,
786 "Device pack invalidations.");
789 #ifdef CAM_TEST_FAILURE
790 SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
791 OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
792 periph, 0, cam_periph_invalidate_sysctl, "I",
793 "Write 1 to invalidate the drive immediately");
796 cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
799 cam_periph_release(periph);
803 ndaflagssysctl(SYSCTL_HANDLER_ARGS)
806 struct nda_softc *softc = arg1;
809 sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
810 if (softc->flags != 0)
811 sbuf_printf(&sbuf, "0x%b", (unsigned)softc->flags, NDA_FLAG_STRING);
813 sbuf_printf(&sbuf, "0");
814 error = sbuf_finish(&sbuf);
821 ndagetattr(struct bio *bp)
824 struct cam_periph *periph;
826 if (g_handleattr_int(bp, "GEOM::canspeedup", nda_enable_biospeedup))
827 return (EJUSTRETURN);
829 periph = (struct cam_periph *)bp->bio_disk->d_drv1;
830 cam_periph_lock(periph);
831 ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
833 cam_periph_unlock(periph);
835 bp->bio_completed = bp->bio_length;
840 ndaregister(struct cam_periph *periph, void *arg)
842 struct nda_softc *softc;
844 struct ccb_pathinq cpi;
845 const struct nvme_namespace_data *nsd;
846 const struct nvme_controller_data *cd;
847 char announce_buf[80];
848 uint8_t flbas_fmt, lbads, vwc_present;
852 nsd = nvme_get_identify_ns(periph);
853 cd = nvme_get_identify_cntrl(periph);
855 softc = (struct nda_softc *)malloc(sizeof(*softc), M_DEVBUF,
859 printf("ndaregister: Unable to probe new device. "
860 "Unable to allocate softc\n");
861 return(CAM_REQ_CMP_ERR);
864 if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
865 printf("ndaregister: Unable to probe new device. "
866 "Unable to allocate iosched memory\n");
867 free(softc, M_DEVBUF);
868 return(CAM_REQ_CMP_ERR);
871 /* ident_data parsing */
873 periph->softc = softc;
874 softc->quirks = NDA_Q_NONE;
875 xpt_path_inq(&cpi, periph->path);
876 TASK_INIT(&softc->sysctl_task, 0, ndasysctlinit, periph);
879 * The name space ID is the lun, save it for later I/O
881 softc->nsid = (uint32_t)xpt_path_lun_id(periph->path);
884 * Register this media as a disk
886 (void)cam_periph_hold(periph, PRIBIO);
887 cam_periph_unlock(periph);
888 snprintf(announce_buf, sizeof(announce_buf),
889 "kern.cam.nda.%d.quirks", periph->unit_number);
890 quirks = softc->quirks;
891 TUNABLE_INT_FETCH(announce_buf, &quirks);
892 softc->quirks = quirks;
893 cam_iosched_set_sort_queue(softc->cam_iosched, 0);
894 softc->disk = disk = disk_alloc();
895 disk->d_rotation_rate = DISK_RR_NON_ROTATING;
896 disk->d_open = ndaopen;
897 disk->d_close = ndaclose;
898 disk->d_strategy = ndastrategy;
899 disk->d_ioctl = ndaioctl;
900 disk->d_getattr = ndagetattr;
901 disk->d_dump = ndadump;
902 disk->d_gone = ndadiskgonecb;
903 disk->d_name = "nda";
904 disk->d_drv1 = periph;
905 disk->d_unit = periph->unit_number;
906 maxio = cpi.maxio; /* Honor max I/O size of SIM */
908 maxio = DFLTPHYS; /* traditional default */
909 else if (maxio > MAXPHYS)
910 maxio = MAXPHYS; /* for safety */
911 disk->d_maxsize = maxio;
912 flbas_fmt = (nsd->flbas >> NVME_NS_DATA_FLBAS_FORMAT_SHIFT) &
913 NVME_NS_DATA_FLBAS_FORMAT_MASK;
914 lbads = (nsd->lbaf[flbas_fmt] >> NVME_NS_DATA_LBAF_LBADS_SHIFT) &
915 NVME_NS_DATA_LBAF_LBADS_MASK;
916 disk->d_sectorsize = 1 << lbads;
917 disk->d_mediasize = (off_t)(disk->d_sectorsize * nsd->nsze);
918 disk->d_delmaxsize = disk->d_mediasize;
919 disk->d_flags = DISKFLAG_DIRECT_COMPLETION;
920 if (nvme_ctrlr_has_dataset_mgmt(cd))
921 disk->d_flags |= DISKFLAG_CANDELETE;
922 vwc_present = (cd->vwc >> NVME_CTRLR_DATA_VWC_PRESENT_SHIFT) &
923 NVME_CTRLR_DATA_VWC_PRESENT_MASK;
925 disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
926 if ((cpi.hba_misc & PIM_UNMAPPED) != 0) {
927 disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
928 softc->unmappedio = 1;
931 * d_ident and d_descr are both far bigger than the length of either
932 * the serial or model number strings.
934 cam_strvis(disk->d_descr, cd->mn,
935 NVME_MODEL_NUMBER_LENGTH, sizeof(disk->d_descr));
936 cam_strvis(disk->d_ident, cd->sn,
937 NVME_SERIAL_NUMBER_LENGTH, sizeof(disk->d_ident));
938 disk->d_hba_vendor = cpi.hba_vendor;
939 disk->d_hba_device = cpi.hba_device;
940 disk->d_hba_subvendor = cpi.hba_subvendor;
941 disk->d_hba_subdevice = cpi.hba_subdevice;
942 snprintf(disk->d_attachment, sizeof(disk->d_attachment),
943 "%s%d", cpi.dev_name, cpi.unit_number);
944 if (((nsd->nsfeat >> NVME_NS_DATA_NSFEAT_NPVALID_SHIFT) &
945 NVME_NS_DATA_NSFEAT_NPVALID_MASK) != 0 && nsd->npwg != 0)
946 disk->d_stripesize = ((nsd->npwg + 1) * disk->d_sectorsize);
948 disk->d_stripesize = nsd->noiob * disk->d_sectorsize;
949 disk->d_stripeoffset = 0;
950 disk->d_devstat = devstat_new_entry(periph->periph_name,
951 periph->unit_number, disk->d_sectorsize,
952 DEVSTAT_ALL_SUPPORTED,
953 DEVSTAT_TYPE_DIRECT | XPORT_DEVSTAT_TYPE(cpi.transport),
954 DEVSTAT_PRIORITY_DISK);
956 * Add alias for older nvd drives to ease transition.
959 disk_add_alias(disk, "nvd");
962 * Acquire a reference to the periph before we register with GEOM.
963 * We'll release this reference once GEOM calls us back (via
964 * ndadiskgonecb()) telling us that our provider has been freed.
966 if (cam_periph_acquire(periph) != 0) {
967 xpt_print(periph->path, "%s: lost periph during "
968 "registration!\n", __func__);
969 cam_periph_lock(periph);
970 return (CAM_REQ_CMP_ERR);
972 disk_create(softc->disk, DISK_VERSION);
973 cam_periph_lock(periph);
974 cam_periph_unhold(periph);
976 snprintf(announce_buf, sizeof(announce_buf),
977 "%juMB (%ju %u byte sectors)",
978 (uintmax_t)((uintmax_t)disk->d_mediasize / (1024*1024)),
979 (uintmax_t)disk->d_mediasize / disk->d_sectorsize,
981 xpt_announce_periph(periph, announce_buf);
982 xpt_announce_quirks(periph, softc->quirks, NDA_Q_BIT_STRING);
985 * Create our sysctl variables, now that we know
986 * we have successfully attached.
988 if (cam_periph_acquire(periph) == 0)
989 taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
992 * Register for device going away and info about the drive
993 * changing (though with NVMe, it can't)
995 xpt_register_async(AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
996 ndaasync, periph, periph->path);
998 softc->state = NDA_STATE_NORMAL;
1003 ndastart(struct cam_periph *periph, union ccb *start_ccb)
1005 struct nda_softc *softc = (struct nda_softc *)periph->softc;
1006 struct ccb_nvmeio *nvmeio = &start_ccb->nvmeio;
1008 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart\n"));
1010 switch (softc->state) {
1011 case NDA_STATE_NORMAL:
1015 bp = cam_iosched_next_bio(softc->cam_iosched);
1016 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("ndastart: bio %p\n", bp));
1018 xpt_release_ccb(start_ccb);
1022 switch (bp->bio_cmd) {
1024 softc->flags |= NDA_FLAG_DIRTY;
1028 #ifdef CAM_TEST_FAILURE
1032 * Support the failure ioctls. If the command is a
1033 * read, and there are pending forced read errors, or
1034 * if a write and pending write errors, then fail this
1035 * operation with EIO. This is useful for testing
1036 * purposes. Also, support having every Nth read fail.
1038 * This is a rather blunt tool.
1040 if (bp->bio_cmd == BIO_READ) {
1041 if (softc->force_read_error) {
1042 softc->force_read_error--;
1045 if (softc->periodic_read_error > 0) {
1046 if (++softc->periodic_read_count >=
1047 softc->periodic_read_error) {
1048 softc->periodic_read_count = 0;
1053 if (softc->force_write_error) {
1054 softc->force_write_error--;
1059 biofinish(bp, NULL, EIO);
1060 xpt_release_ccb(start_ccb);
1061 ndaschedule(periph);
1065 KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
1066 round_page(bp->bio_bcount + bp->bio_ma_offset) /
1067 PAGE_SIZE == bp->bio_ma_n,
1068 ("Short bio %p", bp));
1069 nda_nvme_rw_bio(softc, &start_ccb->nvmeio, bp, bp->bio_cmd == BIO_READ ?
1070 NVME_OPC_READ : NVME_OPC_WRITE);
1075 struct nvme_dsm_range *dsm_range, *dsm_end;
1076 struct nda_trim_request *trim;
1079 uint32_t totalcount = 0, ranges = 0;
1081 trim = malloc(sizeof(*trim), M_NVMEDA, M_ZERO | M_NOWAIT);
1083 biofinish(bp, NULL, ENOMEM);
1084 xpt_release_ccb(start_ccb);
1085 ndaschedule(periph);
1088 TAILQ_INIT(&trim->bps);
1090 ents = min(nitems(trim->dsm), nda_max_trim_entries);
1091 ents = max(ents, 1);
1092 dsm_range = trim->dsm;
1093 dsm_end = dsm_range + ents;
1095 TAILQ_INSERT_TAIL(&trim->bps, bp1, bio_queue);
1097 htole32(bp1->bio_bcount / softc->disk->d_sectorsize);
1098 dsm_range->starting_lba =
1099 htole64(bp1->bio_offset / softc->disk->d_sectorsize);
1101 totalcount += dsm_range->length;
1103 if (dsm_range >= dsm_end)
1105 bp1 = cam_iosched_next_trim(softc->cam_iosched);
1106 /* XXX -- Could collapse adjacent ranges, but we don't for now */
1107 /* XXX -- Could limit based on total payload size */
1108 } while (bp1 != NULL);
1109 start_ccb->ccb_trim = trim;
1110 nda_nvme_trim(softc, &start_ccb->nvmeio, trim->dsm,
1111 dsm_range - trim->dsm);
1112 start_ccb->ccb_state = NDA_CCB_TRIM;
1113 softc->trim_count++;
1114 softc->trim_ranges += ranges;
1115 softc->trim_lbas += totalcount;
1117 * Note: We can have multiple TRIMs in flight, so we don't call
1118 * cam_iosched_submit_trim(softc->cam_iosched);
1119 * since that forces the I/O scheduler to only schedule one at a time.
1120 * On NVMe drives, this is a performance disaster.
1125 nda_nvme_flush(softc, nvmeio);
1128 biofinish(bp, NULL, EOPNOTSUPP);
1129 xpt_release_ccb(start_ccb);
1130 ndaschedule(periph);
1133 start_ccb->ccb_state = NDA_CCB_BUFFER_IO;
1134 start_ccb->ccb_bp = bp;
1136 start_ccb->ccb_h.flags |= CAM_UNLOCKED;
1137 softc->outstanding_cmds++;
1138 softc->refcount++; /* For submission only */
1139 cam_periph_unlock(periph);
1140 xpt_action(start_ccb);
1141 cam_periph_lock(periph);
1142 softc->refcount--; /* Submission done */
1144 /* May have more work to do, so ensure we stay scheduled */
1145 ndaschedule(periph);
1152 ndadone(struct cam_periph *periph, union ccb *done_ccb)
1154 struct nda_softc *softc;
1155 struct ccb_nvmeio *nvmeio = &done_ccb->nvmeio;
1156 struct cam_path *path;
1159 softc = (struct nda_softc *)periph->softc;
1160 path = done_ccb->ccb_h.path;
1162 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("ndadone\n"));
1164 state = nvmeio->ccb_state & NDA_CCB_TYPE_MASK;
1166 case NDA_CCB_BUFFER_IO:
1171 cam_periph_lock(periph);
1172 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1173 error = ndaerror(done_ccb, 0, 0);
1174 if (error == ERESTART) {
1175 /* A retry was scheduled, so just return. */
1176 cam_periph_unlock(periph);
1179 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1180 cam_release_devq(path,
1184 /*getcount_only*/0);
1186 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1187 panic("REQ_CMP with QFRZN");
1190 if (state == NDA_CCB_BUFFER_IO) {
1193 bp = (struct bio *)done_ccb->ccb_bp;
1194 bp->bio_error = error;
1196 bp->bio_resid = bp->bio_bcount;
1197 bp->bio_flags |= BIO_ERROR;
1201 softc->outstanding_cmds--;
1204 * We need to call cam_iosched before we call biodone so that we
1205 * don't measure any activity that happens in the completion
1206 * routine, which in the case of sendfile can be quite
1209 cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
1210 xpt_release_ccb(done_ccb);
1211 ndaschedule(periph);
1212 cam_periph_unlock(periph);
1214 } else { /* state == NDA_CCB_TRIM */
1215 struct nda_trim_request *trim;
1216 struct bio *bp1, *bp2;
1217 TAILQ_HEAD(, bio) queue;
1219 trim = nvmeio->ccb_trim;
1221 TAILQ_CONCAT(&queue, &trim->bps, bio_queue);
1222 free(trim, M_NVMEDA);
1225 * Since we can have multiple trims in flight, we don't
1226 * need to call this here.
1227 * cam_iosched_trim_done(softc->cam_iosched);
1230 * The the I/O scheduler that we're finishing the I/O
1231 * so we can keep book. The first one we pass in the CCB
1232 * which has the timing information. The rest we pass in NULL
1233 * so we can keep proper counts.
1235 bp1 = TAILQ_FIRST(&queue);
1236 cam_iosched_bio_complete(softc->cam_iosched, bp1, done_ccb);
1237 xpt_release_ccb(done_ccb);
1238 softc->outstanding_cmds--;
1239 ndaschedule(periph);
1240 cam_periph_unlock(periph);
1241 while ((bp2 = TAILQ_FIRST(&queue)) != NULL) {
1242 TAILQ_REMOVE(&queue, bp2, bio_queue);
1243 bp2->bio_error = error;
1245 bp2->bio_flags |= BIO_ERROR;
1246 bp2->bio_resid = bp1->bio_bcount;
1250 cam_iosched_bio_complete(softc->cam_iosched, bp2, NULL);
1257 /* No-op. We're polling */
1264 xpt_release_ccb(done_ccb);
1268 ndaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1270 struct nda_softc *softc;
1271 struct cam_periph *periph;
1273 periph = xpt_path_periph(ccb->ccb_h.path);
1274 softc = (struct nda_softc *)periph->softc;
1276 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1277 case CAM_CMD_TIMEOUT:
1282 case CAM_REQ_ABORTED:
1283 case CAM_REQ_CMP_ERR:
1284 case CAM_REQ_TERMIO:
1285 case CAM_UNREC_HBA_ERROR:
1286 case CAM_DATA_RUN_ERR:
1287 case CAM_ATA_STATUS_ERROR:
1296 return(cam_periph_error(ccb, cam_flags, sense_flags));
1300 * Step through all NDA peripheral drivers, and if the device is still open,
1301 * sync the disk cache to physical media.
1306 struct cam_periph *periph;
1307 struct nda_softc *softc;
1311 CAM_PERIPH_FOREACH(periph, &ndadriver) {
1312 softc = (struct nda_softc *)periph->softc;
1314 if (SCHEDULER_STOPPED()) {
1316 * If we paniced with the lock held or the periph is not
1317 * open, do not recurse. Otherwise, call ndadump since
1318 * that avoids the sleeping cam_periph_getccb does if no
1319 * CCBs are available.
1321 if (!cam_periph_owned(periph) &&
1322 (softc->flags & NDA_FLAG_OPEN)) {
1323 ndadump(softc->disk, NULL, 0, 0, 0);
1329 * We only sync the cache if the drive is still open
1331 cam_periph_lock(periph);
1332 if ((softc->flags & NDA_FLAG_OPEN) == 0) {
1333 cam_periph_unlock(periph);
1337 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1338 nda_nvme_flush(softc, &ccb->nvmeio);
1339 error = cam_periph_runccb(ccb, ndaerror, /*cam_flags*/0,
1340 /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
1341 softc->disk->d_devstat);
1343 xpt_print(periph->path, "Synchronize cache failed\n");
1344 xpt_release_ccb(ccb);
1345 cam_periph_unlock(periph);
1350 ndashutdown(void *arg, int howto)
1357 ndasuspend(void *arg)