xref: /titanic_41/usr/src/uts/common/io/nvme/nvme.c (revision 9cc1456618cebf391268f35c45cf2489772832e0)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2016 Nexenta Systems, Inc. All rights reserved.
14  * Copyright 2016 Tegile Systems, Inc. All rights reserved.
15  * Copyright (c) 2016 The MathWorks, Inc.  All rights reserved.
16  * Copyright 2018 Joyent, Inc.
17  */
18 
19 /*
20  * blkdev driver for NVMe compliant storage devices
21  *
22  * This driver was written to conform to version 1.2.1 of the NVMe
23  * specification.  It may work with newer versions, but that is completely
24  * untested and disabled by default.
25  *
26  * The driver has only been tested on x86 systems and will not work on big-
27  * endian systems without changes to the code accessing registers and data
28  * structures used by the hardware.
29  *
30  *
31  * Interrupt Usage:
32  *
33  * The driver will use a single interrupt while configuring the device as the
34  * specification requires, but contrary to the specification it will try to use
35  * a single-message MSI(-X) or FIXED interrupt. Later in the attach process it
36  * will switch to multiple-message MSI(-X) if supported. The driver wants to
37  * have one interrupt vector per CPU, but it will work correctly if less are
38  * available. Interrupts can be shared by queues, the interrupt handler will
39  * iterate through the I/O queue array by steps of n_intr_cnt. Usually only
40  * the admin queue will share an interrupt with one I/O queue. The interrupt
41  * handler will retrieve completed commands from all queues sharing an interrupt
42  * vector and will post them to a taskq for completion processing.
43  *
44  *
45  * Command Processing:
46  *
47  * NVMe devices can have up to 65535 I/O queue pairs, with each queue holding up
48  * to 65536 I/O commands. The driver will configure one I/O queue pair per
49  * available interrupt vector, with the queue length usually much smaller than
50  * the maximum of 65536. If the hardware doesn't provide enough queues, fewer
51  * interrupt vectors will be used.
52  *
53  * Additionally the hardware provides a single special admin queue pair that can
54  * hold up to 4096 admin commands.
55  *
56  * From the hardware perspective both queues of a queue pair are independent,
57  * but they share some driver state: the command array (holding pointers to
58  * commands currently being processed by the hardware) and the active command
59  * counter. Access to a queue pair and the shared state is protected by
60  * nq_mutex.
61  *
62  * When a command is submitted to a queue pair the active command counter is
63  * incremented and a pointer to the command is stored in the command array. The
64  * array index is used as command identifier (CID) in the submission queue
65  * entry. Some commands may take a very long time to complete, and if the queue
66  * wraps around in that time a submission may find the next array slot to still
67  * be used by a long-running command. In this case the array is sequentially
68  * searched for the next free slot. The length of the command array is the same
69  * as the configured queue length. Queue overrun is prevented by the semaphore,
70  * so a command submission may block if the queue is full.
71  *
72  *
73  * Polled I/O Support:
74  *
75  * For kernel core dump support the driver can do polled I/O. As interrupts are
76  * turned off while dumping the driver will just submit a command in the regular
77  * way, and then repeatedly attempt a command retrieval until it gets the
78  * command back.
79  *
80  *
81  * Namespace Support:
82  *
83  * NVMe devices can have multiple namespaces, each being a independent data
84  * store. The driver supports multiple namespaces and creates a blkdev interface
85  * for each namespace found. Namespaces can have various attributes to support
86  * thin provisioning and protection information. This driver does not support
87  * any of this and ignores namespaces that have these attributes.
88  *
89  * As of NVMe 1.1 namespaces can have an 64bit Extended Unique Identifier
90  * (EUI64). This driver uses the EUI64 if present to generate the devid and
91  * passes it to blkdev to use it in the device node names. As this is currently
92  * untested namespaces with EUI64 are ignored by default.
93  *
94  * We currently support only (2 << NVME_MINOR_INST_SHIFT) - 2 namespaces in a
95  * single controller. This is an artificial limit imposed by the driver to be
96  * able to address a reasonable number of controllers and namespaces using a
97  * 32bit minor node number.
98  *
99  *
100  * Minor nodes:
101  *
102  * For each NVMe device the driver exposes one minor node for the controller and
103  * one minor node for each namespace. The only operations supported by those
104  * minor nodes are open(9E), close(9E), and ioctl(9E). This serves as the
105  * interface for the nvmeadm(1M) utility.
106  *
107  *
108  * Blkdev Interface:
109  *
110  * This driver uses blkdev to do all the heavy lifting involved with presenting
111  * a disk device to the system. As a result, the processing of I/O requests is
112  * relatively simple as blkdev takes care of partitioning, boundary checks, DMA
113  * setup, and splitting of transfers into manageable chunks.
114  *
115  * I/O requests coming in from blkdev are turned into NVM commands and posted to
116  * an I/O queue. The queue is selected by taking the CPU id modulo the number of
117  * queues. There is currently no timeout handling of I/O commands.
118  *
119  * Blkdev also supports querying device/media information and generating a
120  * devid. The driver reports the best block size as determined by the namespace
121  * format back to blkdev as physical block size to support partition and block
122  * alignment. The devid is either based on the namespace EUI64, if present, or
123  * composed using the device vendor ID, model number, serial number, and the
124  * namespace ID.
125  *
126  *
127  * Error Handling:
128  *
129  * Error handling is currently limited to detecting fatal hardware errors,
130  * either by asynchronous events, or synchronously through command status or
131  * admin command timeouts. In case of severe errors the device is fenced off,
132  * all further requests will return EIO. FMA is then called to fault the device.
133  *
134  * The hardware has a limit for outstanding asynchronous event requests. Before
135  * this limit is known the driver assumes it is at least 1 and posts a single
136  * asynchronous request. Later when the limit is known more asynchronous event
137  * requests are posted to allow quicker reception of error information. When an
138  * asynchronous event is posted by the hardware the driver will parse the error
139  * status fields and log information or fault the device, depending on the
140  * severity of the asynchronous event. The asynchronous event request is then
141  * reused and posted to the admin queue again.
142  *
143  * On command completion the command status is checked for errors. In case of
144  * errors indicating a driver bug the driver panics. Almost all other error
145  * status values just cause EIO to be returned.
146  *
147  * Command timeouts are currently detected for all admin commands except
148  * asynchronous event requests. If a command times out and the hardware appears
149  * to be healthy the driver attempts to abort the command. The original command
150  * timeout is also applied to the abort command. If the abort times out too the
151  * driver assumes the device to be dead, fences it off, and calls FMA to retire
152  * it. In all other cases the aborted command should return immediately with a
153  * status indicating it was aborted, and the driver will wait indefinitely for
154  * that to happen. No timeout handling of normal I/O commands is presently done.
155  *
156  * Any command that times out due to the controller dropping dead will be put on
157  * nvme_lost_cmds list if it references DMA memory. This will prevent the DMA
158  * memory being reused by the system and later be written to by a "dead" NVMe
159  * controller.
160  *
161  *
162  * Locking:
163  *
164  * Each queue pair has its own nq_mutex, which must be held when accessing the
165  * associated queue registers or the shared state of the queue pair. Callers of
166  * nvme_unqueue_cmd() must make sure that nq_mutex is held, while
167  * nvme_submit_{admin,io}_cmd() and nvme_retrieve_cmd() take care of this
168  * themselves.
169  *
170  * Each command also has its own nc_mutex, which is associated with the
171  * condition variable nc_cv. It is only used on admin commands which are run
172  * synchronously. In that case it must be held across calls to
173  * nvme_submit_{admin,io}_cmd() and nvme_wait_cmd(), which is taken care of by
174  * nvme_admin_cmd(). It must also be held whenever the completion state of the
175  * command is changed or while a admin command timeout is handled.
176  *
177  * If both nc_mutex and nq_mutex must be held, nc_mutex must be acquired first.
178  * More than one nc_mutex may only be held when aborting commands. In this case,
179  * the nc_mutex of the command to be aborted must be held across the call to
180  * nvme_abort_cmd() to prevent the command from completing while the abort is in
181  * progress.
182  *
183  * Each minor node has its own nm_mutex, which protects the open count nm_ocnt
184  * and exclusive-open flag nm_oexcl.
185  *
186  *
187  * Quiesce / Fast Reboot:
188  *
189  * The driver currently does not support fast reboot. A quiesce(9E) entry point
190  * is still provided which is used to send a shutdown notification to the
191  * device.
192  *
193  *
194  * Driver Configuration:
195  *
196  * The following driver properties can be changed to control some aspects of the
197  * drivers operation:
198  * - strict-version: can be set to 0 to allow devices conforming to newer
199  *   major versions to be used
200  * - ignore-unknown-vendor-status: can be set to 1 to not handle any vendor
201  *   specific command status as a fatal error leading device faulting
202  * - admin-queue-len: the maximum length of the admin queue (16-4096)
203  * - io-queue-len: the maximum length of the I/O queues (16-65536)
204  * - async-event-limit: the maximum number of asynchronous event requests to be
205  *   posted by the driver
206  * - volatile-write-cache-enable: can be set to 0 to disable the volatile write
207  *   cache
208  * - min-phys-block-size: the minimum physical block size to report to blkdev,
209  *   which is among other things the basis for ZFS vdev ashift
210  *
211  *
212  * TODO:
213  * - figure out sane default for I/O queue depth reported to blkdev
214  * - FMA handling of media errors
215  * - support for devices supporting very large I/O requests using chained PRPs
216  * - support for configuring hardware parameters like interrupt coalescing
217  * - support for media formatting and hard partitioning into namespaces
218  * - support for big-endian systems
219  * - support for fast reboot
220  * - support for firmware updates
221  * - support for NVMe Subsystem Reset (1.1)
222  * - support for Scatter/Gather lists (1.1)
223  * - support for Reservations (1.1)
224  * - support for power management
225  */
226 
227 #include <sys/byteorder.h>
228 #ifdef _BIG_ENDIAN
229 #error nvme driver needs porting for big-endian platforms
230 #endif
231 
232 #include <sys/modctl.h>
233 #include <sys/conf.h>
234 #include <sys/devops.h>
235 #include <sys/ddi.h>
236 #include <sys/sunddi.h>
237 #include <sys/sunndi.h>
238 #include <sys/bitmap.h>
239 #include <sys/sysmacros.h>
240 #include <sys/param.h>
241 #include <sys/varargs.h>
242 #include <sys/cpuvar.h>
243 #include <sys/disp.h>
244 #include <sys/blkdev.h>
245 #include <sys/atomic.h>
246 #include <sys/archsystm.h>
247 #include <sys/sata/sata_hba.h>
248 #include <sys/stat.h>
249 #include <sys/policy.h>
250 #include <sys/list.h>
251 
252 #include <sys/nvme.h>
253 
254 #ifdef __x86
255 #include <sys/x86_archext.h>
256 #endif
257 
258 #include "nvme_reg.h"
259 #include "nvme_var.h"
260 
261 /*
262  * Assertions to make sure that we've properly captured various aspects of the
263  * packed structures and haven't broken them during updates.
264  */
265 CTASSERT(sizeof (nvme_identify_ctrl_t) == 0x1000);
266 CTASSERT(offsetof(nvme_identify_ctrl_t, id_oacs) == 256);
267 CTASSERT(offsetof(nvme_identify_ctrl_t, id_sqes) == 512);
268 CTASSERT(offsetof(nvme_identify_ctrl_t, id_subnqn) == 768);
269 CTASSERT(offsetof(nvme_identify_ctrl_t, id_nvmof) == 1792);
270 CTASSERT(offsetof(nvme_identify_ctrl_t, id_psd) == 2048);
271 CTASSERT(offsetof(nvme_identify_ctrl_t, id_vs) == 3072);
272 
273 CTASSERT(sizeof (nvme_identify_nsid_t) == 0x1000);
274 CTASSERT(offsetof(nvme_identify_nsid_t, id_fpi) == 32);
275 CTASSERT(offsetof(nvme_identify_nsid_t, id_nguid) == 104);
276 CTASSERT(offsetof(nvme_identify_nsid_t, id_lbaf) == 128);
277 CTASSERT(offsetof(nvme_identify_nsid_t, id_vs) == 384);
278 
279 CTASSERT(sizeof (nvme_identify_primary_caps_t) == 0x1000);
280 CTASSERT(offsetof(nvme_identify_primary_caps_t, nipc_vqfrt) == 32);
281 CTASSERT(offsetof(nvme_identify_primary_caps_t, nipc_vifrt) == 64);
282 
283 
284 /* NVMe spec version supported */
285 static const int nvme_version_major = 1;
286 
287 /* tunable for admin command timeout in seconds, default is 1s */
288 int nvme_admin_cmd_timeout = 1;
289 
290 /* tunable for FORMAT NVM command timeout in seconds, default is 600s */
291 int nvme_format_cmd_timeout = 600;
292 
293 static int nvme_attach(dev_info_t *, ddi_attach_cmd_t);
294 static int nvme_detach(dev_info_t *, ddi_detach_cmd_t);
295 static int nvme_quiesce(dev_info_t *);
296 static int nvme_fm_errcb(dev_info_t *, ddi_fm_error_t *, const void *);
297 static int nvme_setup_interrupts(nvme_t *, int, int);
298 static void nvme_release_interrupts(nvme_t *);
299 static uint_t nvme_intr(caddr_t, caddr_t);
300 
301 static void nvme_shutdown(nvme_t *, int, boolean_t);
302 static boolean_t nvme_reset(nvme_t *, boolean_t);
303 static int nvme_init(nvme_t *);
304 static nvme_cmd_t *nvme_alloc_cmd(nvme_t *, int);
305 static void nvme_free_cmd(nvme_cmd_t *);
306 static nvme_cmd_t *nvme_create_nvm_cmd(nvme_namespace_t *, uint8_t,
307     bd_xfer_t *);
308 static void nvme_admin_cmd(nvme_cmd_t *, int);
309 static void nvme_submit_admin_cmd(nvme_qpair_t *, nvme_cmd_t *);
310 static int nvme_submit_io_cmd(nvme_qpair_t *, nvme_cmd_t *);
311 static void nvme_submit_cmd_common(nvme_qpair_t *, nvme_cmd_t *);
312 static nvme_cmd_t *nvme_unqueue_cmd(nvme_t *, nvme_qpair_t *, int);
313 static nvme_cmd_t *nvme_retrieve_cmd(nvme_t *, nvme_qpair_t *);
314 static void nvme_wait_cmd(nvme_cmd_t *, uint_t);
315 static void nvme_wakeup_cmd(void *);
316 static void nvme_async_event_task(void *);
317 
318 static int nvme_check_unknown_cmd_status(nvme_cmd_t *);
319 static int nvme_check_vendor_cmd_status(nvme_cmd_t *);
320 static int nvme_check_integrity_cmd_status(nvme_cmd_t *);
321 static int nvme_check_specific_cmd_status(nvme_cmd_t *);
322 static int nvme_check_generic_cmd_status(nvme_cmd_t *);
323 static inline int nvme_check_cmd_status(nvme_cmd_t *);
324 
325 static int nvme_abort_cmd(nvme_cmd_t *, uint_t);
326 static void nvme_async_event(nvme_t *);
327 static int nvme_format_nvm(nvme_t *, uint32_t, uint8_t, boolean_t, uint8_t,
328     boolean_t, uint8_t);
329 static int nvme_get_logpage(nvme_t *, void **, size_t *, uint8_t, ...);
330 static int nvme_identify(nvme_t *, uint32_t, void **);
331 static int nvme_set_features(nvme_t *, uint32_t, uint8_t, uint32_t,
332     uint32_t *);
333 static int nvme_get_features(nvme_t *, uint32_t, uint8_t, uint32_t *,
334     void **, size_t *);
335 static int nvme_write_cache_set(nvme_t *, boolean_t);
336 static int nvme_set_nqueues(nvme_t *, uint16_t *);
337 
338 static void nvme_free_dma(nvme_dma_t *);
339 static int nvme_zalloc_dma(nvme_t *, size_t, uint_t, ddi_dma_attr_t *,
340     nvme_dma_t **);
341 static int nvme_zalloc_queue_dma(nvme_t *, uint32_t, uint16_t, uint_t,
342     nvme_dma_t **);
343 static void nvme_free_qpair(nvme_qpair_t *);
344 static int nvme_alloc_qpair(nvme_t *, uint32_t, nvme_qpair_t **, int);
345 static int nvme_create_io_qpair(nvme_t *, nvme_qpair_t *, uint16_t);
346 
347 static inline void nvme_put64(nvme_t *, uintptr_t, uint64_t);
348 static inline void nvme_put32(nvme_t *, uintptr_t, uint32_t);
349 static inline uint64_t nvme_get64(nvme_t *, uintptr_t);
350 static inline uint32_t nvme_get32(nvme_t *, uintptr_t);
351 
352 static boolean_t nvme_check_regs_hdl(nvme_t *);
353 static boolean_t nvme_check_dma_hdl(nvme_dma_t *);
354 
355 static int nvme_fill_prp(nvme_cmd_t *, bd_xfer_t *);
356 
357 static void nvme_bd_xfer_done(void *);
358 static void nvme_bd_driveinfo(void *, bd_drive_t *);
359 static int nvme_bd_mediainfo(void *, bd_media_t *);
360 static int nvme_bd_cmd(nvme_namespace_t *, bd_xfer_t *, uint8_t);
361 static int nvme_bd_read(void *, bd_xfer_t *);
362 static int nvme_bd_write(void *, bd_xfer_t *);
363 static int nvme_bd_sync(void *, bd_xfer_t *);
364 static int nvme_bd_devid(void *, dev_info_t *, ddi_devid_t *);
365 
366 static int nvme_prp_dma_constructor(void *, void *, int);
367 static void nvme_prp_dma_destructor(void *, void *);
368 
369 static void nvme_prepare_devid(nvme_t *, uint32_t);
370 
371 static int nvme_open(dev_t *, int, int, cred_t *);
372 static int nvme_close(dev_t, int, int, cred_t *);
373 static int nvme_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
374 
375 #define	NVME_MINOR_INST_SHIFT	9
376 #define	NVME_MINOR(inst, nsid)	(((inst) << NVME_MINOR_INST_SHIFT) | (nsid))
377 #define	NVME_MINOR_INST(minor)	((minor) >> NVME_MINOR_INST_SHIFT)
378 #define	NVME_MINOR_NSID(minor)	((minor) & ((1 << NVME_MINOR_INST_SHIFT) - 1))
379 #define	NVME_MINOR_MAX		(NVME_MINOR(1, 0) - 2)
380 
381 static void *nvme_state;
382 static kmem_cache_t *nvme_cmd_cache;
383 
384 /*
385  * DMA attributes for queue DMA memory
386  *
387  * Queue DMA memory must be page aligned. The maximum length of a queue is
388  * 65536 entries, and an entry can be 64 bytes long.
389  */
390 static ddi_dma_attr_t nvme_queue_dma_attr = {
391 	.dma_attr_version	= DMA_ATTR_V0,
392 	.dma_attr_addr_lo	= 0,
393 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
394 	.dma_attr_count_max	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t) - 1,
395 	.dma_attr_align		= 0x1000,
396 	.dma_attr_burstsizes	= 0x7ff,
397 	.dma_attr_minxfer	= 0x1000,
398 	.dma_attr_maxxfer	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t),
399 	.dma_attr_seg		= 0xffffffffffffffffULL,
400 	.dma_attr_sgllen	= 1,
401 	.dma_attr_granular	= 1,
402 	.dma_attr_flags		= 0,
403 };
404 
405 /*
406  * DMA attributes for transfers using Physical Region Page (PRP) entries
407  *
408  * A PRP entry describes one page of DMA memory using the page size specified
409  * in the controller configuration's memory page size register (CC.MPS). It uses
410  * a 64bit base address aligned to this page size. There is no limitation on
411  * chaining PRPs together for arbitrarily large DMA transfers.
412  */
413 static ddi_dma_attr_t nvme_prp_dma_attr = {
414 	.dma_attr_version	= DMA_ATTR_V0,
415 	.dma_attr_addr_lo	= 0,
416 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
417 	.dma_attr_count_max	= 0xfff,
418 	.dma_attr_align		= 0x1000,
419 	.dma_attr_burstsizes	= 0x7ff,
420 	.dma_attr_minxfer	= 0x1000,
421 	.dma_attr_maxxfer	= 0x1000,
422 	.dma_attr_seg		= 0xfff,
423 	.dma_attr_sgllen	= -1,
424 	.dma_attr_granular	= 1,
425 	.dma_attr_flags		= 0,
426 };
427 
428 /*
429  * DMA attributes for transfers using scatter/gather lists
430  *
431  * A SGL entry describes a chunk of DMA memory using a 64bit base address and a
432  * 32bit length field. SGL Segment and SGL Last Segment entries require the
433  * length to be a multiple of 16 bytes.
434  */
435 static ddi_dma_attr_t nvme_sgl_dma_attr = {
436 	.dma_attr_version	= DMA_ATTR_V0,
437 	.dma_attr_addr_lo	= 0,
438 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
439 	.dma_attr_count_max	= 0xffffffffUL,
440 	.dma_attr_align		= 1,
441 	.dma_attr_burstsizes	= 0x7ff,
442 	.dma_attr_minxfer	= 0x10,
443 	.dma_attr_maxxfer	= 0xfffffffffULL,
444 	.dma_attr_seg		= 0xffffffffffffffffULL,
445 	.dma_attr_sgllen	= -1,
446 	.dma_attr_granular	= 0x10,
447 	.dma_attr_flags		= 0
448 };
449 
450 static ddi_device_acc_attr_t nvme_reg_acc_attr = {
451 	.devacc_attr_version	= DDI_DEVICE_ATTR_V0,
452 	.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
453 	.devacc_attr_dataorder	= DDI_STRICTORDER_ACC
454 };
455 
456 static struct cb_ops nvme_cb_ops = {
457 	.cb_open	= nvme_open,
458 	.cb_close	= nvme_close,
459 	.cb_strategy	= nodev,
460 	.cb_print	= nodev,
461 	.cb_dump	= nodev,
462 	.cb_read	= nodev,
463 	.cb_write	= nodev,
464 	.cb_ioctl	= nvme_ioctl,
465 	.cb_devmap	= nodev,
466 	.cb_mmap	= nodev,
467 	.cb_segmap	= nodev,
468 	.cb_chpoll	= nochpoll,
469 	.cb_prop_op	= ddi_prop_op,
470 	.cb_str		= 0,
471 	.cb_flag	= D_NEW | D_MP,
472 	.cb_rev		= CB_REV,
473 	.cb_aread	= nodev,
474 	.cb_awrite	= nodev
475 };
476 
477 static struct dev_ops nvme_dev_ops = {
478 	.devo_rev	= DEVO_REV,
479 	.devo_refcnt	= 0,
480 	.devo_getinfo	= ddi_no_info,
481 	.devo_identify	= nulldev,
482 	.devo_probe	= nulldev,
483 	.devo_attach	= nvme_attach,
484 	.devo_detach	= nvme_detach,
485 	.devo_reset	= nodev,
486 	.devo_cb_ops	= &nvme_cb_ops,
487 	.devo_bus_ops	= NULL,
488 	.devo_power	= NULL,
489 	.devo_quiesce	= nvme_quiesce,
490 };
491 
492 static struct modldrv nvme_modldrv = {
493 	.drv_modops	= &mod_driverops,
494 	.drv_linkinfo	= "NVMe v1.1b",
495 	.drv_dev_ops	= &nvme_dev_ops
496 };
497 
498 static struct modlinkage nvme_modlinkage = {
499 	.ml_rev		= MODREV_1,
500 	.ml_linkage	= { &nvme_modldrv, NULL }
501 };
502 
503 static bd_ops_t nvme_bd_ops = {
504 	.o_version	= BD_OPS_VERSION_0,
505 	.o_drive_info	= nvme_bd_driveinfo,
506 	.o_media_info	= nvme_bd_mediainfo,
507 	.o_devid_init	= nvme_bd_devid,
508 	.o_sync_cache	= nvme_bd_sync,
509 	.o_read		= nvme_bd_read,
510 	.o_write	= nvme_bd_write,
511 };
512 
513 /*
514  * This list will hold commands that have timed out and couldn't be aborted.
515  * As we don't know what the hardware may still do with the DMA memory we can't
516  * free them, so we'll keep them forever on this list where we can easily look
517  * at them with mdb.
518  */
519 static struct list nvme_lost_cmds;
520 static kmutex_t nvme_lc_mutex;
521 
522 int
_init(void)523 _init(void)
524 {
525 	int error;
526 
527 	error = ddi_soft_state_init(&nvme_state, sizeof (nvme_t), 1);
528 	if (error != DDI_SUCCESS)
529 		return (error);
530 
531 	nvme_cmd_cache = kmem_cache_create("nvme_cmd_cache",
532 	    sizeof (nvme_cmd_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
533 
534 	mutex_init(&nvme_lc_mutex, NULL, MUTEX_DRIVER, NULL);
535 	list_create(&nvme_lost_cmds, sizeof (nvme_cmd_t),
536 	    offsetof(nvme_cmd_t, nc_list));
537 
538 	bd_mod_init(&nvme_dev_ops);
539 
540 	error = mod_install(&nvme_modlinkage);
541 	if (error != DDI_SUCCESS) {
542 		ddi_soft_state_fini(&nvme_state);
543 		mutex_destroy(&nvme_lc_mutex);
544 		list_destroy(&nvme_lost_cmds);
545 		bd_mod_fini(&nvme_dev_ops);
546 	}
547 
548 	return (error);
549 }
550 
551 int
_fini(void)552 _fini(void)
553 {
554 	int error;
555 
556 	if (!list_is_empty(&nvme_lost_cmds))
557 		return (DDI_FAILURE);
558 
559 	error = mod_remove(&nvme_modlinkage);
560 	if (error == DDI_SUCCESS) {
561 		ddi_soft_state_fini(&nvme_state);
562 		kmem_cache_destroy(nvme_cmd_cache);
563 		mutex_destroy(&nvme_lc_mutex);
564 		list_destroy(&nvme_lost_cmds);
565 		bd_mod_fini(&nvme_dev_ops);
566 	}
567 
568 	return (error);
569 }
570 
571 int
_info(struct modinfo * modinfop)572 _info(struct modinfo *modinfop)
573 {
574 	return (mod_info(&nvme_modlinkage, modinfop));
575 }
576 
577 static inline void
nvme_put64(nvme_t * nvme,uintptr_t reg,uint64_t val)578 nvme_put64(nvme_t *nvme, uintptr_t reg, uint64_t val)
579 {
580 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
581 
582 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
583 	ddi_put64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg), val);
584 }
585 
586 static inline void
nvme_put32(nvme_t * nvme,uintptr_t reg,uint32_t val)587 nvme_put32(nvme_t *nvme, uintptr_t reg, uint32_t val)
588 {
589 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
590 
591 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
592 	ddi_put32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg), val);
593 }
594 
595 static inline uint64_t
nvme_get64(nvme_t * nvme,uintptr_t reg)596 nvme_get64(nvme_t *nvme, uintptr_t reg)
597 {
598 	uint64_t val;
599 
600 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
601 
602 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
603 	val = ddi_get64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg));
604 
605 	return (val);
606 }
607 
608 static inline uint32_t
nvme_get32(nvme_t * nvme,uintptr_t reg)609 nvme_get32(nvme_t *nvme, uintptr_t reg)
610 {
611 	uint32_t val;
612 
613 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
614 
615 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
616 	val = ddi_get32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg));
617 
618 	return (val);
619 }
620 
621 static boolean_t
nvme_check_regs_hdl(nvme_t * nvme)622 nvme_check_regs_hdl(nvme_t *nvme)
623 {
624 	ddi_fm_error_t error;
625 
626 	ddi_fm_acc_err_get(nvme->n_regh, &error, DDI_FME_VERSION);
627 
628 	if (error.fme_status != DDI_FM_OK)
629 		return (B_TRUE);
630 
631 	return (B_FALSE);
632 }
633 
634 static boolean_t
nvme_check_dma_hdl(nvme_dma_t * dma)635 nvme_check_dma_hdl(nvme_dma_t *dma)
636 {
637 	ddi_fm_error_t error;
638 
639 	if (dma == NULL)
640 		return (B_FALSE);
641 
642 	ddi_fm_dma_err_get(dma->nd_dmah, &error, DDI_FME_VERSION);
643 
644 	if (error.fme_status != DDI_FM_OK)
645 		return (B_TRUE);
646 
647 	return (B_FALSE);
648 }
649 
650 static void
nvme_free_dma_common(nvme_dma_t * dma)651 nvme_free_dma_common(nvme_dma_t *dma)
652 {
653 	if (dma->nd_dmah != NULL)
654 		(void) ddi_dma_unbind_handle(dma->nd_dmah);
655 	if (dma->nd_acch != NULL)
656 		ddi_dma_mem_free(&dma->nd_acch);
657 	if (dma->nd_dmah != NULL)
658 		ddi_dma_free_handle(&dma->nd_dmah);
659 }
660 
661 static void
nvme_free_dma(nvme_dma_t * dma)662 nvme_free_dma(nvme_dma_t *dma)
663 {
664 	nvme_free_dma_common(dma);
665 	kmem_free(dma, sizeof (*dma));
666 }
667 
668 /* ARGSUSED */
669 static void
nvme_prp_dma_destructor(void * buf,void * private)670 nvme_prp_dma_destructor(void *buf, void *private)
671 {
672 	nvme_dma_t *dma = (nvme_dma_t *)buf;
673 
674 	nvme_free_dma_common(dma);
675 }
676 
677 static int
nvme_alloc_dma_common(nvme_t * nvme,nvme_dma_t * dma,size_t len,uint_t flags,ddi_dma_attr_t * dma_attr)678 nvme_alloc_dma_common(nvme_t *nvme, nvme_dma_t *dma,
679     size_t len, uint_t flags, ddi_dma_attr_t *dma_attr)
680 {
681 	if (ddi_dma_alloc_handle(nvme->n_dip, dma_attr, DDI_DMA_SLEEP, NULL,
682 	    &dma->nd_dmah) != DDI_SUCCESS) {
683 		/*
684 		 * Due to DDI_DMA_SLEEP this can't be DDI_DMA_NORESOURCES, and
685 		 * the only other possible error is DDI_DMA_BADATTR which
686 		 * indicates a driver bug which should cause a panic.
687 		 */
688 		dev_err(nvme->n_dip, CE_PANIC,
689 		    "!failed to get DMA handle, check DMA attributes");
690 		return (DDI_FAILURE);
691 	}
692 
693 	/*
694 	 * ddi_dma_mem_alloc() can only fail when DDI_DMA_NOSLEEP is specified
695 	 * or the flags are conflicting, which isn't the case here.
696 	 */
697 	(void) ddi_dma_mem_alloc(dma->nd_dmah, len, &nvme->n_reg_acc_attr,
698 	    DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, &dma->nd_memp,
699 	    &dma->nd_len, &dma->nd_acch);
700 
701 	if (ddi_dma_addr_bind_handle(dma->nd_dmah, NULL, dma->nd_memp,
702 	    dma->nd_len, flags | DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL,
703 	    &dma->nd_cookie, &dma->nd_ncookie) != DDI_DMA_MAPPED) {
704 		dev_err(nvme->n_dip, CE_WARN,
705 		    "!failed to bind DMA memory");
706 		atomic_inc_32(&nvme->n_dma_bind_err);
707 		nvme_free_dma_common(dma);
708 		return (DDI_FAILURE);
709 	}
710 
711 	return (DDI_SUCCESS);
712 }
713 
714 static int
nvme_zalloc_dma(nvme_t * nvme,size_t len,uint_t flags,ddi_dma_attr_t * dma_attr,nvme_dma_t ** ret)715 nvme_zalloc_dma(nvme_t *nvme, size_t len, uint_t flags,
716     ddi_dma_attr_t *dma_attr, nvme_dma_t **ret)
717 {
718 	nvme_dma_t *dma = kmem_zalloc(sizeof (nvme_dma_t), KM_SLEEP);
719 
720 	if (nvme_alloc_dma_common(nvme, dma, len, flags, dma_attr) !=
721 	    DDI_SUCCESS) {
722 		*ret = NULL;
723 		kmem_free(dma, sizeof (nvme_dma_t));
724 		return (DDI_FAILURE);
725 	}
726 
727 	bzero(dma->nd_memp, dma->nd_len);
728 
729 	*ret = dma;
730 	return (DDI_SUCCESS);
731 }
732 
733 /* ARGSUSED */
734 static int
nvme_prp_dma_constructor(void * buf,void * private,int flags)735 nvme_prp_dma_constructor(void *buf, void *private, int flags)
736 {
737 	nvme_dma_t *dma = (nvme_dma_t *)buf;
738 	nvme_t *nvme = (nvme_t *)private;
739 
740 	dma->nd_dmah = NULL;
741 	dma->nd_acch = NULL;
742 
743 	if (nvme_alloc_dma_common(nvme, dma, nvme->n_pagesize,
744 	    DDI_DMA_READ, &nvme->n_prp_dma_attr) != DDI_SUCCESS) {
745 		return (-1);
746 	}
747 
748 	ASSERT(dma->nd_ncookie == 1);
749 
750 	dma->nd_cached = B_TRUE;
751 
752 	return (0);
753 }
754 
755 static int
nvme_zalloc_queue_dma(nvme_t * nvme,uint32_t nentry,uint16_t qe_len,uint_t flags,nvme_dma_t ** dma)756 nvme_zalloc_queue_dma(nvme_t *nvme, uint32_t nentry, uint16_t qe_len,
757     uint_t flags, nvme_dma_t **dma)
758 {
759 	uint32_t len = nentry * qe_len;
760 	ddi_dma_attr_t q_dma_attr = nvme->n_queue_dma_attr;
761 
762 	len = roundup(len, nvme->n_pagesize);
763 
764 	q_dma_attr.dma_attr_minxfer = len;
765 
766 	if (nvme_zalloc_dma(nvme, len, flags, &q_dma_attr, dma)
767 	    != DDI_SUCCESS) {
768 		dev_err(nvme->n_dip, CE_WARN,
769 		    "!failed to get DMA memory for queue");
770 		goto fail;
771 	}
772 
773 	if ((*dma)->nd_ncookie != 1) {
774 		dev_err(nvme->n_dip, CE_WARN,
775 		    "!got too many cookies for queue DMA");
776 		goto fail;
777 	}
778 
779 	return (DDI_SUCCESS);
780 
781 fail:
782 	if (*dma) {
783 		nvme_free_dma(*dma);
784 		*dma = NULL;
785 	}
786 
787 	return (DDI_FAILURE);
788 }
789 
790 static void
nvme_free_qpair(nvme_qpair_t * qp)791 nvme_free_qpair(nvme_qpair_t *qp)
792 {
793 	int i;
794 
795 	mutex_destroy(&qp->nq_mutex);
796 	sema_destroy(&qp->nq_sema);
797 
798 	if (qp->nq_sqdma != NULL)
799 		nvme_free_dma(qp->nq_sqdma);
800 	if (qp->nq_cqdma != NULL)
801 		nvme_free_dma(qp->nq_cqdma);
802 
803 	if (qp->nq_active_cmds > 0)
804 		for (i = 0; i != qp->nq_nentry; i++)
805 			if (qp->nq_cmd[i] != NULL)
806 				nvme_free_cmd(qp->nq_cmd[i]);
807 
808 	if (qp->nq_cmd != NULL)
809 		kmem_free(qp->nq_cmd, sizeof (nvme_cmd_t *) * qp->nq_nentry);
810 
811 	kmem_free(qp, sizeof (nvme_qpair_t));
812 }
813 
814 static int
nvme_alloc_qpair(nvme_t * nvme,uint32_t nentry,nvme_qpair_t ** nqp,int idx)815 nvme_alloc_qpair(nvme_t *nvme, uint32_t nentry, nvme_qpair_t **nqp,
816     int idx)
817 {
818 	nvme_qpair_t *qp = kmem_zalloc(sizeof (*qp), KM_SLEEP);
819 
820 	mutex_init(&qp->nq_mutex, NULL, MUTEX_DRIVER,
821 	    DDI_INTR_PRI(nvme->n_intr_pri));
822 	sema_init(&qp->nq_sema, nentry, NULL, SEMA_DRIVER, NULL);
823 
824 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_sqe_t),
825 	    DDI_DMA_WRITE, &qp->nq_sqdma) != DDI_SUCCESS)
826 		goto fail;
827 
828 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_cqe_t),
829 	    DDI_DMA_READ, &qp->nq_cqdma) != DDI_SUCCESS)
830 		goto fail;
831 
832 	qp->nq_sq = (nvme_sqe_t *)qp->nq_sqdma->nd_memp;
833 	qp->nq_cq = (nvme_cqe_t *)qp->nq_cqdma->nd_memp;
834 	qp->nq_nentry = nentry;
835 
836 	qp->nq_sqtdbl = NVME_REG_SQTDBL(nvme, idx);
837 	qp->nq_cqhdbl = NVME_REG_CQHDBL(nvme, idx);
838 
839 	qp->nq_cmd = kmem_zalloc(sizeof (nvme_cmd_t *) * nentry, KM_SLEEP);
840 	qp->nq_next_cmd = 0;
841 
842 	*nqp = qp;
843 	return (DDI_SUCCESS);
844 
845 fail:
846 	nvme_free_qpair(qp);
847 	*nqp = NULL;
848 
849 	return (DDI_FAILURE);
850 }
851 
852 static nvme_cmd_t *
nvme_alloc_cmd(nvme_t * nvme,int kmflag)853 nvme_alloc_cmd(nvme_t *nvme, int kmflag)
854 {
855 	nvme_cmd_t *cmd = kmem_cache_alloc(nvme_cmd_cache, kmflag);
856 
857 	if (cmd == NULL)
858 		return (cmd);
859 
860 	bzero(cmd, sizeof (nvme_cmd_t));
861 
862 	cmd->nc_nvme = nvme;
863 
864 	mutex_init(&cmd->nc_mutex, NULL, MUTEX_DRIVER,
865 	    DDI_INTR_PRI(nvme->n_intr_pri));
866 	cv_init(&cmd->nc_cv, NULL, CV_DRIVER, NULL);
867 
868 	return (cmd);
869 }
870 
871 static void
nvme_free_cmd(nvme_cmd_t * cmd)872 nvme_free_cmd(nvme_cmd_t *cmd)
873 {
874 	/* Don't free commands on the lost commands list. */
875 	if (list_link_active(&cmd->nc_list))
876 		return;
877 
878 	if (cmd->nc_dma) {
879 		if (cmd->nc_dma->nd_cached)
880 			kmem_cache_free(cmd->nc_nvme->n_prp_cache,
881 			    cmd->nc_dma);
882 		else
883 			nvme_free_dma(cmd->nc_dma);
884 		cmd->nc_dma = NULL;
885 	}
886 
887 	cv_destroy(&cmd->nc_cv);
888 	mutex_destroy(&cmd->nc_mutex);
889 
890 	kmem_cache_free(nvme_cmd_cache, cmd);
891 }
892 
893 static void
nvme_submit_admin_cmd(nvme_qpair_t * qp,nvme_cmd_t * cmd)894 nvme_submit_admin_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd)
895 {
896 	sema_p(&qp->nq_sema);
897 	nvme_submit_cmd_common(qp, cmd);
898 }
899 
900 static int
nvme_submit_io_cmd(nvme_qpair_t * qp,nvme_cmd_t * cmd)901 nvme_submit_io_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd)
902 {
903 	if (sema_tryp(&qp->nq_sema) == 0)
904 		return (EAGAIN);
905 
906 	nvme_submit_cmd_common(qp, cmd);
907 	return (0);
908 }
909 
910 static void
nvme_submit_cmd_common(nvme_qpair_t * qp,nvme_cmd_t * cmd)911 nvme_submit_cmd_common(nvme_qpair_t *qp, nvme_cmd_t *cmd)
912 {
913 	nvme_reg_sqtdbl_t tail = { 0 };
914 
915 	mutex_enter(&qp->nq_mutex);
916 	cmd->nc_completed = B_FALSE;
917 
918 	/*
919 	 * Try to insert the cmd into the active cmd array at the nq_next_cmd
920 	 * slot. If the slot is already occupied advance to the next slot and
921 	 * try again. This can happen for long running commands like async event
922 	 * requests.
923 	 */
924 	while (qp->nq_cmd[qp->nq_next_cmd] != NULL)
925 		qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
926 	qp->nq_cmd[qp->nq_next_cmd] = cmd;
927 
928 	qp->nq_active_cmds++;
929 
930 	cmd->nc_sqe.sqe_cid = qp->nq_next_cmd;
931 	bcopy(&cmd->nc_sqe, &qp->nq_sq[qp->nq_sqtail], sizeof (nvme_sqe_t));
932 	(void) ddi_dma_sync(qp->nq_sqdma->nd_dmah,
933 	    sizeof (nvme_sqe_t) * qp->nq_sqtail,
934 	    sizeof (nvme_sqe_t), DDI_DMA_SYNC_FORDEV);
935 	qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
936 
937 	tail.b.sqtdbl_sqt = qp->nq_sqtail = (qp->nq_sqtail + 1) % qp->nq_nentry;
938 	nvme_put32(cmd->nc_nvme, qp->nq_sqtdbl, tail.r);
939 
940 	mutex_exit(&qp->nq_mutex);
941 }
942 
943 static nvme_cmd_t *
nvme_unqueue_cmd(nvme_t * nvme,nvme_qpair_t * qp,int cid)944 nvme_unqueue_cmd(nvme_t *nvme, nvme_qpair_t *qp, int cid)
945 {
946 	nvme_cmd_t *cmd;
947 
948 	ASSERT(mutex_owned(&qp->nq_mutex));
949 	ASSERT3S(cid, <, qp->nq_nentry);
950 
951 	cmd = qp->nq_cmd[cid];
952 	qp->nq_cmd[cid] = NULL;
953 	ASSERT3U(qp->nq_active_cmds, >, 0);
954 	qp->nq_active_cmds--;
955 	sema_v(&qp->nq_sema);
956 
957 	ASSERT3P(cmd, !=, NULL);
958 	ASSERT3P(cmd->nc_nvme, ==, nvme);
959 	ASSERT3S(cmd->nc_sqe.sqe_cid, ==, cid);
960 
961 	return (cmd);
962 }
963 
964 static nvme_cmd_t *
nvme_retrieve_cmd(nvme_t * nvme,nvme_qpair_t * qp)965 nvme_retrieve_cmd(nvme_t *nvme, nvme_qpair_t *qp)
966 {
967 	nvme_reg_cqhdbl_t head = { 0 };
968 
969 	nvme_cqe_t *cqe;
970 	nvme_cmd_t *cmd;
971 
972 	(void) ddi_dma_sync(qp->nq_cqdma->nd_dmah, 0,
973 	    sizeof (nvme_cqe_t) * qp->nq_nentry, DDI_DMA_SYNC_FORKERNEL);
974 
975 	mutex_enter(&qp->nq_mutex);
976 	cqe = &qp->nq_cq[qp->nq_cqhead];
977 
978 	/* Check phase tag of CQE. Hardware inverts it for new entries. */
979 	if (cqe->cqe_sf.sf_p == qp->nq_phase) {
980 		mutex_exit(&qp->nq_mutex);
981 		return (NULL);
982 	}
983 
984 	ASSERT(nvme->n_ioq[cqe->cqe_sqid] == qp);
985 
986 	cmd = nvme_unqueue_cmd(nvme, qp, cqe->cqe_cid);
987 
988 	ASSERT(cmd->nc_sqid == cqe->cqe_sqid);
989 	bcopy(cqe, &cmd->nc_cqe, sizeof (nvme_cqe_t));
990 
991 	qp->nq_sqhead = cqe->cqe_sqhd;
992 
993 	head.b.cqhdbl_cqh = qp->nq_cqhead = (qp->nq_cqhead + 1) % qp->nq_nentry;
994 
995 	/* Toggle phase on wrap-around. */
996 	if (qp->nq_cqhead == 0)
997 		qp->nq_phase = qp->nq_phase ? 0 : 1;
998 
999 	nvme_put32(cmd->nc_nvme, qp->nq_cqhdbl, head.r);
1000 	mutex_exit(&qp->nq_mutex);
1001 
1002 	return (cmd);
1003 }
1004 
1005 static int
nvme_check_unknown_cmd_status(nvme_cmd_t * cmd)1006 nvme_check_unknown_cmd_status(nvme_cmd_t *cmd)
1007 {
1008 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1009 
1010 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1011 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
1012 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
1013 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
1014 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
1015 
1016 	if (cmd->nc_xfer != NULL)
1017 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1018 
1019 	if (cmd->nc_nvme->n_strict_version) {
1020 		cmd->nc_nvme->n_dead = B_TRUE;
1021 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
1022 	}
1023 
1024 	return (EIO);
1025 }
1026 
1027 static int
nvme_check_vendor_cmd_status(nvme_cmd_t * cmd)1028 nvme_check_vendor_cmd_status(nvme_cmd_t *cmd)
1029 {
1030 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1031 
1032 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1033 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
1034 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
1035 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
1036 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
1037 	if (!cmd->nc_nvme->n_ignore_unknown_vendor_status) {
1038 		cmd->nc_nvme->n_dead = B_TRUE;
1039 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
1040 	}
1041 
1042 	return (EIO);
1043 }
1044 
1045 static int
nvme_check_integrity_cmd_status(nvme_cmd_t * cmd)1046 nvme_check_integrity_cmd_status(nvme_cmd_t *cmd)
1047 {
1048 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1049 
1050 	switch (cqe->cqe_sf.sf_sc) {
1051 	case NVME_CQE_SC_INT_NVM_WRITE:
1052 		/* write fail */
1053 		/* TODO: post ereport */
1054 		if (cmd->nc_xfer != NULL)
1055 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
1056 		return (EIO);
1057 
1058 	case NVME_CQE_SC_INT_NVM_READ:
1059 		/* read fail */
1060 		/* TODO: post ereport */
1061 		if (cmd->nc_xfer != NULL)
1062 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
1063 		return (EIO);
1064 
1065 	default:
1066 		return (nvme_check_unknown_cmd_status(cmd));
1067 	}
1068 }
1069 
1070 static int
nvme_check_generic_cmd_status(nvme_cmd_t * cmd)1071 nvme_check_generic_cmd_status(nvme_cmd_t *cmd)
1072 {
1073 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1074 
1075 	switch (cqe->cqe_sf.sf_sc) {
1076 	case NVME_CQE_SC_GEN_SUCCESS:
1077 		return (0);
1078 
1079 	/*
1080 	 * Errors indicating a bug in the driver should cause a panic.
1081 	 */
1082 	case NVME_CQE_SC_GEN_INV_OPC:
1083 		/* Invalid Command Opcode */
1084 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1085 		    "invalid opcode in cmd %p", (void *)cmd);
1086 		return (0);
1087 
1088 	case NVME_CQE_SC_GEN_INV_FLD:
1089 		/* Invalid Field in Command */
1090 		if (!cmd->nc_dontpanic)
1091 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
1092 			    "programming error: invalid field in cmd %p",
1093 			    (void *)cmd);
1094 		return (EIO);
1095 
1096 	case NVME_CQE_SC_GEN_ID_CNFL:
1097 		/* Command ID Conflict */
1098 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1099 		    "cmd ID conflict in cmd %p", (void *)cmd);
1100 		return (0);
1101 
1102 	case NVME_CQE_SC_GEN_INV_NS:
1103 		/* Invalid Namespace or Format */
1104 		if (!cmd->nc_dontpanic)
1105 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
1106 			    "programming error: " "invalid NS/format in cmd %p",
1107 			    (void *)cmd);
1108 		return (EINVAL);
1109 
1110 	case NVME_CQE_SC_GEN_NVM_LBA_RANGE:
1111 		/* LBA Out Of Range */
1112 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1113 		    "LBA out of range in cmd %p", (void *)cmd);
1114 		return (0);
1115 
1116 	/*
1117 	 * Non-fatal errors, handle gracefully.
1118 	 */
1119 	case NVME_CQE_SC_GEN_DATA_XFR_ERR:
1120 		/* Data Transfer Error (DMA) */
1121 		/* TODO: post ereport */
1122 		atomic_inc_32(&cmd->nc_nvme->n_data_xfr_err);
1123 		if (cmd->nc_xfer != NULL)
1124 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1125 		return (EIO);
1126 
1127 	case NVME_CQE_SC_GEN_INTERNAL_ERR:
1128 		/*
1129 		 * Internal Error. The spec (v1.0, section 4.5.1.2) says
1130 		 * detailed error information is returned as async event,
1131 		 * so we pretty much ignore the error here and handle it
1132 		 * in the async event handler.
1133 		 */
1134 		atomic_inc_32(&cmd->nc_nvme->n_internal_err);
1135 		if (cmd->nc_xfer != NULL)
1136 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1137 		return (EIO);
1138 
1139 	case NVME_CQE_SC_GEN_ABORT_REQUEST:
1140 		/*
1141 		 * Command Abort Requested. This normally happens only when a
1142 		 * command times out.
1143 		 */
1144 		/* TODO: post ereport or change blkdev to handle this? */
1145 		atomic_inc_32(&cmd->nc_nvme->n_abort_rq_err);
1146 		return (ECANCELED);
1147 
1148 	case NVME_CQE_SC_GEN_ABORT_PWRLOSS:
1149 		/* Command Aborted due to Power Loss Notification */
1150 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
1151 		cmd->nc_nvme->n_dead = B_TRUE;
1152 		return (EIO);
1153 
1154 	case NVME_CQE_SC_GEN_ABORT_SQ_DEL:
1155 		/* Command Aborted due to SQ Deletion */
1156 		atomic_inc_32(&cmd->nc_nvme->n_abort_sq_del);
1157 		return (EIO);
1158 
1159 	case NVME_CQE_SC_GEN_NVM_CAP_EXC:
1160 		/* Capacity Exceeded */
1161 		atomic_inc_32(&cmd->nc_nvme->n_nvm_cap_exc);
1162 		if (cmd->nc_xfer != NULL)
1163 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
1164 		return (EIO);
1165 
1166 	case NVME_CQE_SC_GEN_NVM_NS_NOTRDY:
1167 		/* Namespace Not Ready */
1168 		atomic_inc_32(&cmd->nc_nvme->n_nvm_ns_notrdy);
1169 		if (cmd->nc_xfer != NULL)
1170 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1171 		return (EIO);
1172 
1173 	default:
1174 		return (nvme_check_unknown_cmd_status(cmd));
1175 	}
1176 }
1177 
1178 static int
nvme_check_specific_cmd_status(nvme_cmd_t * cmd)1179 nvme_check_specific_cmd_status(nvme_cmd_t *cmd)
1180 {
1181 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1182 
1183 	switch (cqe->cqe_sf.sf_sc) {
1184 	case NVME_CQE_SC_SPC_INV_CQ:
1185 		/* Completion Queue Invalid */
1186 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE);
1187 		atomic_inc_32(&cmd->nc_nvme->n_inv_cq_err);
1188 		return (EINVAL);
1189 
1190 	case NVME_CQE_SC_SPC_INV_QID:
1191 		/* Invalid Queue Identifier */
1192 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
1193 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_SQUEUE ||
1194 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE ||
1195 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
1196 		atomic_inc_32(&cmd->nc_nvme->n_inv_qid_err);
1197 		return (EINVAL);
1198 
1199 	case NVME_CQE_SC_SPC_MAX_QSZ_EXC:
1200 		/* Max Queue Size Exceeded */
1201 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
1202 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
1203 		atomic_inc_32(&cmd->nc_nvme->n_max_qsz_exc);
1204 		return (EINVAL);
1205 
1206 	case NVME_CQE_SC_SPC_ABRT_CMD_EXC:
1207 		/* Abort Command Limit Exceeded */
1208 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT);
1209 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1210 		    "abort command limit exceeded in cmd %p", (void *)cmd);
1211 		return (0);
1212 
1213 	case NVME_CQE_SC_SPC_ASYNC_EVREQ_EXC:
1214 		/* Async Event Request Limit Exceeded */
1215 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ASYNC_EVENT);
1216 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1217 		    "async event request limit exceeded in cmd %p",
1218 		    (void *)cmd);
1219 		return (0);
1220 
1221 	case NVME_CQE_SC_SPC_INV_INT_VECT:
1222 		/* Invalid Interrupt Vector */
1223 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
1224 		atomic_inc_32(&cmd->nc_nvme->n_inv_int_vect);
1225 		return (EINVAL);
1226 
1227 	case NVME_CQE_SC_SPC_INV_LOG_PAGE:
1228 		/* Invalid Log Page */
1229 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_GET_LOG_PAGE);
1230 		atomic_inc_32(&cmd->nc_nvme->n_inv_log_page);
1231 		return (EINVAL);
1232 
1233 	case NVME_CQE_SC_SPC_INV_FORMAT:
1234 		/* Invalid Format */
1235 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_FORMAT);
1236 		atomic_inc_32(&cmd->nc_nvme->n_inv_format);
1237 		if (cmd->nc_xfer != NULL)
1238 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1239 		return (EINVAL);
1240 
1241 	case NVME_CQE_SC_SPC_INV_Q_DEL:
1242 		/* Invalid Queue Deletion */
1243 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
1244 		atomic_inc_32(&cmd->nc_nvme->n_inv_q_del);
1245 		return (EINVAL);
1246 
1247 	case NVME_CQE_SC_SPC_NVM_CNFL_ATTR:
1248 		/* Conflicting Attributes */
1249 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_DSET_MGMT ||
1250 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
1251 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1252 		atomic_inc_32(&cmd->nc_nvme->n_cnfl_attr);
1253 		if (cmd->nc_xfer != NULL)
1254 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1255 		return (EINVAL);
1256 
1257 	case NVME_CQE_SC_SPC_NVM_INV_PROT:
1258 		/* Invalid Protection Information */
1259 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_COMPARE ||
1260 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
1261 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1262 		atomic_inc_32(&cmd->nc_nvme->n_inv_prot);
1263 		if (cmd->nc_xfer != NULL)
1264 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1265 		return (EINVAL);
1266 
1267 	case NVME_CQE_SC_SPC_NVM_READONLY:
1268 		/* Write to Read Only Range */
1269 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1270 		atomic_inc_32(&cmd->nc_nvme->n_readonly);
1271 		if (cmd->nc_xfer != NULL)
1272 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1273 		return (EROFS);
1274 
1275 	default:
1276 		return (nvme_check_unknown_cmd_status(cmd));
1277 	}
1278 }
1279 
1280 static inline int
nvme_check_cmd_status(nvme_cmd_t * cmd)1281 nvme_check_cmd_status(nvme_cmd_t *cmd)
1282 {
1283 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1284 
1285 	/*
1286 	 * Take a shortcut if the controller is dead, or if
1287 	 * command status indicates no error.
1288 	 */
1289 	if (cmd->nc_nvme->n_dead)
1290 		return (EIO);
1291 
1292 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1293 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
1294 		return (0);
1295 
1296 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC)
1297 		return (nvme_check_generic_cmd_status(cmd));
1298 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC)
1299 		return (nvme_check_specific_cmd_status(cmd));
1300 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY)
1301 		return (nvme_check_integrity_cmd_status(cmd));
1302 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR)
1303 		return (nvme_check_vendor_cmd_status(cmd));
1304 
1305 	return (nvme_check_unknown_cmd_status(cmd));
1306 }
1307 
1308 static int
nvme_abort_cmd(nvme_cmd_t * abort_cmd,uint_t sec)1309 nvme_abort_cmd(nvme_cmd_t *abort_cmd, uint_t sec)
1310 {
1311 	nvme_t *nvme = abort_cmd->nc_nvme;
1312 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1313 	nvme_abort_cmd_t ac = { 0 };
1314 	int ret = 0;
1315 
1316 	sema_p(&nvme->n_abort_sema);
1317 
1318 	ac.b.ac_cid = abort_cmd->nc_sqe.sqe_cid;
1319 	ac.b.ac_sqid = abort_cmd->nc_sqid;
1320 
1321 	cmd->nc_sqid = 0;
1322 	cmd->nc_sqe.sqe_opc = NVME_OPC_ABORT;
1323 	cmd->nc_callback = nvme_wakeup_cmd;
1324 	cmd->nc_sqe.sqe_cdw10 = ac.r;
1325 
1326 	/*
1327 	 * Send the ABORT to the hardware. The ABORT command will return _after_
1328 	 * the aborted command has completed (aborted or otherwise), but since
1329 	 * we still hold the aborted command's mutex its callback hasn't been
1330 	 * processed yet.
1331 	 */
1332 	nvme_admin_cmd(cmd, sec);
1333 	sema_v(&nvme->n_abort_sema);
1334 
1335 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1336 		dev_err(nvme->n_dip, CE_WARN,
1337 		    "!ABORT failed with sct = %x, sc = %x",
1338 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1339 		atomic_inc_32(&nvme->n_abort_failed);
1340 	} else {
1341 		dev_err(nvme->n_dip, CE_WARN,
1342 		    "!ABORT of command %d/%d %ssuccessful",
1343 		    abort_cmd->nc_sqe.sqe_cid, abort_cmd->nc_sqid,
1344 		    cmd->nc_cqe.cqe_dw0 & 1 ? "un" : "");
1345 		if ((cmd->nc_cqe.cqe_dw0 & 1) == 0)
1346 			atomic_inc_32(&nvme->n_cmd_aborted);
1347 	}
1348 
1349 	nvme_free_cmd(cmd);
1350 	return (ret);
1351 }
1352 
1353 /*
1354  * nvme_wait_cmd -- wait for command completion or timeout
1355  *
1356  * In case of a serious error or a timeout of the abort command the hardware
1357  * will be declared dead and FMA will be notified.
1358  */
1359 static void
nvme_wait_cmd(nvme_cmd_t * cmd,uint_t sec)1360 nvme_wait_cmd(nvme_cmd_t *cmd, uint_t sec)
1361 {
1362 	clock_t timeout = ddi_get_lbolt() + drv_usectohz(sec * MICROSEC);
1363 	nvme_t *nvme = cmd->nc_nvme;
1364 	nvme_reg_csts_t csts;
1365 	nvme_qpair_t *qp;
1366 
1367 	ASSERT(mutex_owned(&cmd->nc_mutex));
1368 
1369 	while (!cmd->nc_completed) {
1370 		if (cv_timedwait(&cmd->nc_cv, &cmd->nc_mutex, timeout) == -1)
1371 			break;
1372 	}
1373 
1374 	if (cmd->nc_completed)
1375 		return;
1376 
1377 	/*
1378 	 * The command timed out.
1379 	 *
1380 	 * Check controller for fatal status, any errors associated with the
1381 	 * register or DMA handle, or for a double timeout (abort command timed
1382 	 * out). If necessary log a warning and call FMA.
1383 	 */
1384 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1385 	dev_err(nvme->n_dip, CE_WARN, "!command %d/%d timeout, "
1386 	    "OPC = %x, CFS = %d", cmd->nc_sqe.sqe_cid, cmd->nc_sqid,
1387 	    cmd->nc_sqe.sqe_opc, csts.b.csts_cfs);
1388 	atomic_inc_32(&nvme->n_cmd_timeout);
1389 
1390 	if (csts.b.csts_cfs ||
1391 	    nvme_check_regs_hdl(nvme) ||
1392 	    nvme_check_dma_hdl(cmd->nc_dma) ||
1393 	    cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT) {
1394 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1395 		nvme->n_dead = B_TRUE;
1396 	} else if (nvme_abort_cmd(cmd, sec) == 0) {
1397 		/*
1398 		 * If the abort succeeded the command should complete
1399 		 * immediately with an appropriate status.
1400 		 */
1401 		while (!cmd->nc_completed)
1402 			cv_wait(&cmd->nc_cv, &cmd->nc_mutex);
1403 
1404 		return;
1405 	}
1406 
1407 	qp = nvme->n_ioq[cmd->nc_sqid];
1408 
1409 	mutex_enter(&qp->nq_mutex);
1410 	(void) nvme_unqueue_cmd(nvme, qp, cmd->nc_sqe.sqe_cid);
1411 	mutex_exit(&qp->nq_mutex);
1412 
1413 	/*
1414 	 * As we don't know what the presumed dead hardware might still do with
1415 	 * the DMA memory, we'll put the command on the lost commands list if it
1416 	 * has any DMA memory.
1417 	 */
1418 	if (cmd->nc_dma != NULL) {
1419 		mutex_enter(&nvme_lc_mutex);
1420 		list_insert_head(&nvme_lost_cmds, cmd);
1421 		mutex_exit(&nvme_lc_mutex);
1422 	}
1423 }
1424 
1425 static void
nvme_wakeup_cmd(void * arg)1426 nvme_wakeup_cmd(void *arg)
1427 {
1428 	nvme_cmd_t *cmd = arg;
1429 
1430 	mutex_enter(&cmd->nc_mutex);
1431 	cmd->nc_completed = B_TRUE;
1432 	cv_signal(&cmd->nc_cv);
1433 	mutex_exit(&cmd->nc_mutex);
1434 }
1435 
1436 static void
nvme_async_event_task(void * arg)1437 nvme_async_event_task(void *arg)
1438 {
1439 	nvme_cmd_t *cmd = arg;
1440 	nvme_t *nvme = cmd->nc_nvme;
1441 	nvme_error_log_entry_t *error_log = NULL;
1442 	nvme_health_log_t *health_log = NULL;
1443 	size_t logsize = 0;
1444 	nvme_async_event_t event;
1445 
1446 	/*
1447 	 * Check for errors associated with the async request itself. The only
1448 	 * command-specific error is "async event limit exceeded", which
1449 	 * indicates a programming error in the driver and causes a panic in
1450 	 * nvme_check_cmd_status().
1451 	 *
1452 	 * Other possible errors are various scenarios where the async request
1453 	 * was aborted, or internal errors in the device. Internal errors are
1454 	 * reported to FMA, the command aborts need no special handling here.
1455 	 */
1456 	if (nvme_check_cmd_status(cmd) != 0) {
1457 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1458 		    "!async event request returned failure, sct = %x, "
1459 		    "sc = %x, dnr = %d, m = %d", cmd->nc_cqe.cqe_sf.sf_sct,
1460 		    cmd->nc_cqe.cqe_sf.sf_sc, cmd->nc_cqe.cqe_sf.sf_dnr,
1461 		    cmd->nc_cqe.cqe_sf.sf_m);
1462 
1463 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1464 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INTERNAL_ERR) {
1465 			cmd->nc_nvme->n_dead = B_TRUE;
1466 			ddi_fm_service_impact(cmd->nc_nvme->n_dip,
1467 			    DDI_SERVICE_LOST);
1468 		}
1469 		nvme_free_cmd(cmd);
1470 		return;
1471 	}
1472 
1473 
1474 	event.r = cmd->nc_cqe.cqe_dw0;
1475 
1476 	/* Clear CQE and re-submit the async request. */
1477 	bzero(&cmd->nc_cqe, sizeof (nvme_cqe_t));
1478 	nvme_submit_admin_cmd(nvme->n_adminq, cmd);
1479 
1480 	switch (event.b.ae_type) {
1481 	case NVME_ASYNC_TYPE_ERROR:
1482 		if (event.b.ae_logpage == NVME_LOGPAGE_ERROR) {
1483 			(void) nvme_get_logpage(nvme, (void **)&error_log,
1484 			    &logsize, event.b.ae_logpage);
1485 		} else {
1486 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1487 			    "async event reply: %d", event.b.ae_logpage);
1488 			atomic_inc_32(&nvme->n_wrong_logpage);
1489 		}
1490 
1491 		switch (event.b.ae_info) {
1492 		case NVME_ASYNC_ERROR_INV_SQ:
1493 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1494 			    "invalid submission queue");
1495 			return;
1496 
1497 		case NVME_ASYNC_ERROR_INV_DBL:
1498 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1499 			    "invalid doorbell write value");
1500 			return;
1501 
1502 		case NVME_ASYNC_ERROR_DIAGFAIL:
1503 			dev_err(nvme->n_dip, CE_WARN, "!diagnostic failure");
1504 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1505 			nvme->n_dead = B_TRUE;
1506 			atomic_inc_32(&nvme->n_diagfail_event);
1507 			break;
1508 
1509 		case NVME_ASYNC_ERROR_PERSISTENT:
1510 			dev_err(nvme->n_dip, CE_WARN, "!persistent internal "
1511 			    "device error");
1512 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1513 			nvme->n_dead = B_TRUE;
1514 			atomic_inc_32(&nvme->n_persistent_event);
1515 			break;
1516 
1517 		case NVME_ASYNC_ERROR_TRANSIENT:
1518 			dev_err(nvme->n_dip, CE_WARN, "!transient internal "
1519 			    "device error");
1520 			/* TODO: send ereport */
1521 			atomic_inc_32(&nvme->n_transient_event);
1522 			break;
1523 
1524 		case NVME_ASYNC_ERROR_FW_LOAD:
1525 			dev_err(nvme->n_dip, CE_WARN,
1526 			    "!firmware image load error");
1527 			atomic_inc_32(&nvme->n_fw_load_event);
1528 			break;
1529 		}
1530 		break;
1531 
1532 	case NVME_ASYNC_TYPE_HEALTH:
1533 		if (event.b.ae_logpage == NVME_LOGPAGE_HEALTH) {
1534 			(void) nvme_get_logpage(nvme, (void **)&health_log,
1535 			    &logsize, event.b.ae_logpage, -1);
1536 		} else {
1537 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1538 			    "async event reply: %d", event.b.ae_logpage);
1539 			atomic_inc_32(&nvme->n_wrong_logpage);
1540 		}
1541 
1542 		switch (event.b.ae_info) {
1543 		case NVME_ASYNC_HEALTH_RELIABILITY:
1544 			dev_err(nvme->n_dip, CE_WARN,
1545 			    "!device reliability compromised");
1546 			/* TODO: send ereport */
1547 			atomic_inc_32(&nvme->n_reliability_event);
1548 			break;
1549 
1550 		case NVME_ASYNC_HEALTH_TEMPERATURE:
1551 			dev_err(nvme->n_dip, CE_WARN,
1552 			    "!temperature above threshold");
1553 			/* TODO: send ereport */
1554 			atomic_inc_32(&nvme->n_temperature_event);
1555 			break;
1556 
1557 		case NVME_ASYNC_HEALTH_SPARE:
1558 			dev_err(nvme->n_dip, CE_WARN,
1559 			    "!spare space below threshold");
1560 			/* TODO: send ereport */
1561 			atomic_inc_32(&nvme->n_spare_event);
1562 			break;
1563 		}
1564 		break;
1565 
1566 	case NVME_ASYNC_TYPE_VENDOR:
1567 		dev_err(nvme->n_dip, CE_WARN, "!vendor specific async event "
1568 		    "received, info = %x, logpage = %x", event.b.ae_info,
1569 		    event.b.ae_logpage);
1570 		atomic_inc_32(&nvme->n_vendor_event);
1571 		break;
1572 
1573 	default:
1574 		dev_err(nvme->n_dip, CE_WARN, "!unknown async event received, "
1575 		    "type = %x, info = %x, logpage = %x", event.b.ae_type,
1576 		    event.b.ae_info, event.b.ae_logpage);
1577 		atomic_inc_32(&nvme->n_unknown_event);
1578 		break;
1579 	}
1580 
1581 	if (error_log)
1582 		kmem_free(error_log, logsize);
1583 
1584 	if (health_log)
1585 		kmem_free(health_log, logsize);
1586 }
1587 
1588 static void
nvme_admin_cmd(nvme_cmd_t * cmd,int sec)1589 nvme_admin_cmd(nvme_cmd_t *cmd, int sec)
1590 {
1591 	mutex_enter(&cmd->nc_mutex);
1592 	nvme_submit_admin_cmd(cmd->nc_nvme->n_adminq, cmd);
1593 	nvme_wait_cmd(cmd, sec);
1594 	mutex_exit(&cmd->nc_mutex);
1595 }
1596 
1597 static void
nvme_async_event(nvme_t * nvme)1598 nvme_async_event(nvme_t *nvme)
1599 {
1600 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1601 
1602 	cmd->nc_sqid = 0;
1603 	cmd->nc_sqe.sqe_opc = NVME_OPC_ASYNC_EVENT;
1604 	cmd->nc_callback = nvme_async_event_task;
1605 
1606 	nvme_submit_admin_cmd(nvme->n_adminq, cmd);
1607 }
1608 
1609 static int
nvme_format_nvm(nvme_t * nvme,uint32_t nsid,uint8_t lbaf,boolean_t ms,uint8_t pi,boolean_t pil,uint8_t ses)1610 nvme_format_nvm(nvme_t *nvme, uint32_t nsid, uint8_t lbaf, boolean_t ms,
1611     uint8_t pi, boolean_t pil, uint8_t ses)
1612 {
1613 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1614 	nvme_format_nvm_t format_nvm = { 0 };
1615 	int ret;
1616 
1617 	format_nvm.b.fm_lbaf = lbaf & 0xf;
1618 	format_nvm.b.fm_ms = ms ? 1 : 0;
1619 	format_nvm.b.fm_pi = pi & 0x7;
1620 	format_nvm.b.fm_pil = pil ? 1 : 0;
1621 	format_nvm.b.fm_ses = ses & 0x7;
1622 
1623 	cmd->nc_sqid = 0;
1624 	cmd->nc_callback = nvme_wakeup_cmd;
1625 	cmd->nc_sqe.sqe_nsid = nsid;
1626 	cmd->nc_sqe.sqe_opc = NVME_OPC_NVM_FORMAT;
1627 	cmd->nc_sqe.sqe_cdw10 = format_nvm.r;
1628 
1629 	/*
1630 	 * Some devices like Samsung SM951 don't allow formatting of all
1631 	 * namespaces in one command. Handle that gracefully.
1632 	 */
1633 	if (nsid == (uint32_t)-1)
1634 		cmd->nc_dontpanic = B_TRUE;
1635 
1636 	nvme_admin_cmd(cmd, nvme_format_cmd_timeout);
1637 
1638 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1639 		dev_err(nvme->n_dip, CE_WARN,
1640 		    "!FORMAT failed with sct = %x, sc = %x",
1641 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1642 	}
1643 
1644 	nvme_free_cmd(cmd);
1645 	return (ret);
1646 }
1647 
1648 static int
nvme_get_logpage(nvme_t * nvme,void ** buf,size_t * bufsize,uint8_t logpage,...)1649 nvme_get_logpage(nvme_t *nvme, void **buf, size_t *bufsize, uint8_t logpage,
1650     ...)
1651 {
1652 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1653 	nvme_getlogpage_t getlogpage = { 0 };
1654 	va_list ap;
1655 	int ret;
1656 
1657 	va_start(ap, logpage);
1658 
1659 	cmd->nc_sqid = 0;
1660 	cmd->nc_callback = nvme_wakeup_cmd;
1661 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_LOG_PAGE;
1662 
1663 	getlogpage.b.lp_lid = logpage;
1664 
1665 	switch (logpage) {
1666 	case NVME_LOGPAGE_ERROR:
1667 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1668 		/*
1669 		 * The GET LOG PAGE command can use at most 2 pages to return
1670 		 * data, PRP lists are not supported.
1671 		 */
1672 		*bufsize = MIN(2 * nvme->n_pagesize,
1673 		    nvme->n_error_log_len * sizeof (nvme_error_log_entry_t));
1674 		break;
1675 
1676 	case NVME_LOGPAGE_HEALTH:
1677 		cmd->nc_sqe.sqe_nsid = va_arg(ap, uint32_t);
1678 		*bufsize = sizeof (nvme_health_log_t);
1679 		break;
1680 
1681 	case NVME_LOGPAGE_FWSLOT:
1682 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1683 		*bufsize = sizeof (nvme_fwslot_log_t);
1684 		break;
1685 
1686 	default:
1687 		dev_err(nvme->n_dip, CE_WARN, "!unknown log page requested: %d",
1688 		    logpage);
1689 		atomic_inc_32(&nvme->n_unknown_logpage);
1690 		ret = EINVAL;
1691 		goto fail;
1692 	}
1693 
1694 	va_end(ap);
1695 
1696 	getlogpage.b.lp_numd = *bufsize / sizeof (uint32_t) - 1;
1697 
1698 	cmd->nc_sqe.sqe_cdw10 = getlogpage.r;
1699 
1700 	if (nvme_zalloc_dma(nvme, getlogpage.b.lp_numd * sizeof (uint32_t),
1701 	    DDI_DMA_READ, &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1702 		dev_err(nvme->n_dip, CE_WARN,
1703 		    "!nvme_zalloc_dma failed for GET LOG PAGE");
1704 		ret = ENOMEM;
1705 		goto fail;
1706 	}
1707 
1708 	if (cmd->nc_dma->nd_ncookie > 2) {
1709 		dev_err(nvme->n_dip, CE_WARN,
1710 		    "!too many DMA cookies for GET LOG PAGE");
1711 		atomic_inc_32(&nvme->n_too_many_cookies);
1712 		ret = ENOMEM;
1713 		goto fail;
1714 	}
1715 
1716 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1717 	if (cmd->nc_dma->nd_ncookie > 1) {
1718 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1719 		    &cmd->nc_dma->nd_cookie);
1720 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1721 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1722 	}
1723 
1724 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
1725 
1726 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1727 		dev_err(nvme->n_dip, CE_WARN,
1728 		    "!GET LOG PAGE failed with sct = %x, sc = %x",
1729 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1730 		goto fail;
1731 	}
1732 
1733 	*buf = kmem_alloc(*bufsize, KM_SLEEP);
1734 	bcopy(cmd->nc_dma->nd_memp, *buf, *bufsize);
1735 
1736 fail:
1737 	nvme_free_cmd(cmd);
1738 
1739 	return (ret);
1740 }
1741 
1742 static int
nvme_identify(nvme_t * nvme,uint32_t nsid,void ** buf)1743 nvme_identify(nvme_t *nvme, uint32_t nsid, void **buf)
1744 {
1745 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1746 	int ret;
1747 
1748 	if (buf == NULL)
1749 		return (EINVAL);
1750 
1751 	cmd->nc_sqid = 0;
1752 	cmd->nc_callback = nvme_wakeup_cmd;
1753 	cmd->nc_sqe.sqe_opc = NVME_OPC_IDENTIFY;
1754 	cmd->nc_sqe.sqe_nsid = nsid;
1755 	cmd->nc_sqe.sqe_cdw10 = nsid ? NVME_IDENTIFY_NSID : NVME_IDENTIFY_CTRL;
1756 
1757 	if (nvme_zalloc_dma(nvme, NVME_IDENTIFY_BUFSIZE, DDI_DMA_READ,
1758 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1759 		dev_err(nvme->n_dip, CE_WARN,
1760 		    "!nvme_zalloc_dma failed for IDENTIFY");
1761 		ret = ENOMEM;
1762 		goto fail;
1763 	}
1764 
1765 	if (cmd->nc_dma->nd_ncookie > 2) {
1766 		dev_err(nvme->n_dip, CE_WARN,
1767 		    "!too many DMA cookies for IDENTIFY");
1768 		atomic_inc_32(&nvme->n_too_many_cookies);
1769 		ret = ENOMEM;
1770 		goto fail;
1771 	}
1772 
1773 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1774 	if (cmd->nc_dma->nd_ncookie > 1) {
1775 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1776 		    &cmd->nc_dma->nd_cookie);
1777 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1778 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1779 	}
1780 
1781 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
1782 
1783 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1784 		dev_err(nvme->n_dip, CE_WARN,
1785 		    "!IDENTIFY failed with sct = %x, sc = %x",
1786 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1787 		goto fail;
1788 	}
1789 
1790 	*buf = kmem_alloc(NVME_IDENTIFY_BUFSIZE, KM_SLEEP);
1791 	bcopy(cmd->nc_dma->nd_memp, *buf, NVME_IDENTIFY_BUFSIZE);
1792 
1793 fail:
1794 	nvme_free_cmd(cmd);
1795 
1796 	return (ret);
1797 }
1798 
1799 static int
nvme_set_features(nvme_t * nvme,uint32_t nsid,uint8_t feature,uint32_t val,uint32_t * res)1800 nvme_set_features(nvme_t *nvme, uint32_t nsid, uint8_t feature, uint32_t val,
1801     uint32_t *res)
1802 {
1803 	_NOTE(ARGUNUSED(nsid));
1804 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1805 	int ret = EINVAL;
1806 
1807 	ASSERT(res != NULL);
1808 
1809 	cmd->nc_sqid = 0;
1810 	cmd->nc_callback = nvme_wakeup_cmd;
1811 	cmd->nc_sqe.sqe_opc = NVME_OPC_SET_FEATURES;
1812 	cmd->nc_sqe.sqe_cdw10 = feature;
1813 	cmd->nc_sqe.sqe_cdw11 = val;
1814 
1815 	switch (feature) {
1816 	case NVME_FEAT_WRITE_CACHE:
1817 		if (!nvme->n_write_cache_present)
1818 			goto fail;
1819 		break;
1820 
1821 	case NVME_FEAT_NQUEUES:
1822 		break;
1823 
1824 	default:
1825 		goto fail;
1826 	}
1827 
1828 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
1829 
1830 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1831 		dev_err(nvme->n_dip, CE_WARN,
1832 		    "!SET FEATURES %d failed with sct = %x, sc = %x",
1833 		    feature, cmd->nc_cqe.cqe_sf.sf_sct,
1834 		    cmd->nc_cqe.cqe_sf.sf_sc);
1835 		goto fail;
1836 	}
1837 
1838 	*res = cmd->nc_cqe.cqe_dw0;
1839 
1840 fail:
1841 	nvme_free_cmd(cmd);
1842 	return (ret);
1843 }
1844 
1845 static int
nvme_get_features(nvme_t * nvme,uint32_t nsid,uint8_t feature,uint32_t * res,void ** buf,size_t * bufsize)1846 nvme_get_features(nvme_t *nvme, uint32_t nsid, uint8_t feature, uint32_t *res,
1847     void **buf, size_t *bufsize)
1848 {
1849 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1850 	int ret = EINVAL;
1851 
1852 	ASSERT(res != NULL);
1853 
1854 	if (bufsize != NULL)
1855 		*bufsize = 0;
1856 
1857 	cmd->nc_sqid = 0;
1858 	cmd->nc_callback = nvme_wakeup_cmd;
1859 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_FEATURES;
1860 	cmd->nc_sqe.sqe_cdw10 = feature;
1861 	cmd->nc_sqe.sqe_cdw11 = *res;
1862 
1863 	switch (feature) {
1864 	case NVME_FEAT_ARBITRATION:
1865 	case NVME_FEAT_POWER_MGMT:
1866 	case NVME_FEAT_TEMPERATURE:
1867 	case NVME_FEAT_ERROR:
1868 	case NVME_FEAT_NQUEUES:
1869 	case NVME_FEAT_INTR_COAL:
1870 	case NVME_FEAT_INTR_VECT:
1871 	case NVME_FEAT_WRITE_ATOM:
1872 	case NVME_FEAT_ASYNC_EVENT:
1873 	case NVME_FEAT_PROGRESS:
1874 		break;
1875 
1876 	case NVME_FEAT_WRITE_CACHE:
1877 		if (!nvme->n_write_cache_present)
1878 			goto fail;
1879 		break;
1880 
1881 	case NVME_FEAT_LBA_RANGE:
1882 		if (!nvme->n_lba_range_supported)
1883 			goto fail;
1884 
1885 		/*
1886 		 * The LBA Range Type feature is optional. There doesn't seem
1887 		 * be a method of detecting whether it is supported other than
1888 		 * using it. This will cause a "invalid field in command" error,
1889 		 * which is normally considered a programming error and causes
1890 		 * panic in nvme_check_generic_cmd_status().
1891 		 */
1892 		cmd->nc_dontpanic = B_TRUE;
1893 		cmd->nc_sqe.sqe_nsid = nsid;
1894 		ASSERT(bufsize != NULL);
1895 		*bufsize = NVME_LBA_RANGE_BUFSIZE;
1896 
1897 		break;
1898 
1899 	case NVME_FEAT_AUTO_PST:
1900 		if (!nvme->n_auto_pst_supported)
1901 			goto fail;
1902 
1903 		ASSERT(bufsize != NULL);
1904 		*bufsize = NVME_AUTO_PST_BUFSIZE;
1905 		break;
1906 
1907 	default:
1908 		goto fail;
1909 	}
1910 
1911 	if (bufsize != NULL && *bufsize != 0) {
1912 		if (nvme_zalloc_dma(nvme, *bufsize, DDI_DMA_READ,
1913 		    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1914 			dev_err(nvme->n_dip, CE_WARN,
1915 			    "!nvme_zalloc_dma failed for GET FEATURES");
1916 			ret = ENOMEM;
1917 			goto fail;
1918 		}
1919 
1920 		if (cmd->nc_dma->nd_ncookie > 2) {
1921 			dev_err(nvme->n_dip, CE_WARN,
1922 			    "!too many DMA cookies for GET FEATURES");
1923 			atomic_inc_32(&nvme->n_too_many_cookies);
1924 			ret = ENOMEM;
1925 			goto fail;
1926 		}
1927 
1928 		cmd->nc_sqe.sqe_dptr.d_prp[0] =
1929 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1930 		if (cmd->nc_dma->nd_ncookie > 1) {
1931 			ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1932 			    &cmd->nc_dma->nd_cookie);
1933 			cmd->nc_sqe.sqe_dptr.d_prp[1] =
1934 			    cmd->nc_dma->nd_cookie.dmac_laddress;
1935 		}
1936 	}
1937 
1938 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
1939 
1940 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1941 		if (feature == NVME_FEAT_LBA_RANGE &&
1942 		    cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1943 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INV_FLD)
1944 			nvme->n_lba_range_supported = B_FALSE;
1945 		else
1946 			dev_err(nvme->n_dip, CE_WARN,
1947 			    "!GET FEATURES %d failed with sct = %x, sc = %x",
1948 			    feature, cmd->nc_cqe.cqe_sf.sf_sct,
1949 			    cmd->nc_cqe.cqe_sf.sf_sc);
1950 		goto fail;
1951 	}
1952 
1953 	if (bufsize != NULL && *bufsize != 0) {
1954 		ASSERT(buf != NULL);
1955 		*buf = kmem_alloc(*bufsize, KM_SLEEP);
1956 		bcopy(cmd->nc_dma->nd_memp, *buf, *bufsize);
1957 	}
1958 
1959 	*res = cmd->nc_cqe.cqe_dw0;
1960 
1961 fail:
1962 	nvme_free_cmd(cmd);
1963 	return (ret);
1964 }
1965 
1966 static int
nvme_write_cache_set(nvme_t * nvme,boolean_t enable)1967 nvme_write_cache_set(nvme_t *nvme, boolean_t enable)
1968 {
1969 	nvme_write_cache_t nwc = { 0 };
1970 
1971 	if (enable)
1972 		nwc.b.wc_wce = 1;
1973 
1974 	return (nvme_set_features(nvme, 0, NVME_FEAT_WRITE_CACHE, nwc.r,
1975 	    &nwc.r));
1976 }
1977 
1978 static int
nvme_set_nqueues(nvme_t * nvme,uint16_t * nqueues)1979 nvme_set_nqueues(nvme_t *nvme, uint16_t *nqueues)
1980 {
1981 	nvme_nqueues_t nq = { 0 };
1982 	int ret;
1983 
1984 	nq.b.nq_nsq = nq.b.nq_ncq = *nqueues - 1;
1985 
1986 	ret = nvme_set_features(nvme, 0, NVME_FEAT_NQUEUES, nq.r, &nq.r);
1987 
1988 	if (ret == 0) {
1989 		/*
1990 		 * Always use the same number of submission and completion
1991 		 * queues, and never use more than the requested number of
1992 		 * queues.
1993 		 */
1994 		*nqueues = MIN(*nqueues, MIN(nq.b.nq_nsq, nq.b.nq_ncq) + 1);
1995 	}
1996 
1997 	return (ret);
1998 }
1999 
2000 static int
nvme_create_io_qpair(nvme_t * nvme,nvme_qpair_t * qp,uint16_t idx)2001 nvme_create_io_qpair(nvme_t *nvme, nvme_qpair_t *qp, uint16_t idx)
2002 {
2003 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
2004 	nvme_create_queue_dw10_t dw10 = { 0 };
2005 	nvme_create_cq_dw11_t c_dw11 = { 0 };
2006 	nvme_create_sq_dw11_t s_dw11 = { 0 };
2007 	int ret;
2008 
2009 	dw10.b.q_qid = idx;
2010 	dw10.b.q_qsize = qp->nq_nentry - 1;
2011 
2012 	c_dw11.b.cq_pc = 1;
2013 	c_dw11.b.cq_ien = 1;
2014 	c_dw11.b.cq_iv = idx % nvme->n_intr_cnt;
2015 
2016 	cmd->nc_sqid = 0;
2017 	cmd->nc_callback = nvme_wakeup_cmd;
2018 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_CQUEUE;
2019 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
2020 	cmd->nc_sqe.sqe_cdw11 = c_dw11.r;
2021 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_cqdma->nd_cookie.dmac_laddress;
2022 
2023 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
2024 
2025 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
2026 		dev_err(nvme->n_dip, CE_WARN,
2027 		    "!CREATE CQUEUE failed with sct = %x, sc = %x",
2028 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
2029 		goto fail;
2030 	}
2031 
2032 	nvme_free_cmd(cmd);
2033 
2034 	s_dw11.b.sq_pc = 1;
2035 	s_dw11.b.sq_cqid = idx;
2036 
2037 	cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
2038 	cmd->nc_sqid = 0;
2039 	cmd->nc_callback = nvme_wakeup_cmd;
2040 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_SQUEUE;
2041 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
2042 	cmd->nc_sqe.sqe_cdw11 = s_dw11.r;
2043 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_sqdma->nd_cookie.dmac_laddress;
2044 
2045 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
2046 
2047 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
2048 		dev_err(nvme->n_dip, CE_WARN,
2049 		    "!CREATE SQUEUE failed with sct = %x, sc = %x",
2050 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
2051 		goto fail;
2052 	}
2053 
2054 fail:
2055 	nvme_free_cmd(cmd);
2056 
2057 	return (ret);
2058 }
2059 
2060 static boolean_t
nvme_reset(nvme_t * nvme,boolean_t quiesce)2061 nvme_reset(nvme_t *nvme, boolean_t quiesce)
2062 {
2063 	nvme_reg_csts_t csts;
2064 	int i;
2065 
2066 	nvme_put32(nvme, NVME_REG_CC, 0);
2067 
2068 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2069 	if (csts.b.csts_rdy == 1) {
2070 		nvme_put32(nvme, NVME_REG_CC, 0);
2071 		for (i = 0; i != nvme->n_timeout * 10; i++) {
2072 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2073 			if (csts.b.csts_rdy == 0)
2074 				break;
2075 
2076 			if (quiesce)
2077 				drv_usecwait(50000);
2078 			else
2079 				delay(drv_usectohz(50000));
2080 		}
2081 	}
2082 
2083 	nvme_put32(nvme, NVME_REG_AQA, 0);
2084 	nvme_put32(nvme, NVME_REG_ASQ, 0);
2085 	nvme_put32(nvme, NVME_REG_ACQ, 0);
2086 
2087 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2088 	return (csts.b.csts_rdy == 0 ? B_TRUE : B_FALSE);
2089 }
2090 
2091 static void
nvme_shutdown(nvme_t * nvme,int mode,boolean_t quiesce)2092 nvme_shutdown(nvme_t *nvme, int mode, boolean_t quiesce)
2093 {
2094 	nvme_reg_cc_t cc;
2095 	nvme_reg_csts_t csts;
2096 	int i;
2097 
2098 	ASSERT(mode == NVME_CC_SHN_NORMAL || mode == NVME_CC_SHN_ABRUPT);
2099 
2100 	cc.r = nvme_get32(nvme, NVME_REG_CC);
2101 	cc.b.cc_shn = mode & 0x3;
2102 	nvme_put32(nvme, NVME_REG_CC, cc.r);
2103 
2104 	for (i = 0; i != 10; i++) {
2105 		csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2106 		if (csts.b.csts_shst == NVME_CSTS_SHN_COMPLETE)
2107 			break;
2108 
2109 		if (quiesce)
2110 			drv_usecwait(100000);
2111 		else
2112 			delay(drv_usectohz(100000));
2113 	}
2114 }
2115 
2116 
2117 static void
nvme_prepare_devid(nvme_t * nvme,uint32_t nsid)2118 nvme_prepare_devid(nvme_t *nvme, uint32_t nsid)
2119 {
2120 	/*
2121 	 * Section 7.7 of the spec describes how to get a unique ID for
2122 	 * the controller: the vendor ID, the model name and the serial
2123 	 * number shall be unique when combined.
2124 	 *
2125 	 * If a namespace has no EUI64 we use the above and add the hex
2126 	 * namespace ID to get a unique ID for the namespace.
2127 	 */
2128 	char model[sizeof (nvme->n_idctl->id_model) + 1];
2129 	char serial[sizeof (nvme->n_idctl->id_serial) + 1];
2130 
2131 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
2132 	bcopy(nvme->n_idctl->id_serial, serial,
2133 	    sizeof (nvme->n_idctl->id_serial));
2134 
2135 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
2136 	serial[sizeof (nvme->n_idctl->id_serial)] = '\0';
2137 
2138 	nvme->n_ns[nsid - 1].ns_devid = kmem_asprintf("%4X-%s-%s-%X",
2139 	    nvme->n_idctl->id_vid, model, serial, nsid);
2140 }
2141 
2142 static int
nvme_init_ns(nvme_t * nvme,int nsid)2143 nvme_init_ns(nvme_t *nvme, int nsid)
2144 {
2145 	nvme_namespace_t *ns = &nvme->n_ns[nsid - 1];
2146 	nvme_identify_nsid_t *idns;
2147 	int last_rp;
2148 
2149 	ns->ns_nvme = nvme;
2150 
2151 	if (nvme_identify(nvme, nsid, (void **)&idns) != 0) {
2152 		dev_err(nvme->n_dip, CE_WARN,
2153 		    "!failed to identify namespace %d", nsid);
2154 		return (DDI_FAILURE);
2155 	}
2156 
2157 	ns->ns_idns = idns;
2158 	ns->ns_id = nsid;
2159 	ns->ns_block_count = idns->id_nsize;
2160 	ns->ns_block_size =
2161 	    1 << idns->id_lbaf[idns->id_flbas.lba_format].lbaf_lbads;
2162 	ns->ns_best_block_size = ns->ns_block_size;
2163 
2164 	/*
2165 	 * Get the EUI64 if present. Use it for devid and device node names.
2166 	 */
2167 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1))
2168 		bcopy(idns->id_eui64, ns->ns_eui64, sizeof (ns->ns_eui64));
2169 
2170 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
2171 	if (*(uint64_t *)ns->ns_eui64 != 0) {
2172 		uint8_t *eui64 = ns->ns_eui64;
2173 
2174 		(void) snprintf(ns->ns_name, sizeof (ns->ns_name),
2175 		    "%02x%02x%02x%02x%02x%02x%02x%02x",
2176 		    eui64[0], eui64[1], eui64[2], eui64[3],
2177 		    eui64[4], eui64[5], eui64[6], eui64[7]);
2178 	} else {
2179 		(void) snprintf(ns->ns_name, sizeof (ns->ns_name), "%d",
2180 		    ns->ns_id);
2181 
2182 		nvme_prepare_devid(nvme, ns->ns_id);
2183 	}
2184 
2185 	/*
2186 	 * Find the LBA format with no metadata and the best relative
2187 	 * performance. A value of 3 means "degraded", 0 is best.
2188 	 */
2189 	last_rp = 3;
2190 	for (int j = 0; j <= idns->id_nlbaf; j++) {
2191 		if (idns->id_lbaf[j].lbaf_lbads == 0)
2192 			break;
2193 		if (idns->id_lbaf[j].lbaf_ms != 0)
2194 			continue;
2195 		if (idns->id_lbaf[j].lbaf_rp >= last_rp)
2196 			continue;
2197 		last_rp = idns->id_lbaf[j].lbaf_rp;
2198 		ns->ns_best_block_size =
2199 		    1 << idns->id_lbaf[j].lbaf_lbads;
2200 	}
2201 
2202 	if (ns->ns_best_block_size < nvme->n_min_block_size)
2203 		ns->ns_best_block_size = nvme->n_min_block_size;
2204 
2205 	/*
2206 	 * We currently don't support namespaces that use either:
2207 	 * - thin provisioning
2208 	 * - protection information
2209 	 * - illegal block size (< 512)
2210 	 */
2211 	if (idns->id_nsfeat.f_thin ||
2212 	    idns->id_dps.dp_pinfo) {
2213 		dev_err(nvme->n_dip, CE_WARN,
2214 		    "!ignoring namespace %d, unsupported features: "
2215 		    "thin = %d, pinfo = %d", nsid,
2216 		    idns->id_nsfeat.f_thin, idns->id_dps.dp_pinfo);
2217 		ns->ns_ignore = B_TRUE;
2218 	} else if (ns->ns_block_size < 512) {
2219 		dev_err(nvme->n_dip, CE_WARN,
2220 		    "!ignoring namespace %d, unsupported block size %"PRIu64,
2221 		    nsid, (uint64_t)ns->ns_block_size);
2222 		ns->ns_ignore = B_TRUE;
2223 	} else {
2224 		ns->ns_ignore = B_FALSE;
2225 	}
2226 
2227 	return (DDI_SUCCESS);
2228 }
2229 
2230 static int
nvme_init(nvme_t * nvme)2231 nvme_init(nvme_t *nvme)
2232 {
2233 	nvme_reg_cc_t cc = { 0 };
2234 	nvme_reg_aqa_t aqa = { 0 };
2235 	nvme_reg_asq_t asq = { 0 };
2236 	nvme_reg_acq_t acq = { 0 };
2237 	nvme_reg_cap_t cap;
2238 	nvme_reg_vs_t vs;
2239 	nvme_reg_csts_t csts;
2240 	int i = 0;
2241 	uint16_t nqueues;
2242 	char model[sizeof (nvme->n_idctl->id_model) + 1];
2243 	char *vendor, *product;
2244 
2245 	/* Check controller version */
2246 	vs.r = nvme_get32(nvme, NVME_REG_VS);
2247 	nvme->n_version.v_major = vs.b.vs_mjr;
2248 	nvme->n_version.v_minor = vs.b.vs_mnr;
2249 	dev_err(nvme->n_dip, CE_CONT, "?NVMe spec version %d.%d",
2250 	    nvme->n_version.v_major, nvme->n_version.v_minor);
2251 
2252 	if (nvme->n_version.v_major > nvme_version_major) {
2253 		dev_err(nvme->n_dip, CE_WARN, "!no support for version > %d.x",
2254 		    nvme_version_major);
2255 		if (nvme->n_strict_version)
2256 			goto fail;
2257 	}
2258 
2259 	/* retrieve controller configuration */
2260 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
2261 
2262 	if ((cap.b.cap_css & NVME_CAP_CSS_NVM) == 0) {
2263 		dev_err(nvme->n_dip, CE_WARN,
2264 		    "!NVM command set not supported by hardware");
2265 		goto fail;
2266 	}
2267 
2268 	nvme->n_nssr_supported = cap.b.cap_nssrs;
2269 	nvme->n_doorbell_stride = 4 << cap.b.cap_dstrd;
2270 	nvme->n_timeout = cap.b.cap_to;
2271 	nvme->n_arbitration_mechanisms = cap.b.cap_ams;
2272 	nvme->n_cont_queues_reqd = cap.b.cap_cqr;
2273 	nvme->n_max_queue_entries = cap.b.cap_mqes + 1;
2274 
2275 	/*
2276 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to specify
2277 	 * the base page size of 4k (1<<12), so add 12 here to get the real
2278 	 * page size value.
2279 	 */
2280 	nvme->n_pageshift = MIN(MAX(cap.b.cap_mpsmin + 12, PAGESHIFT),
2281 	    cap.b.cap_mpsmax + 12);
2282 	nvme->n_pagesize = 1UL << (nvme->n_pageshift);
2283 
2284 	/*
2285 	 * Set up Queue DMA to transfer at least 1 page-aligned page at a time.
2286 	 */
2287 	nvme->n_queue_dma_attr.dma_attr_align = nvme->n_pagesize;
2288 	nvme->n_queue_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
2289 
2290 	/*
2291 	 * Set up PRP DMA to transfer 1 page-aligned page at a time.
2292 	 * Maxxfer may be increased after we identified the controller limits.
2293 	 */
2294 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_pagesize;
2295 	nvme->n_prp_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
2296 	nvme->n_prp_dma_attr.dma_attr_align = nvme->n_pagesize;
2297 	nvme->n_prp_dma_attr.dma_attr_seg = nvme->n_pagesize - 1;
2298 
2299 	/*
2300 	 * Reset controller if it's still in ready state.
2301 	 */
2302 	if (nvme_reset(nvme, B_FALSE) == B_FALSE) {
2303 		dev_err(nvme->n_dip, CE_WARN, "!unable to reset controller");
2304 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
2305 		nvme->n_dead = B_TRUE;
2306 		goto fail;
2307 	}
2308 
2309 	/*
2310 	 * Create the admin queue pair.
2311 	 */
2312 	if (nvme_alloc_qpair(nvme, nvme->n_admin_queue_len, &nvme->n_adminq, 0)
2313 	    != DDI_SUCCESS) {
2314 		dev_err(nvme->n_dip, CE_WARN,
2315 		    "!unable to allocate admin qpair");
2316 		goto fail;
2317 	}
2318 	nvme->n_ioq = kmem_alloc(sizeof (nvme_qpair_t *), KM_SLEEP);
2319 	nvme->n_ioq[0] = nvme->n_adminq;
2320 
2321 	nvme->n_progress |= NVME_ADMIN_QUEUE;
2322 
2323 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2324 	    "admin-queue-len", nvme->n_admin_queue_len);
2325 
2326 	aqa.b.aqa_asqs = aqa.b.aqa_acqs = nvme->n_admin_queue_len - 1;
2327 	asq = nvme->n_adminq->nq_sqdma->nd_cookie.dmac_laddress;
2328 	acq = nvme->n_adminq->nq_cqdma->nd_cookie.dmac_laddress;
2329 
2330 	ASSERT((asq & (nvme->n_pagesize - 1)) == 0);
2331 	ASSERT((acq & (nvme->n_pagesize - 1)) == 0);
2332 
2333 	nvme_put32(nvme, NVME_REG_AQA, aqa.r);
2334 	nvme_put64(nvme, NVME_REG_ASQ, asq);
2335 	nvme_put64(nvme, NVME_REG_ACQ, acq);
2336 
2337 	cc.b.cc_ams = 0;	/* use Round-Robin arbitration */
2338 	cc.b.cc_css = 0;	/* use NVM command set */
2339 	cc.b.cc_mps = nvme->n_pageshift - 12;
2340 	cc.b.cc_shn = 0;	/* no shutdown in progress */
2341 	cc.b.cc_en = 1;		/* enable controller */
2342 	cc.b.cc_iosqes = 6;	/* submission queue entry is 2^6 bytes long */
2343 	cc.b.cc_iocqes = 4;	/* completion queue entry is 2^4 bytes long */
2344 
2345 	nvme_put32(nvme, NVME_REG_CC, cc.r);
2346 
2347 	/*
2348 	 * Wait for the controller to become ready.
2349 	 */
2350 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2351 	if (csts.b.csts_rdy == 0) {
2352 		for (i = 0; i != nvme->n_timeout * 10; i++) {
2353 			delay(drv_usectohz(50000));
2354 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2355 
2356 			if (csts.b.csts_cfs == 1) {
2357 				dev_err(nvme->n_dip, CE_WARN,
2358 				    "!controller fatal status at init");
2359 				ddi_fm_service_impact(nvme->n_dip,
2360 				    DDI_SERVICE_LOST);
2361 				nvme->n_dead = B_TRUE;
2362 				goto fail;
2363 			}
2364 
2365 			if (csts.b.csts_rdy == 1)
2366 				break;
2367 		}
2368 	}
2369 
2370 	if (csts.b.csts_rdy == 0) {
2371 		dev_err(nvme->n_dip, CE_WARN, "!controller not ready");
2372 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
2373 		nvme->n_dead = B_TRUE;
2374 		goto fail;
2375 	}
2376 
2377 	/*
2378 	 * Assume an abort command limit of 1. We'll destroy and re-init
2379 	 * that later when we know the true abort command limit.
2380 	 */
2381 	sema_init(&nvme->n_abort_sema, 1, NULL, SEMA_DRIVER, NULL);
2382 
2383 	/*
2384 	 * Setup initial interrupt for admin queue.
2385 	 */
2386 	if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX, 1)
2387 	    != DDI_SUCCESS) &&
2388 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI, 1)
2389 	    != DDI_SUCCESS) &&
2390 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_FIXED, 1)
2391 	    != DDI_SUCCESS)) {
2392 		dev_err(nvme->n_dip, CE_WARN,
2393 		    "!failed to setup initial interrupt");
2394 		goto fail;
2395 	}
2396 
2397 	/*
2398 	 * Post an asynchronous event command to catch errors.
2399 	 */
2400 	nvme_async_event(nvme);
2401 
2402 	/*
2403 	 * Identify Controller
2404 	 */
2405 	if (nvme_identify(nvme, 0, (void **)&nvme->n_idctl) != 0) {
2406 		dev_err(nvme->n_dip, CE_WARN,
2407 		    "!failed to identify controller");
2408 		goto fail;
2409 	}
2410 
2411 	/*
2412 	 * Get Vendor & Product ID
2413 	 */
2414 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
2415 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
2416 	sata_split_model(model, &vendor, &product);
2417 
2418 	if (vendor == NULL)
2419 		nvme->n_vendor = strdup("NVMe");
2420 	else
2421 		nvme->n_vendor = strdup(vendor);
2422 
2423 	nvme->n_product = strdup(product);
2424 
2425 	/*
2426 	 * Get controller limits.
2427 	 */
2428 	nvme->n_async_event_limit = MAX(NVME_MIN_ASYNC_EVENT_LIMIT,
2429 	    MIN(nvme->n_admin_queue_len / 10,
2430 	    MIN(nvme->n_idctl->id_aerl + 1, nvme->n_async_event_limit)));
2431 
2432 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2433 	    "async-event-limit", nvme->n_async_event_limit);
2434 
2435 	nvme->n_abort_command_limit = nvme->n_idctl->id_acl + 1;
2436 
2437 	/*
2438 	 * Reinitialize the semaphore with the true abort command limit
2439 	 * supported by the hardware. It's not necessary to disable interrupts
2440 	 * as only command aborts use the semaphore, and no commands are
2441 	 * executed or aborted while we're here.
2442 	 */
2443 	sema_destroy(&nvme->n_abort_sema);
2444 	sema_init(&nvme->n_abort_sema, nvme->n_abort_command_limit - 1, NULL,
2445 	    SEMA_DRIVER, NULL);
2446 
2447 	nvme->n_progress |= NVME_CTRL_LIMITS;
2448 
2449 	if (nvme->n_idctl->id_mdts == 0)
2450 		nvme->n_max_data_transfer_size = nvme->n_pagesize * 65536;
2451 	else
2452 		nvme->n_max_data_transfer_size =
2453 		    1ull << (nvme->n_pageshift + nvme->n_idctl->id_mdts);
2454 
2455 	nvme->n_error_log_len = nvme->n_idctl->id_elpe + 1;
2456 
2457 	/*
2458 	 * Limit n_max_data_transfer_size to what we can handle in one PRP.
2459 	 * Chained PRPs are currently unsupported.
2460 	 *
2461 	 * This is a no-op on hardware which doesn't support a transfer size
2462 	 * big enough to require chained PRPs.
2463 	 */
2464 	nvme->n_max_data_transfer_size = MIN(nvme->n_max_data_transfer_size,
2465 	    (nvme->n_pagesize / sizeof (uint64_t) * nvme->n_pagesize));
2466 
2467 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_max_data_transfer_size;
2468 
2469 	/*
2470 	 * Make sure the minimum/maximum queue entry sizes are not
2471 	 * larger/smaller than the default.
2472 	 */
2473 
2474 	if (((1 << nvme->n_idctl->id_sqes.qes_min) > sizeof (nvme_sqe_t)) ||
2475 	    ((1 << nvme->n_idctl->id_sqes.qes_max) < sizeof (nvme_sqe_t)) ||
2476 	    ((1 << nvme->n_idctl->id_cqes.qes_min) > sizeof (nvme_cqe_t)) ||
2477 	    ((1 << nvme->n_idctl->id_cqes.qes_max) < sizeof (nvme_cqe_t)))
2478 		goto fail;
2479 
2480 	/*
2481 	 * Check for the presence of a Volatile Write Cache. If present,
2482 	 * enable or disable based on the value of the property
2483 	 * volatile-write-cache-enable (default is enabled).
2484 	 */
2485 	nvme->n_write_cache_present =
2486 	    nvme->n_idctl->id_vwc.vwc_present == 0 ? B_FALSE : B_TRUE;
2487 
2488 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2489 	    "volatile-write-cache-present",
2490 	    nvme->n_write_cache_present ? 1 : 0);
2491 
2492 	if (!nvme->n_write_cache_present) {
2493 		nvme->n_write_cache_enabled = B_FALSE;
2494 	} else if (nvme_write_cache_set(nvme, nvme->n_write_cache_enabled)
2495 	    != 0) {
2496 		dev_err(nvme->n_dip, CE_WARN,
2497 		    "!failed to %sable volatile write cache",
2498 		    nvme->n_write_cache_enabled ? "en" : "dis");
2499 		/*
2500 		 * Assume the cache is (still) enabled.
2501 		 */
2502 		nvme->n_write_cache_enabled = B_TRUE;
2503 	}
2504 
2505 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2506 	    "volatile-write-cache-enable",
2507 	    nvme->n_write_cache_enabled ? 1 : 0);
2508 
2509 	/*
2510 	 * Assume LBA Range Type feature is supported. If it isn't this
2511 	 * will be set to B_FALSE by nvme_get_features().
2512 	 */
2513 	nvme->n_lba_range_supported = B_TRUE;
2514 
2515 	/*
2516 	 * Check support for Autonomous Power State Transition.
2517 	 */
2518 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1))
2519 		nvme->n_auto_pst_supported =
2520 		    nvme->n_idctl->id_apsta.ap_sup == 0 ? B_FALSE : B_TRUE;
2521 
2522 	/*
2523 	 * Identify Namespaces
2524 	 */
2525 	nvme->n_namespace_count = nvme->n_idctl->id_nn;
2526 	if (nvme->n_namespace_count > NVME_MINOR_MAX) {
2527 		dev_err(nvme->n_dip, CE_WARN,
2528 		    "!too many namespaces: %d, limiting to %d\n",
2529 		    nvme->n_namespace_count, NVME_MINOR_MAX);
2530 		nvme->n_namespace_count = NVME_MINOR_MAX;
2531 	}
2532 
2533 	nvme->n_ns = kmem_zalloc(sizeof (nvme_namespace_t) *
2534 	    nvme->n_namespace_count, KM_SLEEP);
2535 
2536 	for (i = 0; i != nvme->n_namespace_count; i++) {
2537 		mutex_init(&nvme->n_ns[i].ns_minor.nm_mutex, NULL, MUTEX_DRIVER,
2538 		    NULL);
2539 		if (nvme_init_ns(nvme, i + 1) != DDI_SUCCESS)
2540 			goto fail;
2541 	}
2542 
2543 	/*
2544 	 * Try to set up MSI/MSI-X interrupts.
2545 	 */
2546 	if ((nvme->n_intr_types & (DDI_INTR_TYPE_MSI | DDI_INTR_TYPE_MSIX))
2547 	    != 0) {
2548 		nvme_release_interrupts(nvme);
2549 
2550 		nqueues = MIN(UINT16_MAX, ncpus);
2551 
2552 		if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX,
2553 		    nqueues) != DDI_SUCCESS) &&
2554 		    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI,
2555 		    nqueues) != DDI_SUCCESS)) {
2556 			dev_err(nvme->n_dip, CE_WARN,
2557 			    "!failed to setup MSI/MSI-X interrupts");
2558 			goto fail;
2559 		}
2560 	}
2561 
2562 	nqueues = nvme->n_intr_cnt;
2563 
2564 	/*
2565 	 * Create I/O queue pairs.
2566 	 */
2567 
2568 	if (nvme_set_nqueues(nvme, &nqueues) != 0) {
2569 		dev_err(nvme->n_dip, CE_WARN,
2570 		    "!failed to set number of I/O queues to %d",
2571 		    nvme->n_intr_cnt);
2572 		goto fail;
2573 	}
2574 
2575 	/*
2576 	 * Reallocate I/O queue array
2577 	 */
2578 	kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *));
2579 	nvme->n_ioq = kmem_zalloc(sizeof (nvme_qpair_t *) *
2580 	    (nqueues + 1), KM_SLEEP);
2581 	nvme->n_ioq[0] = nvme->n_adminq;
2582 
2583 	nvme->n_ioq_count = nqueues;
2584 
2585 	/*
2586 	 * If we got less queues than we asked for we might as well give
2587 	 * some of the interrupt vectors back to the system.
2588 	 */
2589 	if (nvme->n_ioq_count < nvme->n_intr_cnt) {
2590 		nvme_release_interrupts(nvme);
2591 
2592 		if (nvme_setup_interrupts(nvme, nvme->n_intr_type,
2593 		    nvme->n_ioq_count) != DDI_SUCCESS) {
2594 			dev_err(nvme->n_dip, CE_WARN,
2595 			    "!failed to reduce number of interrupts");
2596 			goto fail;
2597 		}
2598 	}
2599 
2600 	/*
2601 	 * Alloc & register I/O queue pairs
2602 	 */
2603 	nvme->n_io_queue_len =
2604 	    MIN(nvme->n_io_queue_len, nvme->n_max_queue_entries);
2605 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-queue-len",
2606 	    nvme->n_io_queue_len);
2607 
2608 	for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2609 		if (nvme_alloc_qpair(nvme, nvme->n_io_queue_len,
2610 		    &nvme->n_ioq[i], i) != DDI_SUCCESS) {
2611 			dev_err(nvme->n_dip, CE_WARN,
2612 			    "!unable to allocate I/O qpair %d", i);
2613 			goto fail;
2614 		}
2615 
2616 		if (nvme_create_io_qpair(nvme, nvme->n_ioq[i], i) != 0) {
2617 			dev_err(nvme->n_dip, CE_WARN,
2618 			    "!unable to create I/O qpair %d", i);
2619 			goto fail;
2620 		}
2621 	}
2622 
2623 	/*
2624 	 * Post more asynchronous events commands to reduce event reporting
2625 	 * latency as suggested by the spec.
2626 	 */
2627 	for (i = 1; i != nvme->n_async_event_limit; i++)
2628 		nvme_async_event(nvme);
2629 
2630 	return (DDI_SUCCESS);
2631 
2632 fail:
2633 	(void) nvme_reset(nvme, B_FALSE);
2634 	return (DDI_FAILURE);
2635 }
2636 
2637 static uint_t
nvme_intr(caddr_t arg1,caddr_t arg2)2638 nvme_intr(caddr_t arg1, caddr_t arg2)
2639 {
2640 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2641 	nvme_t *nvme = (nvme_t *)arg1;
2642 	int inum = (int)(uintptr_t)arg2;
2643 	int ccnt = 0;
2644 	int qnum;
2645 	nvme_cmd_t *cmd;
2646 
2647 	if (inum >= nvme->n_intr_cnt)
2648 		return (DDI_INTR_UNCLAIMED);
2649 
2650 	if (nvme->n_dead)
2651 		return (nvme->n_intr_type == DDI_INTR_TYPE_FIXED ?
2652 		    DDI_INTR_UNCLAIMED : DDI_INTR_CLAIMED);
2653 
2654 	/*
2655 	 * The interrupt vector a queue uses is calculated as queue_idx %
2656 	 * intr_cnt in nvme_create_io_qpair(). Iterate through the queue array
2657 	 * in steps of n_intr_cnt to process all queues using this vector.
2658 	 */
2659 	for (qnum = inum;
2660 	    qnum < nvme->n_ioq_count + 1 && nvme->n_ioq[qnum] != NULL;
2661 	    qnum += nvme->n_intr_cnt) {
2662 		while ((cmd = nvme_retrieve_cmd(nvme, nvme->n_ioq[qnum]))) {
2663 			taskq_dispatch_ent((taskq_t *)cmd->nc_nvme->n_cmd_taskq,
2664 			    cmd->nc_callback, cmd, TQ_NOSLEEP, &cmd->nc_tqent);
2665 			ccnt++;
2666 		}
2667 	}
2668 
2669 	return (ccnt > 0 ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
2670 }
2671 
2672 static void
nvme_release_interrupts(nvme_t * nvme)2673 nvme_release_interrupts(nvme_t *nvme)
2674 {
2675 	int i;
2676 
2677 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2678 		if (nvme->n_inth[i] == NULL)
2679 			break;
2680 
2681 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2682 			(void) ddi_intr_block_disable(&nvme->n_inth[i], 1);
2683 		else
2684 			(void) ddi_intr_disable(nvme->n_inth[i]);
2685 
2686 		(void) ddi_intr_remove_handler(nvme->n_inth[i]);
2687 		(void) ddi_intr_free(nvme->n_inth[i]);
2688 	}
2689 
2690 	kmem_free(nvme->n_inth, nvme->n_inth_sz);
2691 	nvme->n_inth = NULL;
2692 	nvme->n_inth_sz = 0;
2693 
2694 	nvme->n_progress &= ~NVME_INTERRUPTS;
2695 }
2696 
2697 static int
nvme_setup_interrupts(nvme_t * nvme,int intr_type,int nqpairs)2698 nvme_setup_interrupts(nvme_t *nvme, int intr_type, int nqpairs)
2699 {
2700 	int nintrs, navail, count;
2701 	int ret;
2702 	int i;
2703 
2704 	if (nvme->n_intr_types == 0) {
2705 		ret = ddi_intr_get_supported_types(nvme->n_dip,
2706 		    &nvme->n_intr_types);
2707 		if (ret != DDI_SUCCESS) {
2708 			dev_err(nvme->n_dip, CE_WARN,
2709 			    "!%s: ddi_intr_get_supported types failed",
2710 			    __func__);
2711 			return (ret);
2712 		}
2713 #ifdef __x86
2714 		if (get_hwenv() == HW_VMWARE)
2715 			nvme->n_intr_types &= ~DDI_INTR_TYPE_MSIX;
2716 #endif
2717 	}
2718 
2719 	if ((nvme->n_intr_types & intr_type) == 0)
2720 		return (DDI_FAILURE);
2721 
2722 	ret = ddi_intr_get_nintrs(nvme->n_dip, intr_type, &nintrs);
2723 	if (ret != DDI_SUCCESS) {
2724 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_nintrs failed",
2725 		    __func__);
2726 		return (ret);
2727 	}
2728 
2729 	ret = ddi_intr_get_navail(nvme->n_dip, intr_type, &navail);
2730 	if (ret != DDI_SUCCESS) {
2731 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_navail failed",
2732 		    __func__);
2733 		return (ret);
2734 	}
2735 
2736 	/* We want at most one interrupt per queue pair. */
2737 	if (navail > nqpairs)
2738 		navail = nqpairs;
2739 
2740 	nvme->n_inth_sz = sizeof (ddi_intr_handle_t) * navail;
2741 	nvme->n_inth = kmem_zalloc(nvme->n_inth_sz, KM_SLEEP);
2742 
2743 	ret = ddi_intr_alloc(nvme->n_dip, nvme->n_inth, intr_type, 0, navail,
2744 	    &count, 0);
2745 	if (ret != DDI_SUCCESS) {
2746 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_alloc failed",
2747 		    __func__);
2748 		goto fail;
2749 	}
2750 
2751 	nvme->n_intr_cnt = count;
2752 
2753 	ret = ddi_intr_get_pri(nvme->n_inth[0], &nvme->n_intr_pri);
2754 	if (ret != DDI_SUCCESS) {
2755 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_pri failed",
2756 		    __func__);
2757 		goto fail;
2758 	}
2759 
2760 	for (i = 0; i < count; i++) {
2761 		ret = ddi_intr_add_handler(nvme->n_inth[i], nvme_intr,
2762 		    (void *)nvme, (void *)(uintptr_t)i);
2763 		if (ret != DDI_SUCCESS) {
2764 			dev_err(nvme->n_dip, CE_WARN,
2765 			    "!%s: ddi_intr_add_handler failed", __func__);
2766 			goto fail;
2767 		}
2768 	}
2769 
2770 	(void) ddi_intr_get_cap(nvme->n_inth[0], &nvme->n_intr_cap);
2771 
2772 	for (i = 0; i < count; i++) {
2773 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2774 			ret = ddi_intr_block_enable(&nvme->n_inth[i], 1);
2775 		else
2776 			ret = ddi_intr_enable(nvme->n_inth[i]);
2777 
2778 		if (ret != DDI_SUCCESS) {
2779 			dev_err(nvme->n_dip, CE_WARN,
2780 			    "!%s: enabling interrupt %d failed", __func__, i);
2781 			goto fail;
2782 		}
2783 	}
2784 
2785 	nvme->n_intr_type = intr_type;
2786 
2787 	nvme->n_progress |= NVME_INTERRUPTS;
2788 
2789 	return (DDI_SUCCESS);
2790 
2791 fail:
2792 	nvme_release_interrupts(nvme);
2793 
2794 	return (ret);
2795 }
2796 
2797 static int
nvme_fm_errcb(dev_info_t * dip,ddi_fm_error_t * fm_error,const void * arg)2798 nvme_fm_errcb(dev_info_t *dip, ddi_fm_error_t *fm_error, const void *arg)
2799 {
2800 	_NOTE(ARGUNUSED(arg));
2801 
2802 	pci_ereport_post(dip, fm_error, NULL);
2803 	return (fm_error->fme_status);
2804 }
2805 
2806 static int
nvme_attach(dev_info_t * dip,ddi_attach_cmd_t cmd)2807 nvme_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2808 {
2809 	nvme_t *nvme;
2810 	int instance;
2811 	int nregs;
2812 	off_t regsize;
2813 	int i;
2814 	char name[32];
2815 
2816 	if (cmd != DDI_ATTACH)
2817 		return (DDI_FAILURE);
2818 
2819 	instance = ddi_get_instance(dip);
2820 
2821 	if (ddi_soft_state_zalloc(nvme_state, instance) != DDI_SUCCESS)
2822 		return (DDI_FAILURE);
2823 
2824 	nvme = ddi_get_soft_state(nvme_state, instance);
2825 	ddi_set_driver_private(dip, nvme);
2826 	nvme->n_dip = dip;
2827 
2828 	mutex_init(&nvme->n_minor.nm_mutex, NULL, MUTEX_DRIVER, NULL);
2829 
2830 	nvme->n_strict_version = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2831 	    DDI_PROP_DONTPASS, "strict-version", 1) == 1 ? B_TRUE : B_FALSE;
2832 	nvme->n_ignore_unknown_vendor_status = ddi_prop_get_int(DDI_DEV_T_ANY,
2833 	    dip, DDI_PROP_DONTPASS, "ignore-unknown-vendor-status", 0) == 1 ?
2834 	    B_TRUE : B_FALSE;
2835 	nvme->n_admin_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2836 	    DDI_PROP_DONTPASS, "admin-queue-len", NVME_DEFAULT_ADMIN_QUEUE_LEN);
2837 	nvme->n_io_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2838 	    DDI_PROP_DONTPASS, "io-queue-len", NVME_DEFAULT_IO_QUEUE_LEN);
2839 	nvme->n_async_event_limit = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2840 	    DDI_PROP_DONTPASS, "async-event-limit",
2841 	    NVME_DEFAULT_ASYNC_EVENT_LIMIT);
2842 	nvme->n_write_cache_enabled = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2843 	    DDI_PROP_DONTPASS, "volatile-write-cache-enable", 1) != 0 ?
2844 	    B_TRUE : B_FALSE;
2845 	nvme->n_min_block_size = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2846 	    DDI_PROP_DONTPASS, "min-phys-block-size",
2847 	    NVME_DEFAULT_MIN_BLOCK_SIZE);
2848 
2849 	if (!ISP2(nvme->n_min_block_size) ||
2850 	    (nvme->n_min_block_size < NVME_DEFAULT_MIN_BLOCK_SIZE)) {
2851 		dev_err(dip, CE_WARN, "!min-phys-block-size %s, "
2852 		    "using default %d", ISP2(nvme->n_min_block_size) ?
2853 		    "too low" : "not a power of 2",
2854 		    NVME_DEFAULT_MIN_BLOCK_SIZE);
2855 		nvme->n_min_block_size = NVME_DEFAULT_MIN_BLOCK_SIZE;
2856 	}
2857 
2858 	if (nvme->n_admin_queue_len < NVME_MIN_ADMIN_QUEUE_LEN)
2859 		nvme->n_admin_queue_len = NVME_MIN_ADMIN_QUEUE_LEN;
2860 	else if (nvme->n_admin_queue_len > NVME_MAX_ADMIN_QUEUE_LEN)
2861 		nvme->n_admin_queue_len = NVME_MAX_ADMIN_QUEUE_LEN;
2862 
2863 	if (nvme->n_io_queue_len < NVME_MIN_IO_QUEUE_LEN)
2864 		nvme->n_io_queue_len = NVME_MIN_IO_QUEUE_LEN;
2865 
2866 	if (nvme->n_async_event_limit < 1)
2867 		nvme->n_async_event_limit = NVME_DEFAULT_ASYNC_EVENT_LIMIT;
2868 
2869 	nvme->n_reg_acc_attr = nvme_reg_acc_attr;
2870 	nvme->n_queue_dma_attr = nvme_queue_dma_attr;
2871 	nvme->n_prp_dma_attr = nvme_prp_dma_attr;
2872 	nvme->n_sgl_dma_attr = nvme_sgl_dma_attr;
2873 
2874 	/*
2875 	 * Setup FMA support.
2876 	 */
2877 	nvme->n_fm_cap = ddi_getprop(DDI_DEV_T_ANY, dip,
2878 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
2879 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
2880 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
2881 
2882 	ddi_fm_init(dip, &nvme->n_fm_cap, &nvme->n_fm_ibc);
2883 
2884 	if (nvme->n_fm_cap) {
2885 		if (nvme->n_fm_cap & DDI_FM_ACCCHK_CAPABLE)
2886 			nvme->n_reg_acc_attr.devacc_attr_access =
2887 			    DDI_FLAGERR_ACC;
2888 
2889 		if (nvme->n_fm_cap & DDI_FM_DMACHK_CAPABLE) {
2890 			nvme->n_prp_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2891 			nvme->n_sgl_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2892 		}
2893 
2894 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2895 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2896 			pci_ereport_setup(dip);
2897 
2898 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2899 			ddi_fm_handler_register(dip, nvme_fm_errcb,
2900 			    (void *)nvme);
2901 	}
2902 
2903 	nvme->n_progress |= NVME_FMA_INIT;
2904 
2905 	/*
2906 	 * The spec defines several register sets. Only the controller
2907 	 * registers (set 1) are currently used.
2908 	 */
2909 	if (ddi_dev_nregs(dip, &nregs) == DDI_FAILURE ||
2910 	    nregs < 2 ||
2911 	    ddi_dev_regsize(dip, 1, &regsize) == DDI_FAILURE)
2912 		goto fail;
2913 
2914 	if (ddi_regs_map_setup(dip, 1, &nvme->n_regs, 0, regsize,
2915 	    &nvme->n_reg_acc_attr, &nvme->n_regh) != DDI_SUCCESS) {
2916 		dev_err(dip, CE_WARN, "!failed to map regset 1");
2917 		goto fail;
2918 	}
2919 
2920 	nvme->n_progress |= NVME_REGS_MAPPED;
2921 
2922 	/*
2923 	 * Create taskq for command completion.
2924 	 */
2925 	(void) snprintf(name, sizeof (name), "%s%d_cmd_taskq",
2926 	    ddi_driver_name(dip), ddi_get_instance(dip));
2927 	nvme->n_cmd_taskq = ddi_taskq_create(dip, name, MIN(UINT16_MAX, ncpus),
2928 	    TASKQ_DEFAULTPRI, 0);
2929 	if (nvme->n_cmd_taskq == NULL) {
2930 		dev_err(dip, CE_WARN, "!failed to create cmd taskq");
2931 		goto fail;
2932 	}
2933 
2934 	/*
2935 	 * Create PRP DMA cache
2936 	 */
2937 	(void) snprintf(name, sizeof (name), "%s%d_prp_cache",
2938 	    ddi_driver_name(dip), ddi_get_instance(dip));
2939 	nvme->n_prp_cache = kmem_cache_create(name, sizeof (nvme_dma_t),
2940 	    0, nvme_prp_dma_constructor, nvme_prp_dma_destructor,
2941 	    NULL, (void *)nvme, NULL, 0);
2942 
2943 	if (nvme_init(nvme) != DDI_SUCCESS)
2944 		goto fail;
2945 
2946 	/*
2947 	 * Attach the blkdev driver for each namespace.
2948 	 */
2949 	for (i = 0; i != nvme->n_namespace_count; i++) {
2950 		if (ddi_create_minor_node(nvme->n_dip, nvme->n_ns[i].ns_name,
2951 		    S_IFCHR, NVME_MINOR(ddi_get_instance(nvme->n_dip), i + 1),
2952 		    DDI_NT_NVME_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
2953 			dev_err(dip, CE_WARN,
2954 			    "!failed to create minor node for namespace %d", i);
2955 			goto fail;
2956 		}
2957 
2958 		if (nvme->n_ns[i].ns_ignore)
2959 			continue;
2960 
2961 		nvme->n_ns[i].ns_bd_hdl = bd_alloc_handle(&nvme->n_ns[i],
2962 		    &nvme_bd_ops, &nvme->n_prp_dma_attr, KM_SLEEP);
2963 
2964 		if (nvme->n_ns[i].ns_bd_hdl == NULL) {
2965 			dev_err(dip, CE_WARN,
2966 			    "!failed to get blkdev handle for namespace %d", i);
2967 			goto fail;
2968 		}
2969 
2970 		if (bd_attach_handle(dip, nvme->n_ns[i].ns_bd_hdl)
2971 		    != DDI_SUCCESS) {
2972 			dev_err(dip, CE_WARN,
2973 			    "!failed to attach blkdev handle for namespace %d",
2974 			    i);
2975 			goto fail;
2976 		}
2977 	}
2978 
2979 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
2980 	    NVME_MINOR(ddi_get_instance(dip), 0), DDI_NT_NVME_NEXUS, 0)
2981 	    != DDI_SUCCESS) {
2982 		dev_err(dip, CE_WARN, "nvme_attach: "
2983 		    "cannot create devctl minor node");
2984 		goto fail;
2985 	}
2986 
2987 	return (DDI_SUCCESS);
2988 
2989 fail:
2990 	/* attach successful anyway so that FMA can retire the device */
2991 	if (nvme->n_dead)
2992 		return (DDI_SUCCESS);
2993 
2994 	(void) nvme_detach(dip, DDI_DETACH);
2995 
2996 	return (DDI_FAILURE);
2997 }
2998 
2999 static int
nvme_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)3000 nvme_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
3001 {
3002 	int instance, i;
3003 	nvme_t *nvme;
3004 
3005 	if (cmd != DDI_DETACH)
3006 		return (DDI_FAILURE);
3007 
3008 	instance = ddi_get_instance(dip);
3009 
3010 	nvme = ddi_get_soft_state(nvme_state, instance);
3011 
3012 	if (nvme == NULL)
3013 		return (DDI_FAILURE);
3014 
3015 	ddi_remove_minor_node(dip, "devctl");
3016 	mutex_destroy(&nvme->n_minor.nm_mutex);
3017 
3018 	if (nvme->n_ns) {
3019 		for (i = 0; i != nvme->n_namespace_count; i++) {
3020 			ddi_remove_minor_node(dip, nvme->n_ns[i].ns_name);
3021 			mutex_destroy(&nvme->n_ns[i].ns_minor.nm_mutex);
3022 
3023 			if (nvme->n_ns[i].ns_bd_hdl) {
3024 				(void) bd_detach_handle(
3025 				    nvme->n_ns[i].ns_bd_hdl);
3026 				bd_free_handle(nvme->n_ns[i].ns_bd_hdl);
3027 			}
3028 
3029 			if (nvme->n_ns[i].ns_idns)
3030 				kmem_free(nvme->n_ns[i].ns_idns,
3031 				    sizeof (nvme_identify_nsid_t));
3032 			if (nvme->n_ns[i].ns_devid)
3033 				strfree(nvme->n_ns[i].ns_devid);
3034 		}
3035 
3036 		kmem_free(nvme->n_ns, sizeof (nvme_namespace_t) *
3037 		    nvme->n_namespace_count);
3038 	}
3039 
3040 	if (nvme->n_progress & NVME_INTERRUPTS)
3041 		nvme_release_interrupts(nvme);
3042 
3043 	if (nvme->n_cmd_taskq)
3044 		ddi_taskq_wait(nvme->n_cmd_taskq);
3045 
3046 	if (nvme->n_ioq_count > 0) {
3047 		for (i = 1; i != nvme->n_ioq_count + 1; i++) {
3048 			if (nvme->n_ioq[i] != NULL) {
3049 				/* TODO: send destroy queue commands */
3050 				nvme_free_qpair(nvme->n_ioq[i]);
3051 			}
3052 		}
3053 
3054 		kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *) *
3055 		    (nvme->n_ioq_count + 1));
3056 	}
3057 
3058 	if (nvme->n_prp_cache != NULL) {
3059 		kmem_cache_destroy(nvme->n_prp_cache);
3060 	}
3061 
3062 	if (nvme->n_progress & NVME_REGS_MAPPED) {
3063 		nvme_shutdown(nvme, NVME_CC_SHN_NORMAL, B_FALSE);
3064 		(void) nvme_reset(nvme, B_FALSE);
3065 	}
3066 
3067 	if (nvme->n_cmd_taskq)
3068 		ddi_taskq_destroy(nvme->n_cmd_taskq);
3069 
3070 	if (nvme->n_progress & NVME_CTRL_LIMITS)
3071 		sema_destroy(&nvme->n_abort_sema);
3072 
3073 	if (nvme->n_progress & NVME_ADMIN_QUEUE)
3074 		nvme_free_qpair(nvme->n_adminq);
3075 
3076 	if (nvme->n_idctl)
3077 		kmem_free(nvme->n_idctl, NVME_IDENTIFY_BUFSIZE);
3078 
3079 	if (nvme->n_progress & NVME_REGS_MAPPED)
3080 		ddi_regs_map_free(&nvme->n_regh);
3081 
3082 	if (nvme->n_progress & NVME_FMA_INIT) {
3083 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
3084 			ddi_fm_handler_unregister(nvme->n_dip);
3085 
3086 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
3087 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
3088 			pci_ereport_teardown(nvme->n_dip);
3089 
3090 		ddi_fm_fini(nvme->n_dip);
3091 	}
3092 
3093 	if (nvme->n_vendor != NULL)
3094 		strfree(nvme->n_vendor);
3095 
3096 	if (nvme->n_product != NULL)
3097 		strfree(nvme->n_product);
3098 
3099 	ddi_soft_state_free(nvme_state, instance);
3100 
3101 	return (DDI_SUCCESS);
3102 }
3103 
3104 static int
nvme_quiesce(dev_info_t * dip)3105 nvme_quiesce(dev_info_t *dip)
3106 {
3107 	int instance;
3108 	nvme_t *nvme;
3109 
3110 	instance = ddi_get_instance(dip);
3111 
3112 	nvme = ddi_get_soft_state(nvme_state, instance);
3113 
3114 	if (nvme == NULL)
3115 		return (DDI_FAILURE);
3116 
3117 	nvme_shutdown(nvme, NVME_CC_SHN_ABRUPT, B_TRUE);
3118 
3119 	(void) nvme_reset(nvme, B_TRUE);
3120 
3121 	return (DDI_FAILURE);
3122 }
3123 
3124 static int
nvme_fill_prp(nvme_cmd_t * cmd,bd_xfer_t * xfer)3125 nvme_fill_prp(nvme_cmd_t *cmd, bd_xfer_t *xfer)
3126 {
3127 	nvme_t *nvme = cmd->nc_nvme;
3128 	int nprp_page, nprp;
3129 	uint64_t *prp;
3130 
3131 	if (xfer->x_ndmac == 0)
3132 		return (DDI_FAILURE);
3133 
3134 	cmd->nc_sqe.sqe_dptr.d_prp[0] = xfer->x_dmac.dmac_laddress;
3135 	ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
3136 
3137 	if (xfer->x_ndmac == 1) {
3138 		cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
3139 		return (DDI_SUCCESS);
3140 	} else if (xfer->x_ndmac == 2) {
3141 		cmd->nc_sqe.sqe_dptr.d_prp[1] = xfer->x_dmac.dmac_laddress;
3142 		return (DDI_SUCCESS);
3143 	}
3144 
3145 	xfer->x_ndmac--;
3146 
3147 	nprp_page = nvme->n_pagesize / sizeof (uint64_t) - 1;
3148 	ASSERT(nprp_page > 0);
3149 	nprp = (xfer->x_ndmac + nprp_page - 1) / nprp_page;
3150 
3151 	/*
3152 	 * We currently don't support chained PRPs and set up our DMA
3153 	 * attributes to reflect that. If we still get an I/O request
3154 	 * that needs a chained PRP something is very wrong.
3155 	 */
3156 	VERIFY(nprp == 1);
3157 
3158 	cmd->nc_dma = kmem_cache_alloc(nvme->n_prp_cache, KM_SLEEP);
3159 	bzero(cmd->nc_dma->nd_memp, cmd->nc_dma->nd_len);
3160 
3161 	cmd->nc_sqe.sqe_dptr.d_prp[1] = cmd->nc_dma->nd_cookie.dmac_laddress;
3162 
3163 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
3164 	for (prp = (uint64_t *)cmd->nc_dma->nd_memp;
3165 	    xfer->x_ndmac > 0;
3166 	    prp++, xfer->x_ndmac--) {
3167 		*prp = xfer->x_dmac.dmac_laddress;
3168 		ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
3169 	}
3170 
3171 	(void) ddi_dma_sync(cmd->nc_dma->nd_dmah, 0, cmd->nc_dma->nd_len,
3172 	    DDI_DMA_SYNC_FORDEV);
3173 	return (DDI_SUCCESS);
3174 }
3175 
3176 static nvme_cmd_t *
nvme_create_nvm_cmd(nvme_namespace_t * ns,uint8_t opc,bd_xfer_t * xfer)3177 nvme_create_nvm_cmd(nvme_namespace_t *ns, uint8_t opc, bd_xfer_t *xfer)
3178 {
3179 	nvme_t *nvme = ns->ns_nvme;
3180 	nvme_cmd_t *cmd;
3181 
3182 	/*
3183 	 * Blkdev only sets BD_XFER_POLL when dumping, so don't sleep.
3184 	 */
3185 	cmd = nvme_alloc_cmd(nvme, (xfer->x_flags & BD_XFER_POLL) ?
3186 	    KM_NOSLEEP : KM_SLEEP);
3187 
3188 	if (cmd == NULL)
3189 		return (NULL);
3190 
3191 	cmd->nc_sqe.sqe_opc = opc;
3192 	cmd->nc_callback = nvme_bd_xfer_done;
3193 	cmd->nc_xfer = xfer;
3194 
3195 	switch (opc) {
3196 	case NVME_OPC_NVM_WRITE:
3197 	case NVME_OPC_NVM_READ:
3198 		VERIFY(xfer->x_nblks <= 0x10000);
3199 
3200 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
3201 
3202 		cmd->nc_sqe.sqe_cdw10 = xfer->x_blkno & 0xffffffffu;
3203 		cmd->nc_sqe.sqe_cdw11 = (xfer->x_blkno >> 32);
3204 		cmd->nc_sqe.sqe_cdw12 = (uint16_t)(xfer->x_nblks - 1);
3205 
3206 		if (nvme_fill_prp(cmd, xfer) != DDI_SUCCESS)
3207 			goto fail;
3208 		break;
3209 
3210 	case NVME_OPC_NVM_FLUSH:
3211 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
3212 		break;
3213 
3214 	default:
3215 		goto fail;
3216 	}
3217 
3218 	return (cmd);
3219 
3220 fail:
3221 	nvme_free_cmd(cmd);
3222 	return (NULL);
3223 }
3224 
3225 static void
nvme_bd_xfer_done(void * arg)3226 nvme_bd_xfer_done(void *arg)
3227 {
3228 	nvme_cmd_t *cmd = arg;
3229 	bd_xfer_t *xfer = cmd->nc_xfer;
3230 	int error = 0;
3231 
3232 	error = nvme_check_cmd_status(cmd);
3233 	nvme_free_cmd(cmd);
3234 
3235 	bd_xfer_done(xfer, error);
3236 }
3237 
3238 static void
nvme_bd_driveinfo(void * arg,bd_drive_t * drive)3239 nvme_bd_driveinfo(void *arg, bd_drive_t *drive)
3240 {
3241 	nvme_namespace_t *ns = arg;
3242 	nvme_t *nvme = ns->ns_nvme;
3243 
3244 	/*
3245 	 * blkdev maintains one queue size per instance (namespace),
3246 	 * but all namespace share the I/O queues.
3247 	 * TODO: need to figure out a sane default, or use per-NS I/O queues,
3248 	 * or change blkdev to handle EAGAIN
3249 	 */
3250 	drive->d_qsize = nvme->n_ioq_count * nvme->n_io_queue_len
3251 	    / nvme->n_namespace_count;
3252 
3253 	/*
3254 	 * d_maxxfer is not set, which means the value is taken from the DMA
3255 	 * attributes specified to bd_alloc_handle.
3256 	 */
3257 
3258 	drive->d_removable = B_FALSE;
3259 	drive->d_hotpluggable = B_FALSE;
3260 
3261 	bcopy(ns->ns_eui64, drive->d_eui64, sizeof (drive->d_eui64));
3262 	drive->d_target = ns->ns_id;
3263 	drive->d_lun = 0;
3264 
3265 	drive->d_model = nvme->n_idctl->id_model;
3266 	drive->d_model_len = sizeof (nvme->n_idctl->id_model);
3267 	drive->d_vendor = nvme->n_vendor;
3268 	drive->d_vendor_len = strlen(nvme->n_vendor);
3269 	drive->d_product = nvme->n_product;
3270 	drive->d_product_len = strlen(nvme->n_product);
3271 	drive->d_serial = nvme->n_idctl->id_serial;
3272 	drive->d_serial_len = sizeof (nvme->n_idctl->id_serial);
3273 	drive->d_revision = nvme->n_idctl->id_fwrev;
3274 	drive->d_revision_len = sizeof (nvme->n_idctl->id_fwrev);
3275 }
3276 
3277 static int
nvme_bd_mediainfo(void * arg,bd_media_t * media)3278 nvme_bd_mediainfo(void *arg, bd_media_t *media)
3279 {
3280 	nvme_namespace_t *ns = arg;
3281 
3282 	media->m_nblks = ns->ns_block_count;
3283 	media->m_blksize = ns->ns_block_size;
3284 	media->m_readonly = B_FALSE;
3285 	media->m_solidstate = B_TRUE;
3286 
3287 	media->m_pblksize = ns->ns_best_block_size;
3288 
3289 	return (0);
3290 }
3291 
3292 static int
nvme_bd_cmd(nvme_namespace_t * ns,bd_xfer_t * xfer,uint8_t opc)3293 nvme_bd_cmd(nvme_namespace_t *ns, bd_xfer_t *xfer, uint8_t opc)
3294 {
3295 	nvme_t *nvme = ns->ns_nvme;
3296 	nvme_cmd_t *cmd;
3297 	nvme_qpair_t *ioq;
3298 	boolean_t poll;
3299 	int ret;
3300 
3301 	if (nvme->n_dead)
3302 		return (EIO);
3303 
3304 	cmd = nvme_create_nvm_cmd(ns, opc, xfer);
3305 	if (cmd == NULL)
3306 		return (ENOMEM);
3307 
3308 	cmd->nc_sqid = (CPU->cpu_id % nvme->n_ioq_count) + 1;
3309 	ASSERT(cmd->nc_sqid <= nvme->n_ioq_count);
3310 	ioq = nvme->n_ioq[cmd->nc_sqid];
3311 
3312 	/*
3313 	 * Get the polling flag before submitting the command. The command may
3314 	 * complete immediately after it was submitted, which means we must
3315 	 * treat both cmd and xfer as if they have been freed already.
3316 	 */
3317 	poll = (xfer->x_flags & BD_XFER_POLL) != 0;
3318 
3319 	ret = nvme_submit_io_cmd(ioq, cmd);
3320 
3321 	if (ret != 0)
3322 		return (ret);
3323 
3324 	if (!poll)
3325 		return (0);
3326 
3327 	do {
3328 		cmd = nvme_retrieve_cmd(nvme, ioq);
3329 		if (cmd != NULL)
3330 			nvme_bd_xfer_done(cmd);
3331 		else
3332 			drv_usecwait(10);
3333 	} while (ioq->nq_active_cmds != 0);
3334 
3335 	return (0);
3336 }
3337 
3338 static int
nvme_bd_read(void * arg,bd_xfer_t * xfer)3339 nvme_bd_read(void *arg, bd_xfer_t *xfer)
3340 {
3341 	nvme_namespace_t *ns = arg;
3342 
3343 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_READ));
3344 }
3345 
3346 static int
nvme_bd_write(void * arg,bd_xfer_t * xfer)3347 nvme_bd_write(void *arg, bd_xfer_t *xfer)
3348 {
3349 	nvme_namespace_t *ns = arg;
3350 
3351 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_WRITE));
3352 }
3353 
3354 static int
nvme_bd_sync(void * arg,bd_xfer_t * xfer)3355 nvme_bd_sync(void *arg, bd_xfer_t *xfer)
3356 {
3357 	nvme_namespace_t *ns = arg;
3358 
3359 	if (ns->ns_nvme->n_dead)
3360 		return (EIO);
3361 
3362 	/*
3363 	 * If the volatile write cache is not present or not enabled the FLUSH
3364 	 * command is a no-op, so we can take a shortcut here.
3365 	 */
3366 	if (!ns->ns_nvme->n_write_cache_present) {
3367 		bd_xfer_done(xfer, ENOTSUP);
3368 		return (0);
3369 	}
3370 
3371 	if (!ns->ns_nvme->n_write_cache_enabled) {
3372 		bd_xfer_done(xfer, 0);
3373 		return (0);
3374 	}
3375 
3376 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_FLUSH));
3377 }
3378 
3379 static int
nvme_bd_devid(void * arg,dev_info_t * devinfo,ddi_devid_t * devid)3380 nvme_bd_devid(void *arg, dev_info_t *devinfo, ddi_devid_t *devid)
3381 {
3382 	nvme_namespace_t *ns = arg;
3383 
3384 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
3385 	if (*(uint64_t *)ns->ns_eui64 != 0) {
3386 		return (ddi_devid_init(devinfo, DEVID_SCSI3_WWN,
3387 		    sizeof (ns->ns_eui64), ns->ns_eui64, devid));
3388 	} else {
3389 		return (ddi_devid_init(devinfo, DEVID_ENCAP,
3390 		    strlen(ns->ns_devid), ns->ns_devid, devid));
3391 	}
3392 }
3393 
3394 static int
nvme_open(dev_t * devp,int flag,int otyp,cred_t * cred_p)3395 nvme_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
3396 {
3397 #ifndef __lock_lint
3398 	_NOTE(ARGUNUSED(cred_p));
3399 #endif
3400 	minor_t minor = getminor(*devp);
3401 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3402 	int nsid = NVME_MINOR_NSID(minor);
3403 	nvme_minor_state_t *nm;
3404 	int rv = 0;
3405 
3406 	if (otyp != OTYP_CHR)
3407 		return (EINVAL);
3408 
3409 	if (nvme == NULL)
3410 		return (ENXIO);
3411 
3412 	if (nsid > nvme->n_namespace_count)
3413 		return (ENXIO);
3414 
3415 	if (nvme->n_dead)
3416 		return (EIO);
3417 
3418 	nm = nsid == 0 ? &nvme->n_minor : &nvme->n_ns[nsid - 1].ns_minor;
3419 
3420 	mutex_enter(&nm->nm_mutex);
3421 	if (nm->nm_oexcl) {
3422 		rv = EBUSY;
3423 		goto out;
3424 	}
3425 
3426 	if (flag & FEXCL) {
3427 		if (nm->nm_ocnt != 0) {
3428 			rv = EBUSY;
3429 			goto out;
3430 		}
3431 		nm->nm_oexcl = B_TRUE;
3432 	}
3433 
3434 	nm->nm_ocnt++;
3435 
3436 out:
3437 	mutex_exit(&nm->nm_mutex);
3438 	return (rv);
3439 
3440 }
3441 
3442 static int
nvme_close(dev_t dev,int flag,int otyp,cred_t * cred_p)3443 nvme_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3444 {
3445 #ifndef __lock_lint
3446 	_NOTE(ARGUNUSED(cred_p));
3447 	_NOTE(ARGUNUSED(flag));
3448 #endif
3449 	minor_t minor = getminor(dev);
3450 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3451 	int nsid = NVME_MINOR_NSID(minor);
3452 	nvme_minor_state_t *nm;
3453 
3454 	if (otyp != OTYP_CHR)
3455 		return (ENXIO);
3456 
3457 	if (nvme == NULL)
3458 		return (ENXIO);
3459 
3460 	if (nsid > nvme->n_namespace_count)
3461 		return (ENXIO);
3462 
3463 	nm = nsid == 0 ? &nvme->n_minor : &nvme->n_ns[nsid - 1].ns_minor;
3464 
3465 	mutex_enter(&nm->nm_mutex);
3466 	if (nm->nm_oexcl)
3467 		nm->nm_oexcl = B_FALSE;
3468 
3469 	ASSERT(nm->nm_ocnt > 0);
3470 	nm->nm_ocnt--;
3471 	mutex_exit(&nm->nm_mutex);
3472 
3473 	return (0);
3474 }
3475 
3476 static int
nvme_ioctl_identify(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3477 nvme_ioctl_identify(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3478     cred_t *cred_p)
3479 {
3480 	_NOTE(ARGUNUSED(cred_p));
3481 	int rv = 0;
3482 	void *idctl;
3483 
3484 	if ((mode & FREAD) == 0)
3485 		return (EPERM);
3486 
3487 	if (nioc->n_len < NVME_IDENTIFY_BUFSIZE)
3488 		return (EINVAL);
3489 
3490 	if ((rv = nvme_identify(nvme, nsid, (void **)&idctl)) != 0)
3491 		return (rv);
3492 
3493 	if (ddi_copyout(idctl, (void *)nioc->n_buf, NVME_IDENTIFY_BUFSIZE, mode)
3494 	    != 0)
3495 		rv = EFAULT;
3496 
3497 	kmem_free(idctl, NVME_IDENTIFY_BUFSIZE);
3498 
3499 	return (rv);
3500 }
3501 
3502 static int
nvme_ioctl_capabilities(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3503 nvme_ioctl_capabilities(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3504     int mode, cred_t *cred_p)
3505 {
3506 	_NOTE(ARGUNUSED(nsid, cred_p));
3507 	int rv = 0;
3508 	nvme_reg_cap_t cap = { 0 };
3509 	nvme_capabilities_t nc;
3510 
3511 	if ((mode & FREAD) == 0)
3512 		return (EPERM);
3513 
3514 	if (nioc->n_len < sizeof (nc))
3515 		return (EINVAL);
3516 
3517 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
3518 
3519 	/*
3520 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to
3521 	 * specify the base page size of 4k (1<<12), so add 12 here to
3522 	 * get the real page size value.
3523 	 */
3524 	nc.mpsmax = 1 << (12 + cap.b.cap_mpsmax);
3525 	nc.mpsmin = 1 << (12 + cap.b.cap_mpsmin);
3526 
3527 	if (ddi_copyout(&nc, (void *)nioc->n_buf, sizeof (nc), mode) != 0)
3528 		rv = EFAULT;
3529 
3530 	return (rv);
3531 }
3532 
3533 static int
nvme_ioctl_get_logpage(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3534 nvme_ioctl_get_logpage(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3535     int mode, cred_t *cred_p)
3536 {
3537 	_NOTE(ARGUNUSED(cred_p));
3538 	void *log = NULL;
3539 	size_t bufsize = 0;
3540 	int rv = 0;
3541 
3542 	if ((mode & FREAD) == 0)
3543 		return (EPERM);
3544 
3545 	switch (nioc->n_arg) {
3546 	case NVME_LOGPAGE_ERROR:
3547 		if (nsid != 0)
3548 			return (EINVAL);
3549 		break;
3550 	case NVME_LOGPAGE_HEALTH:
3551 		if (nsid != 0 && nvme->n_idctl->id_lpa.lp_smart == 0)
3552 			return (EINVAL);
3553 
3554 		if (nsid == 0)
3555 			nsid = (uint32_t)-1;
3556 
3557 		break;
3558 	case NVME_LOGPAGE_FWSLOT:
3559 		if (nsid != 0)
3560 			return (EINVAL);
3561 		break;
3562 	default:
3563 		return (EINVAL);
3564 	}
3565 
3566 	if (nvme_get_logpage(nvme, &log, &bufsize, nioc->n_arg, nsid)
3567 	    != DDI_SUCCESS)
3568 		return (EIO);
3569 
3570 	if (nioc->n_len < bufsize) {
3571 		kmem_free(log, bufsize);
3572 		return (EINVAL);
3573 	}
3574 
3575 	if (ddi_copyout(log, (void *)nioc->n_buf, bufsize, mode) != 0)
3576 		rv = EFAULT;
3577 
3578 	nioc->n_len = bufsize;
3579 	kmem_free(log, bufsize);
3580 
3581 	return (rv);
3582 }
3583 
3584 static int
nvme_ioctl_get_features(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3585 nvme_ioctl_get_features(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3586     int mode, cred_t *cred_p)
3587 {
3588 	_NOTE(ARGUNUSED(cred_p));
3589 	void *buf = NULL;
3590 	size_t bufsize = 0;
3591 	uint32_t res = 0;
3592 	uint8_t feature;
3593 	int rv = 0;
3594 
3595 	if ((mode & FREAD) == 0)
3596 		return (EPERM);
3597 
3598 	if ((nioc->n_arg >> 32) > 0xff)
3599 		return (EINVAL);
3600 
3601 	feature = (uint8_t)(nioc->n_arg >> 32);
3602 
3603 	switch (feature) {
3604 	case NVME_FEAT_ARBITRATION:
3605 	case NVME_FEAT_POWER_MGMT:
3606 	case NVME_FEAT_TEMPERATURE:
3607 	case NVME_FEAT_ERROR:
3608 	case NVME_FEAT_NQUEUES:
3609 	case NVME_FEAT_INTR_COAL:
3610 	case NVME_FEAT_WRITE_ATOM:
3611 	case NVME_FEAT_ASYNC_EVENT:
3612 	case NVME_FEAT_PROGRESS:
3613 		if (nsid != 0)
3614 			return (EINVAL);
3615 		break;
3616 
3617 	case NVME_FEAT_INTR_VECT:
3618 		if (nsid != 0)
3619 			return (EINVAL);
3620 
3621 		res = nioc->n_arg & 0xffffffffUL;
3622 		if (res >= nvme->n_intr_cnt)
3623 			return (EINVAL);
3624 		break;
3625 
3626 	case NVME_FEAT_LBA_RANGE:
3627 		if (nvme->n_lba_range_supported == B_FALSE)
3628 			return (EINVAL);
3629 
3630 		if (nsid == 0 ||
3631 		    nsid > nvme->n_namespace_count)
3632 			return (EINVAL);
3633 
3634 		break;
3635 
3636 	case NVME_FEAT_WRITE_CACHE:
3637 		if (nsid != 0)
3638 			return (EINVAL);
3639 
3640 		if (!nvme->n_write_cache_present)
3641 			return (EINVAL);
3642 
3643 		break;
3644 
3645 	case NVME_FEAT_AUTO_PST:
3646 		if (nsid != 0)
3647 			return (EINVAL);
3648 
3649 		if (!nvme->n_auto_pst_supported)
3650 			return (EINVAL);
3651 
3652 		break;
3653 
3654 	default:
3655 		return (EINVAL);
3656 	}
3657 
3658 	rv = nvme_get_features(nvme, nsid, feature, &res, &buf, &bufsize);
3659 	if (rv != 0)
3660 		return (rv);
3661 
3662 	if (nioc->n_len < bufsize) {
3663 		kmem_free(buf, bufsize);
3664 		return (EINVAL);
3665 	}
3666 
3667 	if (buf && ddi_copyout(buf, (void*)nioc->n_buf, bufsize, mode) != 0)
3668 		rv = EFAULT;
3669 
3670 	kmem_free(buf, bufsize);
3671 	nioc->n_arg = res;
3672 	nioc->n_len = bufsize;
3673 
3674 	return (rv);
3675 }
3676 
3677 static int
nvme_ioctl_intr_cnt(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3678 nvme_ioctl_intr_cnt(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3679     cred_t *cred_p)
3680 {
3681 	_NOTE(ARGUNUSED(nsid, mode, cred_p));
3682 
3683 	if ((mode & FREAD) == 0)
3684 		return (EPERM);
3685 
3686 	nioc->n_arg = nvme->n_intr_cnt;
3687 	return (0);
3688 }
3689 
3690 static int
nvme_ioctl_version(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3691 nvme_ioctl_version(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3692     cred_t *cred_p)
3693 {
3694 	_NOTE(ARGUNUSED(nsid, cred_p));
3695 	int rv = 0;
3696 
3697 	if ((mode & FREAD) == 0)
3698 		return (EPERM);
3699 
3700 	if (nioc->n_len < sizeof (nvme->n_version))
3701 		return (ENOMEM);
3702 
3703 	if (ddi_copyout(&nvme->n_version, (void *)nioc->n_buf,
3704 	    sizeof (nvme->n_version), mode) != 0)
3705 		rv = EFAULT;
3706 
3707 	return (rv);
3708 }
3709 
3710 static int
nvme_ioctl_format(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3711 nvme_ioctl_format(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3712     cred_t *cred_p)
3713 {
3714 	_NOTE(ARGUNUSED(mode));
3715 	nvme_format_nvm_t frmt = { 0 };
3716 	int c_nsid = nsid != 0 ? nsid - 1 : 0;
3717 
3718 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3719 		return (EPERM);
3720 
3721 	frmt.r = nioc->n_arg & 0xffffffff;
3722 
3723 	/*
3724 	 * Check whether the FORMAT NVM command is supported.
3725 	 */
3726 	if (nvme->n_idctl->id_oacs.oa_format == 0)
3727 		return (EINVAL);
3728 
3729 	/*
3730 	 * Don't allow format or secure erase of individual namespace if that
3731 	 * would cause a format or secure erase of all namespaces.
3732 	 */
3733 	if (nsid != 0 && nvme->n_idctl->id_fna.fn_format != 0)
3734 		return (EINVAL);
3735 
3736 	if (nsid != 0 && frmt.b.fm_ses != NVME_FRMT_SES_NONE &&
3737 	    nvme->n_idctl->id_fna.fn_sec_erase != 0)
3738 		return (EINVAL);
3739 
3740 	/*
3741 	 * Don't allow formatting with Protection Information.
3742 	 */
3743 	if (frmt.b.fm_pi != 0 || frmt.b.fm_pil != 0 || frmt.b.fm_ms != 0)
3744 		return (EINVAL);
3745 
3746 	/*
3747 	 * Don't allow formatting using an illegal LBA format, or any LBA format
3748 	 * that uses metadata.
3749 	 */
3750 	if (frmt.b.fm_lbaf > nvme->n_ns[c_nsid].ns_idns->id_nlbaf ||
3751 	    nvme->n_ns[c_nsid].ns_idns->id_lbaf[frmt.b.fm_lbaf].lbaf_ms != 0)
3752 		return (EINVAL);
3753 
3754 	/*
3755 	 * Don't allow formatting using an illegal Secure Erase setting.
3756 	 */
3757 	if (frmt.b.fm_ses > NVME_FRMT_MAX_SES ||
3758 	    (frmt.b.fm_ses == NVME_FRMT_SES_CRYPTO &&
3759 	    nvme->n_idctl->id_fna.fn_crypt_erase == 0))
3760 		return (EINVAL);
3761 
3762 	if (nsid == 0)
3763 		nsid = (uint32_t)-1;
3764 
3765 	return (nvme_format_nvm(nvme, nsid, frmt.b.fm_lbaf, B_FALSE, 0, B_FALSE,
3766 	    frmt.b.fm_ses));
3767 }
3768 
3769 static int
nvme_ioctl_detach(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3770 nvme_ioctl_detach(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3771     cred_t *cred_p)
3772 {
3773 	_NOTE(ARGUNUSED(nioc, mode));
3774 	int rv = 0;
3775 
3776 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3777 		return (EPERM);
3778 
3779 	if (nsid == 0)
3780 		return (EINVAL);
3781 
3782 	rv = bd_detach_handle(nvme->n_ns[nsid - 1].ns_bd_hdl);
3783 	if (rv != DDI_SUCCESS)
3784 		rv = EBUSY;
3785 
3786 	return (rv);
3787 }
3788 
3789 static int
nvme_ioctl_attach(nvme_t * nvme,int nsid,nvme_ioctl_t * nioc,int mode,cred_t * cred_p)3790 nvme_ioctl_attach(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3791     cred_t *cred_p)
3792 {
3793 	_NOTE(ARGUNUSED(nioc, mode));
3794 	nvme_identify_nsid_t *idns;
3795 	int rv = 0;
3796 
3797 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3798 		return (EPERM);
3799 
3800 	if (nsid == 0)
3801 		return (EINVAL);
3802 
3803 	/*
3804 	 * Identify namespace again, free old identify data.
3805 	 */
3806 	idns = nvme->n_ns[nsid - 1].ns_idns;
3807 	if (nvme_init_ns(nvme, nsid) != DDI_SUCCESS)
3808 		return (EIO);
3809 
3810 	kmem_free(idns, sizeof (nvme_identify_nsid_t));
3811 
3812 	rv = bd_attach_handle(nvme->n_dip, nvme->n_ns[nsid - 1].ns_bd_hdl);
3813 	if (rv != DDI_SUCCESS)
3814 		rv = EBUSY;
3815 
3816 	return (rv);
3817 }
3818 
3819 static int
nvme_ioctl(dev_t dev,int cmd,intptr_t arg,int mode,cred_t * cred_p,int * rval_p)3820 nvme_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *cred_p,
3821     int *rval_p)
3822 {
3823 #ifndef __lock_lint
3824 	_NOTE(ARGUNUSED(rval_p));
3825 #endif
3826 	minor_t minor = getminor(dev);
3827 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3828 	int nsid = NVME_MINOR_NSID(minor);
3829 	int rv = 0;
3830 	nvme_ioctl_t nioc;
3831 
3832 	int (*nvme_ioctl[])(nvme_t *, int, nvme_ioctl_t *, int, cred_t *) = {
3833 		NULL,
3834 		nvme_ioctl_identify,
3835 		nvme_ioctl_identify,
3836 		nvme_ioctl_capabilities,
3837 		nvme_ioctl_get_logpage,
3838 		nvme_ioctl_get_features,
3839 		nvme_ioctl_intr_cnt,
3840 		nvme_ioctl_version,
3841 		nvme_ioctl_format,
3842 		nvme_ioctl_detach,
3843 		nvme_ioctl_attach
3844 	};
3845 
3846 	if (nvme == NULL)
3847 		return (ENXIO);
3848 
3849 	if (nsid > nvme->n_namespace_count)
3850 		return (ENXIO);
3851 
3852 	if (IS_DEVCTL(cmd))
3853 		return (ndi_devctl_ioctl(nvme->n_dip, cmd, arg, mode, 0));
3854 
3855 #ifdef _MULTI_DATAMODEL
3856 	switch (ddi_model_convert_from(mode & FMODELS)) {
3857 	case DDI_MODEL_ILP32: {
3858 		nvme_ioctl32_t nioc32;
3859 		if (ddi_copyin((void*)arg, &nioc32, sizeof (nvme_ioctl32_t),
3860 		    mode) != 0)
3861 			return (EFAULT);
3862 		nioc.n_len = nioc32.n_len;
3863 		nioc.n_buf = nioc32.n_buf;
3864 		nioc.n_arg = nioc32.n_arg;
3865 		break;
3866 	}
3867 	case DDI_MODEL_NONE:
3868 #endif
3869 		if (ddi_copyin((void*)arg, &nioc, sizeof (nvme_ioctl_t), mode)
3870 		    != 0)
3871 			return (EFAULT);
3872 #ifdef _MULTI_DATAMODEL
3873 		break;
3874 	}
3875 #endif
3876 
3877 	if (nvme->n_dead && cmd != NVME_IOC_DETACH)
3878 		return (EIO);
3879 
3880 
3881 	if (cmd == NVME_IOC_IDENTIFY_CTRL) {
3882 		/*
3883 		 * This makes NVME_IOC_IDENTIFY_CTRL work the same on devctl and
3884 		 * attachment point nodes.
3885 		 */
3886 		nsid = 0;
3887 	} else if (cmd == NVME_IOC_IDENTIFY_NSID && nsid == 0) {
3888 		/*
3889 		 * This makes NVME_IOC_IDENTIFY_NSID work on a devctl node, it
3890 		 * will always return identify data for namespace 1.
3891 		 */
3892 		nsid = 1;
3893 	}
3894 
3895 	if (IS_NVME_IOC(cmd) && nvme_ioctl[NVME_IOC_CMD(cmd)] != NULL)
3896 		rv = nvme_ioctl[NVME_IOC_CMD(cmd)](nvme, nsid, &nioc, mode,
3897 		    cred_p);
3898 	else
3899 		rv = EINVAL;
3900 
3901 #ifdef _MULTI_DATAMODEL
3902 	switch (ddi_model_convert_from(mode & FMODELS)) {
3903 	case DDI_MODEL_ILP32: {
3904 		nvme_ioctl32_t nioc32;
3905 
3906 		nioc32.n_len = (size32_t)nioc.n_len;
3907 		nioc32.n_buf = (uintptr32_t)nioc.n_buf;
3908 		nioc32.n_arg = nioc.n_arg;
3909 
3910 		if (ddi_copyout(&nioc32, (void *)arg, sizeof (nvme_ioctl32_t),
3911 		    mode) != 0)
3912 			return (EFAULT);
3913 		break;
3914 	}
3915 	case DDI_MODEL_NONE:
3916 #endif
3917 		if (ddi_copyout(&nioc, (void *)arg, sizeof (nvme_ioctl_t), mode)
3918 		    != 0)
3919 			return (EFAULT);
3920 #ifdef _MULTI_DATAMODEL
3921 		break;
3922 	}
3923 #endif
3924 
3925 	return (rv);
3926 }
3927