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