xref: /illumos-gate/usr/src/uts/common/io/nvme/nvme.c (revision da4e43d8b1f65447b33215ad3fd9bc9820cb7e82)
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 (c) 2016 The MathWorks, Inc.  All rights reserved.
14  * Copyright 2019 Unix Software Ltd.
15  * Copyright 2020 Joyent, Inc.
16  * Copyright 2020 Racktop Systems.
17  * Copyright 2026 Oxide Computer Company.
18  * Copyright 2022 OmniOS Community Edition (OmniOSce) Association.
19  * Copyright 2022 Tintri by DDN, Inc. All rights reserved.
20  */
21 
22 /*
23  * blkdev driver for NVMe compliant storage devices
24  *
25  * This driver targets and is designed to support all NVMe 1.x and NVMe 2.x
26  * devices. Features are added to the driver as we encounter devices that
27  * require them and our needs, so some commands or log pages may not take
28  * advantage of newer features that devices support at this time. When you
29  * encounter such a case, it is generally fine to add that support to the driver
30  * as long as you take care to ensure that the requisite device version is met
31  * before using it.
32  *
33  * The driver has only been tested on x86 systems and will not work on big-
34  * endian systems without changes to the code accessing registers and data
35  * structures used by the hardware.
36  *
37  * ---------------
38  * Interrupt Usage
39  * ---------------
40  *
41  * The driver will use a single interrupt while configuring the device as the
42  * specification requires, but contrary to the specification it will try to use
43  * a single-message MSI(-X) or FIXED interrupt. Later in the attach process it
44  * will switch to multiple-message MSI(-X) if supported. The driver wants to
45  * have one interrupt vector per CPU, but it will work correctly if less are
46  * available. Interrupts can be shared by queues, the interrupt handler will
47  * iterate through the I/O queue array by steps of n_intr_cnt. Usually only
48  * the admin queue will share an interrupt with one I/O queue. The interrupt
49  * handler will retrieve completed commands from all queues sharing an interrupt
50  * vector and will post them to a taskq for completion processing.
51  *
52  * ------------------
53  * Command Processing
54  * ------------------
55  *
56  * NVMe devices can have up to 65535 I/O queue pairs, with each queue holding up
57  * to 65536 I/O commands. The driver will configure one I/O queue pair per
58  * available interrupt vector, with the queue length usually much smaller than
59  * the maximum of 65536. If the hardware doesn't provide enough queues, fewer
60  * interrupt vectors will be used.
61  *
62  * Additionally the hardware provides a single special admin queue pair that can
63  * hold up to 4096 admin commands.
64  *
65  * From the hardware perspective both queues of a queue pair are independent,
66  * but they share some driver state: the command array (holding pointers to
67  * commands currently being processed by the hardware) and the active command
68  * counter. Access to a submission queue and the shared state is protected by
69  * nq_mutex; completion queue is protected by ncq_mutex.
70  *
71  * When a command is submitted to a queue pair the active command counter is
72  * incremented and a pointer to the command is stored in the command array. The
73  * array index is used as command identifier (CID) in the submission queue
74  * entry. Some commands may take a very long time to complete, and if the queue
75  * wraps around in that time a submission may find the next array slot to still
76  * be used by a long-running command. In this case the array is sequentially
77  * searched for the next free slot. The length of the command array is the same
78  * as the configured queue length. Queue overrun is prevented by the semaphore,
79  * so a command submission may block if the queue is full.
80  *
81  * ------------------
82  * Polled I/O Support
83  * ------------------
84  *
85  * For kernel core dump support the driver can do polled I/O. As interrupts are
86  * turned off while dumping the driver will just submit a command in the regular
87  * way, and then repeatedly attempt a command retrieval until it gets the
88  * command back.
89  *
90  * -----------------
91  * Namespace Support
92  * -----------------
93  *
94  * NVMe devices can have multiple namespaces, each being a independent data
95  * store. The driver supports multiple namespaces and creates a blkdev interface
96  * for each namespace found. Namespaces can have various attributes to support
97  * protection information. This driver does not support any of this and ignores
98  * namespaces that have these attributes.
99  *
100  * As of NVMe 1.1 namespaces can have an 64bit Extended Unique Identifier
101  * (EUI64), and NVMe 1.2 introduced an additional 128bit Namespace Globally
102  * Unique Identifier (NGUID). This driver uses either the NGUID or the EUI64
103  * if present to generate the devid, and passes the EUI64 to blkdev to use it
104  * in the device node names.
105  *
106  * When a device has more than (2 << NVME_MINOR_INST_SHIFT) - 2 namespaces in a
107  * single controller, additional namespaces will not have minor nodes created.
108  * They can still be used and specified by the controller and libnvme. This
109  * limit is trying to balance the number of controllers and namespaces while
110  * fitting within the constraints of MAXMIN32, aka a 32-bit device number which
111  * only has 18-bits for the minor number. See the minor node section for more
112  * information.
113  *
114  * The driver supports namespace management, meaning the ability to create and
115  * destroy namespaces, and to attach and detach namespaces from controllers.
116  * Each namespace has an associated nvme_ns_state_t, which transitions through
117  * several states. The UNALLOCATED, ALLOCATED, and ACTIVE states are states that
118  * are defined by the NVMe specification. Not all ACTIVE namespaces may be
119  * attached to blkdev(4D) due to the use of features we don't support, for
120  * example, metadata protection. Such namespaces are automatically in the
121  * NOT_IGNORED state. Once they are attached to blkdev they enter the ATTACHED
122  * state.
123  *
124  * By default, a device can only transition one such state at a time. Each
125  * command that transitions between states has a corresponding array of errnos
126  * to use to transition. Examples of this are the nvme_ns_delete_states[],
127  * nvme_ctrl_attach_states[], etc. These dictate whether it is okay or not for a
128  * command that changes state to occur or not based on the current state. Each
129  * of these returns a specific error allowing one to understand why something
130  * isn't in the proper state. This allows library consumers to determine whether
131  * or not a namespace is already in the current state it's targeting to be
132  * ignored or not. The following diagram summarizes namespace transitions:
133  *
134  *                       +-------------+
135  *                       |             |
136  *                       | Unallocated |
137  *                       |             |
138  *                       +-------------+
139  *                          |       ^
140  *                          |       |
141  * Namespace Management: . .*       * . . . Namespace Management:
142  * Create                   |       |       Delete
143  * NVME_IOC_NS_CREATE       |       |       NVME_IOC_NS_DELETE
144  *                          v       |
145  *                       +-------------+
146  *                       |             |
147  *                       |  Allocated  |
148  *                       |             |
149  *                       +-------------+
150  *                          |       ^
151  *                          |       |
152  * Namespace Attachment: . .*       * . . . Namespace Attachment:
153  * Controller Attach        |       |       Controller Detach
154  * NVME_IOC_CTRL_ATTACH     |       |       NVME_IOC_CTRL_DETACH
155  *                          v       |
156  *              +------------+      |
157  *              |            |      |     +----------+
158  *              |   Active   |>-----+----<|   Not    |
159  *              |            |--*-------->| Ignored  |
160  *              +------------+  .         +----------+
161  *                              .           |      ^
162  *    automatic kernel transition           |      |
163  *                                          |      * . . blkdev Detach
164  *                       blkdev attach  . . *      |     NVME_IOC_BD_DETACH
165  *                       NVME_IOC_BD_ATTACH |      |
166  *                                          v      |
167  *                                        +----------+
168  *                                        |          |
169  *                                        |  blkdev  |
170  *                                        | attached |
171  *                                        |          |
172  *                                        +----------+
173  *
174  * -----------
175  * Minor nodes
176  * -----------
177  *
178  * For each NVMe device the driver exposes one minor node for the controller and
179  * one minor node for each namespace. The only operations supported by those
180  * minor nodes are open(9E), close(9E), and ioctl(9E). This serves as the
181  * primary control interface for the devices. The character device is a private
182  * interface and we attempt stability through libnvme and more so nvmeadm.
183  *
184  * The controller minor node is much more flexible than the namespace minor node
185  * and should be preferred. The controller node allows one to target any
186  * namespace that the device has, while the namespace is limited in what it can
187  * acquire. While the namespace minor exists, it should not be relied upon and
188  * is not by libnvme.
189  *
190  * The minor number space is split in two. We use the lower part to support the
191  * controller and namespaces as described above in the 'Namespace Support'
192  * section. The second set is used for cloning opens. We set aside one million
193  * minors for this purpose. We utilize a cloning open so that way we can have
194  * per-file_t state. This is how we end up implementing and tracking locking
195  * state and related.
196  *
197  * When we have this cloned open, then we allocate a new nvme_minor_t which gets
198  * its minor number from the nvme_open_minors id_space_t and is stored in the
199  * nvme_open_minors_avl. While someone calls open on a controller or namespace
200  * minor, everything else occurs in the context of one of these ephemeral
201  * minors.
202  *
203  * ------------------------------------
204  * ioctls, Errors, and Exclusive Access
205  * ------------------------------------
206  *
207  * All of the logical commands that one can issue are driven through the
208  * ioctl(9E) interface. All of our ioctls have a similar shape where they
209  * all include the 'nvme_ioctl_common_t' as their first member.
210  *
211  * This common ioctl structure is used to communicate the namespace that should
212  * be targeted. When the namespace is left as 0, then that indicates that it
213  * should target whatever the default is of the minor node. For a namespace
214  * minor, that will be transparently rewritten to the namespace's namespace id.
215  *
216  * In addition, the nvme_ioctl_common_t structure also has a standard error
217  * return. Our goal in our ioctl path is to ensure that we have useful semantic
218  * errors as much as possible. EINVAL, EIO, etc. are all overloaded. Instead as
219  * long as we can copy in our structure, then we will set a semantic error. If
220  * we have an error from the controller, then that will be included there.
221  *
222  * Each command has a specific policy that controls whether or not it is allowed
223  * on the namespace or controller minor, whether the broadcast namespace is
224  * allowed, various settings around what kind of exclusive access is allowed,
225  * and more. Each of these is wrapped up in a bit of policy described by the
226  * 'nvme_ioctl_check_t' structure.
227  *
228  * The device provides a form of exclusion in the form of both a
229  * controller-level and namespace-level read and write lock. Most operations do
230  * not require a lock (e.g. get log page, identify, etc.), but a few do (e.g.
231  * format nvm, firmware related activity, etc.). A read lock guarantees that you
232  * can complete your operation without interference, but read locks are not
233  * required. If you don't take a read lock and someone comes in with a write
234  * lock, then subsequent operations will fail with a semantic error indicating
235  * that you were blocked due to this.
236  *
237  * Here are some of the rules that govern our locks:
238  *
239  * 1. Writers starve readers. Any readers are allowed to finish when there is a
240  *    pending writer; however, all subsequent readers will be blocked upon that
241  *    writer.
242  * 2. A controller write lock takes priority over all other locks. Put
243  *    differently a controller writer not only starves subsequent controller
244  *    readers, but also all namespace read and write locks.
245  * 3. Each namespace lock is independent.
246  * 4. At most a single namespace lock may be owned.
247  * 5. If you own a namespace lock, you may not take a controller lock (to help
248  *    with lock ordering).
249  * 6. In a similar spirit, if you own a controller write lock, you may not take
250  *    any namespace lock. Someone with the controller write lock can perform any
251  *    operations that they need to. However, if you have a controller read lock
252  *    you may take any namespace lock.
253  * 7. There is no ability to upgrade a read lock to a write lock.
254  * 8. There is no recursive locking.
255  *
256  * While there's a lot there to keep track of, the goals of these are to
257  * constrain things so as to avoid deadlock. This is more complex than the
258  * original implementation in the driver which only allowed for an exclusive
259  * open that was tied to the thread. The first issue with tying this to the
260  * thread was that that didn't work well for software that utilized thread
261  * pools, like complex daemons. The second issue is that we want the ability for
262  * daemons, such as a FRU monitor, to be able to retain a file descriptor to the
263  * device without blocking others from taking action except during critical
264  * periods.
265  *
266  * In particular to enable something like libnvme, we didn't want someone to
267  * have to open and close the file descriptor to change what kind of exclusive
268  * access they desired.
269  *
270  * There are two different sets of data structures that we employ for tracking
271  * locking information:
272  *
273  * 1) The nvme_lock_t structure is contained in both the nvme_t and the
274  * nvme_namespace_t and tracks the current writer, readers, and pending writers
275  * and readers. Each of these lists or the writer pointer all refer to our
276  * second data structure.
277  *
278  * When a lock is owned by a single writer, then the nl_writer field is set to a
279  * specific minor's lock data structure. If instead readers are present, then
280  * the nl_readers list_t is not empty. An invariant of the system is that if
281  * nl_writer is non-NULL, nl_readers must be empty and conversely, if nl_readers
282  * is not empty, nl_writer must be NULL.
283  *
284  * 2) The nvme_minor_lock_info_t exists in the nvme_minor_t. There is one
285  * information structure which represents the minor's controller lock and a
286  * second one that represents the minor's namespace lock. The members of this
287  * are broken into tracking what the current lock is and what it targets. It
288  * also several members that are intended for debugging (nli_last_change,
289  * nli_acq_kthread, etc.).
290  *
291  * While the minor has two different lock information structures, our rules
292  * ensure that only one of the two can be pending and that they shouldn't result
293  * in a deadlock. When a lock is pending, the caller is sleeping on the minor's
294  * nm_cv member.
295  *
296  * These relationships are represented in the following image which shows a
297  * controller write lock being held with a pending readers on the controller
298  * lock and pending writers on one of the controller's namespaces.
299  *
300  *  +---------+
301  *  | nvme_t  |
302  *  |         |
303  *  | n_lock -|-------+
304  *  | n_ns -+ |       |                          +-----------------------------+
305  *  +-------|-+   +-----------------+            | nvme_minor_t                |
306  *          |     | nvme_lock_t     |            |                             |
307  *          |     |                 |            |  +------------------------+ |
308  *          |     | writer        --|-------------->| nvme_minor_lock_info_t | |
309  *          |     | reader list     |            |  | nm_ctrl_lock           | |
310  *          |     | pending writers |            |  +------------------------+ |
311  *          |     | pending readers |------+     |  +------------------------+ |
312  *          |     +-----------------+      |     |  | nvme_minor_lock_info_t | |
313  *          |                              |     |  | nm_ns_lock             | |
314  *          |                              |     |  +------------------------+ |
315  *          |                              |     +-----------------------------+
316  *  +------------------+                   |                 +-----------------+
317  *  | nvme_namespace_t |                   |                 | nvme_minor_t    |
318  *  |                  |                   |                 |                 |
319  *  | ns_lock ---+     |                   |                 | +-------------+ |
320  *  +------------|-----+                   +-----------------|>|nm_ctrl_lock | |
321  *               |                                           | +-------------+ |
322  *               v                                           +-----------------+
323  *     +------------------+                                         ...
324  *     | nvme_lock_t      |                                  +-----------------+
325  *     |                  |                                  | nvme_minor_t    |
326  *     | writer           |                                  |                 |
327  *     | reader list      |                                  | +-------------+ |
328  *     | pending writers -|-----------------+                | |nm_ctrl_lock | |
329  *     | pending readers  |                 |                | +-------------+ |
330  *     +------------------+                 |                +-----------------+
331  *         +-----------------------------+  |  +-----------------------------+
332  *         | nvme_minor_t                |  |  | nvme_minor_t                |
333  *         |                             |  |  |                             |
334  *         |  +------------------------+ |  |  |  +------------------------+ |
335  *         |  | nvme_minor_lock_info_t | |  |  |  | nvme_minor_lock_info_t | |
336  *         |  | nm_ctrl_lock           | |  |  |  | nm_ctrl_lock           | |
337  *         |  +------------------------+ |  |  |  +------------------------+ |
338  *         |  +------------------------+ |  v  |  +------------------------+ |
339  *         |  | nvme_minor_lock_info_t |-|-----|->| nvme_minor_lock_info_t | |
340  *         |  | nm_ns_lock             | |     |  | nm_ns_lock             | |
341  *         |  +------------------------+ |     |  +------------------------+ |
342  *         +-----------------------------+     +-----------------------------+
343  *
344  * ----------------
345  * Blkdev Interface
346  * ----------------
347  *
348  * This driver uses blkdev to do all the heavy lifting involved with presenting
349  * a disk device to the system. As a result, the processing of I/O requests is
350  * relatively simple as blkdev takes care of partitioning, boundary checks, DMA
351  * setup, and splitting of transfers into manageable chunks.
352  *
353  * I/O requests coming in from blkdev are turned into NVM commands and posted to
354  * an I/O queue. The queue is selected by taking the CPU id modulo the number of
355  * queues. There is currently no timeout handling of I/O commands.
356  *
357  * Blkdev also supports querying device/media information and generating a
358  * devid. The driver reports the best block size as determined by the namespace
359  * format back to blkdev as physical block size to support partition and block
360  * alignment. The devid is either based on the namespace GUID or EUI64, if
361  * present, or composed using the device vendor ID, model number, serial number,
362  * and the namespace ID.
363  *
364  * --------------
365  * Error Handling
366  * --------------
367  *
368  * Error handling is currently limited to detecting fatal hardware errors,
369  * either by asynchronous events, or synchronously through command status or
370  * admin command timeouts. In case of severe errors the device is fenced off,
371  * all further requests will return EIO. FMA is then called to fault the device.
372  *
373  * The hardware has a limit for outstanding asynchronous event requests. Before
374  * this limit is known the driver assumes it is at least 1 and posts a single
375  * asynchronous request. Later when the limit is known more asynchronous event
376  * requests are posted to allow quicker reception of error information. When an
377  * asynchronous event is posted by the hardware the driver will parse the error
378  * status fields and log information or fault the device, depending on the
379  * severity of the asynchronous event. The asynchronous event request is then
380  * reused and posted to the admin queue again.
381  *
382  * On command completion the command status is checked for errors. In case of
383  * errors indicating a driver bug the driver panics. Almost all other error
384  * status values just cause EIO to be returned.
385  *
386  * Command timeouts are currently detected for all admin commands except
387  * asynchronous event requests. If a command times out and the hardware appears
388  * to be healthy the driver attempts to abort the command. The abort command
389  * timeout is a separate tunable but the original command timeout will be used
390  * if it is greater. If the abort times out too the driver assumes the device
391  * to be dead, fences it off, and calls FMA to retire it. In all other cases
392  * the aborted command should return immediately with a status indicating it
393  * was aborted, and the driver will wait indefinitely for that to happen. No
394  * timeout handling of normal I/O commands is presently done.
395  *
396  * Any command that times out due to the controller dropping dead will be put on
397  * nvme_lost_cmds list if it references DMA memory. This will prevent the DMA
398  * memory being reused by the system and later being written to by a "dead"
399  * NVMe controller.
400  *
401  * -------
402  * Locking
403  * -------
404  *
405  * Each queue pair has a nq_mutex and ncq_mutex. The nq_mutex must be held
406  * when accessing shared state and submission queue registers, ncq_mutex
407  * is held when accessing completion queue state and registers.
408  * Callers of nvme_unqueue_cmd() must make sure that nq_mutex is held, while
409  * nvme_submit_{admin,io}_cmd() and nvme_retrieve_cmd() take care of both
410  * mutexes themselves.
411  *
412  * Each command also has its own nc_mutex, which is associated with the
413  * condition variable nc_cv. It is only used on admin commands which are run
414  * synchronously. In that case it must be held across calls to
415  * nvme_submit_{admin,io}_cmd() and nvme_wait_cmd(), which is taken care of by
416  * nvme_admin_cmd(). It must also be held whenever the completion state of the
417  * command is changed or while an admin command timeout is handled.
418  *
419  * If both nc_mutex and nq_mutex must be held, nc_mutex must be acquired first.
420  * More than one nc_mutex may only be held when aborting commands. In this case,
421  * the nc_mutex of the command to be aborted must be held across the call to
422  * nvme_abort_cmd() to prevent the command from completing while the abort is in
423  * progress.
424  *
425  * If both nq_mutex and ncq_mutex need to be held, ncq_mutex must be
426  * acquired first. More than one nq_mutex is never held by a single thread.
427  * The ncq_mutex is held by nvme_retrieve_cmd() and nvme_process_iocq().
428  * nvme_process_iocq() is called from the interrupt thread and
429  * nvme_retrieve_cmd() during polled I/O, and also by nvme_wait_cmd as a
430  * fallback after a command timeout, so the mutex is required.
431  *
432  * Lastly, in the exceptional situation where ncq_mutex and an nc_mutex must be
433  * held, ncq_mutex must be acquired first (to match the order that they need to
434  * be taken during an interrupt). So the total lock ordering in this driver is:
435  *
436  *       ncq_mutex -> nc_mutex -> nq_mutex
437  *
438  * Each nvme_t has an n_admin_stat_mutex that protects the admin command
439  * statistics structure. If this is taken in conjunction with any other locks,
440  * then it must be taken last.
441  *
442  * There is one mutex n_minor_mutex which protects all open flags nm_open and
443  * exclusive-open thread pointers nm_oexcl of each minor node associated with a
444  * controller and its namespaces.
445  *
446  * In addition, there is a logical namespace management mutex which protects the
447  * data about namespaces. When interrogating the metadata of any namespace, this
448  * lock must be held. This gets tricky as we need to call into blkdev, which may
449  * issue callbacks into us which want this and it is illegal to hold locks
450  * across those blkdev calls as otherwise they might lead to deadlock (blkdev
451  * leverages ndi_devi_enter()).
452  *
453  * The lock exposes two levels, one that we call 'NVME' and one 'BDRO' or blkdev
454  * read-only. The idea is that most callers will use the NVME level which says
455  * this is a full traditional mutex operation. The BDRO level is used by blkdev
456  * callback functions and is a promise to only only read the data. When a blkdev
457  * operation starts, the lock holder will use nvme_mgmt_bd_start(). This
458  * strictly speaking drops the mutex, but records that the lock is logically
459  * held by the thread that did the start() operation.
460  *
461  * During this time, other threads (or even the same one) may end up calling
462  * into nvme_mgmt_lock(). Only one person may still hold the lock at any time;
463  * however, the BRDO level will be allowed to proceed during this time. This
464  * allows us to make consistent progress and honor the blkdev lock ordering
465  * requirements, albeit it is not as straightforward as a simple mutex.
466  *
467  * ---------------------
468  * Quiesce / Fast Reboot
469  * ---------------------
470  *
471  * The driver currently does not support fast reboot. A quiesce(9E) entry point
472  * is still provided which is used to send a shutdown notification to the
473  * device.
474  *
475  *
476  * ------------
477  * NVMe Hotplug
478  * ------------
479  *
480  * The driver supports hot removal. The driver uses the NDI event framework
481  * to register a callback, nvme_remove_callback, to clean up when a disk is
482  * removed. In particular, the driver will unqueue outstanding I/O commands and
483  * set n_dead on the softstate to true so that other operations, such as ioctls
484  * and command submissions, fail as well.
485  *
486  * While the callback registration relies on the NDI event framework, the
487  * removal event itself is kicked off in the PCIe hotplug framework, when the
488  * PCIe bridge driver ("pcieb") gets a hotplug interrupt indicating that a
489  * device was removed from the slot.
490  *
491  * The NVMe driver instance itself will remain until the final close of the
492  * device.
493  *
494  * ---------------
495  * DDI UFM Support
496  * ---------------
497  *
498  * The driver supports the DDI UFM framework for reporting information about
499  * the device's firmware image and slot configuration. This data can be
500  * queried by userland software via ioctls to the ufm driver. For more
501  * information, see ddi_ufm(9E).
502  *
503  * --------------------
504  * Driver Configuration
505  * --------------------
506  *
507  * The following driver properties can be changed to control some aspects of the
508  * drivers operation:
509  * - strict-version: can be set to 0 to allow devices conforming to newer
510  *   major versions to be used
511  * - ignore-unknown-vendor-status: can be set to 1 to not handle any vendor
512  *   specific command status as a fatal error leading device faulting
513  * - admin-queue-len: the maximum length of the admin queue (16-4096)
514  * - io-squeue-len: the maximum length of the I/O submission queues (16-65536)
515  * - io-cqueue-len: the maximum length of the I/O completion queues (16-65536)
516  * - async-event-limit: the maximum number of asynchronous event requests to be
517  *   posted by the driver
518  * - volatile-write-cache-enable: can be set to 0 to disable the volatile write
519  *   cache
520  * - min-phys-block-size: the minimum physical block size to report to blkdev,
521  *   which is among other things the basis for ZFS vdev ashift
522  * - max-submission-queues: the maximum number of I/O submission queues.
523  * - max-completion-queues: the maximum number of I/O completion queues,
524  *   can be less than max-submission-queues, in which case the completion
525  *   queues are shared.
526  *
527  * In addition to the above properties, some device-specific tunables can be
528  * configured using the nvme-config-list global property. The value of this
529  * property is a list of triplets. The formal syntax is:
530  *
531  *   nvme-config-list ::= <triplet> [, <triplet>]* ;
532  *   <triplet>        ::= "<model>" , "<rev-list>" , "<tuple-list>"
533  *   <rev-list>       ::= [ <fwrev> [, <fwrev>]*]
534  *   <tuple-list>     ::= <tunable> [, <tunable>]*
535  *   <tunable>        ::= <name> : <value>
536  *
537  * The <model> and <fwrev> are the strings in nvme_identify_ctrl_t`id_model and
538  * nvme_identify_ctrl_t`id_fwrev, respectively. The remainder of <tuple-list>
539  * contains one or more tunables to apply to all controllers that match the
540  * specified model number and optionally firmware revision. Each <tunable> is a
541  * <name> : <value> pair.  Supported tunables are:
542  *
543  * - ignore-unknown-vendor-status:  can be set to "on" to not handle any vendor
544  *   specific command status as a fatal error leading device faulting
545  *
546  * - min-phys-block-size: the minimum physical block size to report to blkdev,
547  *   which is among other things the basis for ZFS vdev ashift
548  *
549  * - volatile-write-cache: can be set to "on" or "off" to enable or disable the
550  *   volatile write cache, if present
551  *
552  *
553  * TODO:
554  * - figure out sane default for I/O queue depth reported to blkdev
555  * - FMA handling of media errors
556  * - support for devices supporting very large I/O requests using chained PRPs
557  * - support for configuring hardware parameters like interrupt coalescing
558  * - support for big-endian systems
559  * - support for fast reboot
560  * - support for NVMe Subsystem Reset (1.1)
561  * - support for Scatter/Gather lists (1.1)
562  * - support for Reservations (1.1)
563  * - support for power management
564  */
565 
566 #include <sys/byteorder.h>
567 #ifdef _BIG_ENDIAN
568 #error nvme driver needs porting for big-endian platforms
569 #endif
570 
571 #include <sys/modctl.h>
572 #include <sys/conf.h>
573 #include <sys/devops.h>
574 #include <sys/ddi.h>
575 #include <sys/ddi_ufm.h>
576 #include <sys/sunddi.h>
577 #include <sys/sunndi.h>
578 #include <sys/bitmap.h>
579 #include <sys/sysmacros.h>
580 #include <sys/param.h>
581 #include <sys/varargs.h>
582 #include <sys/cpuvar.h>
583 #include <sys/disp.h>
584 #include <sys/blkdev.h>
585 #include <sys/atomic.h>
586 #include <sys/archsystm.h>
587 #include <sys/sata/sata_hba.h>
588 #include <sys/stat.h>
589 #include <sys/policy.h>
590 #include <sys/list.h>
591 #include <sys/dkio.h>
592 #include <sys/pci.h>
593 #include <sys/mkdev.h>
594 
595 #include <sys/nvme.h>
596 
597 #ifdef __x86
598 #include <sys/x86_archext.h>
599 #endif
600 
601 #include "nvme_reg.h"
602 #include "nvme_var.h"
603 
604 /*
605  * Assertions to make sure that we've properly captured various aspects of the
606  * packed structures and haven't broken them during updates.
607  */
608 CTASSERT(sizeof (nvme_identify_ctrl_t) == NVME_IDENTIFY_BUFSIZE);
609 CTASSERT(offsetof(nvme_identify_ctrl_t, id_oacs) == 256);
610 CTASSERT(offsetof(nvme_identify_ctrl_t, id_sqes) == 512);
611 CTASSERT(offsetof(nvme_identify_ctrl_t, id_oncs) == 520);
612 CTASSERT(offsetof(nvme_identify_ctrl_t, id_subnqn) == 768);
613 CTASSERT(offsetof(nvme_identify_ctrl_t, id_nvmof) == 1792);
614 CTASSERT(offsetof(nvme_identify_ctrl_t, id_psd) == 2048);
615 CTASSERT(offsetof(nvme_identify_ctrl_t, id_vs) == 3072);
616 
617 CTASSERT(sizeof (nvme_identify_nsid_t) == NVME_IDENTIFY_BUFSIZE);
618 CTASSERT(offsetof(nvme_identify_nsid_t, id_fpi) == 32);
619 CTASSERT(offsetof(nvme_identify_nsid_t, id_anagrpid) == 92);
620 CTASSERT(offsetof(nvme_identify_nsid_t, id_nguid) == 104);
621 CTASSERT(offsetof(nvme_identify_nsid_t, id_lbaf) == 128);
622 CTASSERT(offsetof(nvme_identify_nsid_t, id_vs) == 384);
623 
624 CTASSERT(sizeof (nvme_identify_nsid_list_t) == NVME_IDENTIFY_BUFSIZE);
625 CTASSERT(sizeof (nvme_identify_ctrl_list_t) == NVME_IDENTIFY_BUFSIZE);
626 
627 CTASSERT(sizeof (nvme_identify_primary_caps_t) == NVME_IDENTIFY_BUFSIZE);
628 CTASSERT(offsetof(nvme_identify_primary_caps_t, nipc_vqfrt) == 32);
629 CTASSERT(offsetof(nvme_identify_primary_caps_t, nipc_vifrt) == 64);
630 
631 CTASSERT(sizeof (nvme_nschange_list_t) == 4096);
632 
633 /* NVMe spec version supported */
634 static const int nvme_version_major = 2;
635 
636 /* Tunable for FORMAT NVM command timeout in seconds, default is 600s */
637 uint32_t nvme_format_cmd_timeout = 600;
638 
639 /* Tunable for firmware commit with NVME_FWC_SAVE, default is 15s */
640 uint32_t nvme_commit_save_cmd_timeout = 15;
641 
642 /*
643  * Tunable for the admin command timeout used for commands other than those
644  * with their own timeouts defined above; in seconds. While most commands are
645  * expected to complete very quickly (sub-second), experience has shown that
646  * some controllers can occasionally be a bit slower, and not always consistent
647  * in the time taken - times of up to around 4.2s have been observed. Setting
648  * this to 15s by default provides headroom.
649  */
650 uint32_t nvme_admin_cmd_timeout = 15;
651 
652 /*
653  * Tunable for abort command timeout in seconds, default is 60s. This timeout
654  * is used when issuing an abort command, currently only in response to a
655  * different admin command timing out. Aborts always complete after the command
656  * that they are attempting to abort so we need to allow enough time for the
657  * controller to process the long running command that we are attempting to
658  * abort. The abort timeout here is only used if it is greater than the timeout
659  * for the command that is being aborted.
660  */
661 uint32_t nvme_abort_cmd_timeout = 60;
662 
663 /*
664  * Tunable for the size of arbitrary vendor specific admin commands,
665  * default is 16MiB.
666  */
667 uint32_t nvme_vendor_specific_admin_cmd_size = 1 << 24;
668 
669 /*
670  * Tunable for the max timeout of arbitary vendor specific admin commands,
671  * default is 60s.
672  */
673 uint_t nvme_vendor_specific_admin_cmd_max_timeout = 60;
674 
675 /*
676  * This ID space, AVL, and lock are used for keeping track of minor state across
677  * opens between different devices.
678  */
679 static id_space_t *nvme_open_minors;
680 static avl_tree_t nvme_open_minors_avl;
681 kmutex_t nvme_open_minors_mutex;
682 
683 /*
684  * Removal taskq used for n_dead callback processing.
685  */
686 taskq_t *nvme_dead_taskq;
687 
688 /*
689  * This enumeration is used in tandem with nvme_mgmt_lock() to describe which
690  * form of the lock is being taken. See the theory statement for more context.
691  */
692 typedef enum {
693 	/*
694 	 * This is the primary form of taking the management lock and indicates
695 	 * that the user intends to do a read/write of it. This should always be
696 	 * used for any ioctl paths or truly anything other than a blkdev
697 	 * information operation.
698 	 */
699 	NVME_MGMT_LOCK_NVME,
700 	/*
701 	 * This is a subordinate form of the lock whereby the user is in blkdev
702 	 * callback context and will only intend to read the namespace data.
703 	 */
704 	NVME_MGMT_LOCK_BDRO
705 } nvme_mgmt_lock_level_t;
706 
707 static int nvme_attach(dev_info_t *, ddi_attach_cmd_t);
708 static int nvme_detach(dev_info_t *, ddi_detach_cmd_t);
709 static int nvme_quiesce(dev_info_t *);
710 static int nvme_fm_errcb(dev_info_t *, ddi_fm_error_t *, const void *);
711 static int nvme_setup_interrupts(nvme_t *, int, int);
712 static void nvme_release_interrupts(nvme_t *);
713 static uint_t nvme_intr(caddr_t, caddr_t);
714 
715 static void nvme_shutdown(nvme_t *, boolean_t);
716 static boolean_t nvme_reset(nvme_t *, boolean_t);
717 static int nvme_init(nvme_t *);
718 static nvme_cmd_t *nvme_alloc_cmd(nvme_t *, int);
719 static void nvme_free_cmd(nvme_cmd_t *);
720 static nvme_cmd_t *nvme_create_nvm_cmd(nvme_namespace_t *, uint8_t,
721     bd_xfer_t *);
722 static void nvme_admin_cmd(nvme_cmd_t *, uint32_t);
723 static void nvme_submit_admin_cmd(nvme_qpair_t *, nvme_cmd_t *, uint32_t *);
724 static int nvme_submit_io_cmd(nvme_qpair_t *, nvme_cmd_t *);
725 static void nvme_submit_cmd_common(nvme_qpair_t *, nvme_cmd_t *, uint32_t *);
726 static nvme_cmd_t *nvme_unqueue_cmd(nvme_t *, nvme_qpair_t *, int);
727 static nvme_cmd_t *nvme_retrieve_cmd(nvme_t *, nvme_qpair_t *);
728 static void nvme_wait_cmd(nvme_cmd_t *, uint_t);
729 static void nvme_wakeup_cmd(void *);
730 static void nvme_async_event_task(void *);
731 
732 static int nvme_check_unknown_cmd_status(nvme_cmd_t *);
733 static int nvme_check_vendor_cmd_status(nvme_cmd_t *);
734 static int nvme_check_integrity_cmd_status(nvme_cmd_t *);
735 static int nvme_check_specific_cmd_status(nvme_cmd_t *);
736 static int nvme_check_generic_cmd_status(nvme_cmd_t *);
737 static inline int nvme_check_cmd_status(nvme_cmd_t *);
738 static boolean_t nvme_check_cmd_status_ioctl(nvme_cmd_t *,
739     nvme_ioctl_common_t *);
740 
741 static int nvme_abort_cmd(nvme_cmd_t *, const uint32_t);
742 static void nvme_async_event(nvme_t *);
743 static boolean_t nvme_format_nvm(nvme_t *, nvme_ioctl_format_t *);
744 static boolean_t nvme_get_logpage_int(nvme_t *, boolean_t, void **, size_t *,
745     uint8_t);
746 static boolean_t nvme_identify(nvme_t *, boolean_t, nvme_ioctl_identify_t *,
747     void **);
748 static boolean_t nvme_identify_int(nvme_t *, uint32_t, uint8_t, void **);
749 static int nvme_set_features(nvme_t *, boolean_t, uint32_t, uint8_t, uint32_t,
750     uint32_t *);
751 static int nvme_write_cache_set(nvme_t *, boolean_t);
752 static int nvme_set_nqueues(nvme_t *);
753 
754 static void nvme_free_dma(nvme_dma_t *);
755 static int nvme_zalloc_dma(nvme_t *, size_t, uint_t, ddi_dma_attr_t *,
756     nvme_dma_t **);
757 static int nvme_zalloc_queue_dma(nvme_t *, uint32_t, uint16_t, uint_t,
758     nvme_dma_t **);
759 static void nvme_free_qpair(nvme_qpair_t *);
760 static int nvme_alloc_qpair(nvme_t *, uint32_t, nvme_qpair_t **, uint_t);
761 static int nvme_create_io_qpair(nvme_t *, nvme_qpair_t *, uint16_t);
762 
763 static inline void nvme_put64(nvme_t *, uintptr_t, uint64_t);
764 static inline void nvme_put32(nvme_t *, uintptr_t, uint32_t);
765 static inline uint64_t nvme_get64(nvme_t *, uintptr_t);
766 static inline uint32_t nvme_get32(nvme_t *, uintptr_t);
767 
768 static boolean_t nvme_check_regs_hdl(nvme_t *);
769 static boolean_t nvme_check_dma_hdl(nvme_dma_t *);
770 
771 static int nvme_fill_prp(nvme_cmd_t *, ddi_dma_handle_t);
772 
773 static void nvme_bd_xfer_done(void *);
774 static void nvme_bd_driveinfo(void *, bd_drive_t *);
775 static int nvme_bd_mediainfo(void *, bd_media_t *);
776 static int nvme_bd_cmd(nvme_namespace_t *, bd_xfer_t *, uint8_t);
777 static int nvme_bd_read(void *, bd_xfer_t *);
778 static int nvme_bd_write(void *, bd_xfer_t *);
779 static int nvme_bd_sync(void *, bd_xfer_t *);
780 static int nvme_bd_devid(void *, dev_info_t *, ddi_devid_t *);
781 static int nvme_bd_free_space(void *, bd_xfer_t *);
782 
783 static int nvme_prp_dma_constructor(void *, void *, int);
784 static void nvme_prp_dma_destructor(void *, void *);
785 
786 static void nvme_prepare_devid(nvme_t *, uint32_t);
787 
788 /* DDI UFM callbacks */
789 static int nvme_ufm_fill_image(ddi_ufm_handle_t *, void *, uint_t,
790     ddi_ufm_image_t *);
791 static int nvme_ufm_fill_slot(ddi_ufm_handle_t *, void *, uint_t, uint_t,
792     ddi_ufm_slot_t *);
793 static int nvme_ufm_getcaps(ddi_ufm_handle_t *, void *, ddi_ufm_cap_t *);
794 
795 static int nvme_open(dev_t *, int, int, cred_t *);
796 static int nvme_close(dev_t, int, int, cred_t *);
797 static int nvme_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
798 
799 static int nvme_init_ns(nvme_t *, uint32_t);
800 static boolean_t nvme_bd_attach_ns(nvme_t *, nvme_ioctl_common_t *);
801 static boolean_t nvme_bd_detach_ns(nvme_t *, nvme_ioctl_common_t *);
802 
803 static int nvme_minor_comparator(const void *, const void *);
804 
805 typedef struct {
806 	nvme_sqe_t *ica_sqe;
807 	void *ica_data;
808 	uint32_t ica_data_len;
809 	uint_t ica_dma_flags;
810 	int ica_copy_flags;
811 	uint32_t ica_timeout;
812 	uint32_t ica_cdw0;
813 } nvme_ioc_cmd_args_t;
814 static boolean_t nvme_ioc_cmd(nvme_t *, nvme_ioctl_common_t *,
815     nvme_ioc_cmd_args_t *);
816 
817 static ddi_ufm_ops_t nvme_ufm_ops = {
818 	NULL,
819 	nvme_ufm_fill_image,
820 	nvme_ufm_fill_slot,
821 	nvme_ufm_getcaps
822 };
823 
824 /*
825  * Minor numbers are split amongst those used for controllers and for device
826  * opens. The number of controller minors are limited based open MAXMIN32 per
827  * the theory statement. We allocate 1 million minors as a total guess at a
828  * number that'll probably be enough. The starting point of the open minors can
829  * be shifted to accommodate future expansion of the NVMe device minors.
830  */
831 #define	NVME_MINOR_INST_SHIFT	9
832 #define	NVME_MINOR(inst, nsid)	(((inst) << NVME_MINOR_INST_SHIFT) | (nsid))
833 #define	NVME_MINOR_INST(minor)	((minor) >> NVME_MINOR_INST_SHIFT)
834 #define	NVME_MINOR_NSID(minor)	((minor) & ((1 << NVME_MINOR_INST_SHIFT) - 1))
835 #define	NVME_MINOR_MAX		(NVME_MINOR(1, 0) - 2)
836 
837 #define	NVME_OPEN_NMINORS		(1024 * 1024)
838 #define	NVME_OPEN_MINOR_MIN		(MAXMIN32 + 1)
839 #define	NVME_OPEN_MINOR_MAX_EXCL	(NVME_OPEN_MINOR_MIN + \
840     NVME_OPEN_NMINORS)
841 
842 #define	NVME_BUMP_STAT(nvme, stat)	\
843 	atomic_inc_64(&nvme->n_device_stat.nds_ ## stat.value.ui64)
844 
845 static void *nvme_state;
846 static kmem_cache_t *nvme_cmd_cache;
847 
848 /*
849  * DMA attributes for queue DMA memory
850  *
851  * Queue DMA memory must be page aligned. The maximum length of a queue is
852  * 65536 entries, and an entry can be 64 bytes long.
853  */
854 static const ddi_dma_attr_t nvme_queue_dma_attr = {
855 	.dma_attr_version	= DMA_ATTR_V0,
856 	.dma_attr_addr_lo	= 0,
857 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
858 	.dma_attr_count_max	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t) - 1,
859 	.dma_attr_align		= 0x1000,
860 	.dma_attr_burstsizes	= 0x7ff,
861 	.dma_attr_minxfer	= 0x1000,
862 	.dma_attr_maxxfer	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t),
863 	.dma_attr_seg		= 0xffffffffffffffffULL,
864 	.dma_attr_sgllen	= 1,
865 	.dma_attr_granular	= 1,
866 	.dma_attr_flags		= 0,
867 };
868 
869 /*
870  * DMA attributes for transfers using Physical Region Page (PRP) entries
871  *
872  * A PRP entry describes one page of DMA memory using the page size specified
873  * in the controller configuration's memory page size register (CC.MPS). It uses
874  * a 64bit base address aligned to this page size. There is no limitation on
875  * chaining PRPs together for arbitrarily large DMA transfers. These DMA
876  * attributes will be copied into the nvme_t during nvme_attach() and the
877  * dma_attr_maxxfer will be updated.
878  */
879 static const ddi_dma_attr_t nvme_prp_dma_attr = {
880 	.dma_attr_version	= DMA_ATTR_V0,
881 	.dma_attr_addr_lo	= 0,
882 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
883 	.dma_attr_count_max	= 0xfff,
884 	.dma_attr_align		= 0x1000,
885 	.dma_attr_burstsizes	= 0x7ff,
886 	.dma_attr_minxfer	= 0x1000,
887 	.dma_attr_maxxfer	= 0x1000,
888 	.dma_attr_seg		= 0xfff,
889 	.dma_attr_sgllen	= -1,
890 	.dma_attr_granular	= 1,
891 	.dma_attr_flags		= 0,
892 };
893 
894 /*
895  * DMA attributes for transfers using scatter/gather lists
896  *
897  * A SGL entry describes a chunk of DMA memory using a 64bit base address and a
898  * 32bit length field. SGL Segment and SGL Last Segment entries require the
899  * length to be a multiple of 16 bytes. While the SGL DMA attributes are copied
900  * into the nvme_t, they are not currently used for any I/O.
901  */
902 static const ddi_dma_attr_t nvme_sgl_dma_attr = {
903 	.dma_attr_version	= DMA_ATTR_V0,
904 	.dma_attr_addr_lo	= 0,
905 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
906 	.dma_attr_count_max	= 0xffffffffUL,
907 	.dma_attr_align		= 1,
908 	.dma_attr_burstsizes	= 0x7ff,
909 	.dma_attr_minxfer	= 0x10,
910 	.dma_attr_maxxfer	= 0xfffffffffULL,
911 	.dma_attr_seg		= 0xffffffffffffffffULL,
912 	.dma_attr_sgllen	= -1,
913 	.dma_attr_granular	= 0x10,
914 	.dma_attr_flags		= 0
915 };
916 
917 static ddi_device_acc_attr_t nvme_reg_acc_attr = {
918 	.devacc_attr_version	= DDI_DEVICE_ATTR_V0,
919 	.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
920 	.devacc_attr_dataorder	= DDI_STRICTORDER_ACC
921 };
922 
923 /*
924  * ioctl validation policies. These are policies that determine which namespaces
925  * are allowed or disallowed for various operations. Note, all policy items
926  * should be explicitly listed here to help make it clear what our intent is.
927  * That is also why some of these are identical or repeated when they cover
928  * different ioctls.
929  */
930 
931 /*
932  * The controller information ioctl generally contains read-only information
933  * about the controller that is sourced from multiple different pieces of
934  * information. This does not operate on a namespace and none are accepted.
935  */
936 static const nvme_ioctl_check_t nvme_check_ctrl_info = {
937 	.nck_ns_ok = B_FALSE, .nck_ns_minor_ok = B_FALSE,
938 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
939 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_NONE
940 };
941 
942 /*
943  * The kernel namespace information requires a namespace ID to be specified. It
944  * does not allow for the broadcast ID to be specified.
945  */
946 static const nvme_ioctl_check_t nvme_check_ns_info = {
947 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
948 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
949 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_NONE
950 };
951 
952 /*
953  * Identify commands are allowed to operate on a namespace minor. Unfortunately,
954  * the namespace field in identify commands is a bit, weird. In particular, some
955  * commands need a valid namespace, while others are namespace listing
956  * operations, which means illegal namespaces like zero are allowed.
957  */
958 static const nvme_ioctl_check_t nvme_check_identify = {
959 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
960 	.nck_skip_ctrl = B_TRUE, .nck_ctrl_rewrite = B_FALSE,
961 	.nck_bcast_ok = B_TRUE, .nck_excl = NVME_IOCTL_EXCL_NONE
962 };
963 
964 /*
965  * The get log page command requires the ability to specify namespaces. When
966  * targeting the controller, one must use the broadcast NSID.
967  */
968 static const nvme_ioctl_check_t nvme_check_get_logpage = {
969 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
970 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_TRUE,
971 	.nck_bcast_ok = B_TRUE, .nck_excl = NVME_IOCTL_EXCL_NONE
972 };
973 
974 /*
975  * When getting a feature, we do not want rewriting behavior as most features do
976  * not require a namespace to be specified. Specific instances are checked in
977  * nvme_validate_get_feature().
978  */
979 static const nvme_ioctl_check_t nvme_check_get_feature = {
980 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
981 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
982 	.nck_bcast_ok = B_TRUE, .nck_excl = NVME_IOCTL_EXCL_NONE
983 };
984 
985 /*
986  * Format commands must target a namespace. The broadcast namespace must be used
987  * when referring to the controller.
988  */
989 static const nvme_ioctl_check_t nvme_check_format = {
990 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
991 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_TRUE,
992 	.nck_bcast_ok = B_TRUE, .nck_excl = NVME_IOCTL_EXCL_WRITE
993 };
994 
995 /*
996  * blkdev and controller attach and detach must always target a namespace.
997  * However, the broadcast namespace is not allowed. We still perform rewriting
998  * so that way specifying the controller node with 0 will be caught.
999  */
1000 static const nvme_ioctl_check_t nvme_check_attach_detach = {
1001 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
1002 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_TRUE,
1003 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_WRITE
1004 };
1005 
1006 /*
1007  * Namespace creation operations cannot target a namespace as the new namespace
1008  * ID will be returned in the operation. This operation requires the entire
1009  * controller lock to be owned as one has to coordinate this operation with all
1010  * of the actual namespace logic that's present.
1011  */
1012 static const nvme_ioctl_check_t nvme_check_ns_create = {
1013 	.nck_ns_ok = B_FALSE, .nck_ns_minor_ok = B_FALSE,
1014 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
1015 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_CTRL
1016 };
1017 
1018 /*
1019  * NVMe namespace delete must always target a namespace. The broadcast namespace
1020  * isn't allowed. We perform rewriting so that way we can catch this.
1021  * Importantly this only requires holding an exclusive lock on the namespace,
1022  * not on the whole device like creating a namespace does. Note, we don't allow
1023  * this on the namespace minor itself as part of our path towards transitioning
1024  * away from its use.
1025  */
1026 static const nvme_ioctl_check_t nvme_check_ns_delete = {
1027 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_FALSE,
1028 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_TRUE,
1029 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_WRITE
1030 };
1031 
1032 /*
1033  * Firmware operations must not target a namespace and are only allowed from the
1034  * controller.
1035  */
1036 static const nvme_ioctl_check_t nvme_check_firmware = {
1037 	.nck_ns_ok = B_FALSE, .nck_ns_minor_ok = B_FALSE,
1038 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
1039 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_WRITE
1040 };
1041 
1042 /*
1043  * Passthru commands are an odd set. We only allow them from the primary
1044  * controller; however, we allow a namespace to be specified in them and allow
1045  * the broadcast namespace. We do not perform rewriting because we don't know
1046  * what the semantics are. We explicitly exempt passthru commands from needing
1047  * an exclusive lock and leave it up to them to tell us the impact of the
1048  * command and semantics. As this is a privileged interface and the semantics
1049  * are arbitrary, there's not much we can do without some assistance from the
1050  * consumer.
1051  */
1052 static const nvme_ioctl_check_t nvme_check_passthru = {
1053 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_FALSE,
1054 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
1055 	.nck_bcast_ok = B_TRUE, .nck_excl = NVME_IOCTL_EXCL_NONE
1056 };
1057 
1058 /*
1059  * Lock operations are allowed to target a namespace, but must not be rewritten.
1060  * There is no support for the broadcast namespace. This is the only ioctl that
1061  * should skip exclusive checking as it's used to grant it.
1062  */
1063 static const nvme_ioctl_check_t nvme_check_locking = {
1064 	.nck_ns_ok = B_TRUE, .nck_ns_minor_ok = B_TRUE,
1065 	.nck_skip_ctrl = B_FALSE, .nck_ctrl_rewrite = B_FALSE,
1066 	.nck_bcast_ok = B_FALSE, .nck_excl = NVME_IOCTL_EXCL_SKIP
1067 };
1068 
1069 /*
1070  * These data tables indicate how we handle the various states a namespace may
1071  * be in before we put it through the namespace state transition diagram. Note,
1072  * namespace creation does not allow one to specify a namespace ID, therefore
1073  * there it doesn't have a set of entries here.
1074  *
1075  * See Namespace Support in the theory statement for more information.
1076  */
1077 static const nvme_ioctl_errno_t nvme_ns_delete_states[] = {
1078 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1079 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_OK,
1080 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1081 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1082 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_NS_BLKDEV_ATTACH
1083 };
1084 
1085 static const nvme_ioctl_errno_t nvme_ctrl_attach_states[] = {
1086 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1087 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_OK,
1088 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1089 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1090 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_NS_BLKDEV_ATTACH
1091 };
1092 
1093 static const nvme_ioctl_errno_t nvme_ctrl_detach_states[] = {
1094 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1095 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_NS_CTRL_NOT_ATTACHED,
1096 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_OK,
1097 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_OK,
1098 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_NS_BLKDEV_ATTACH
1099 };
1100 
1101 static const nvme_ioctl_errno_t nvme_bd_attach_states[] = {
1102 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1103 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_NS_CTRL_NOT_ATTACHED,
1104 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_UNSUP_ATTACH_NS,
1105 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_OK,
1106 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_NS_BLKDEV_ATTACH,
1107 };
1108 
1109 static const nvme_ioctl_errno_t nvme_bd_detach_states[] = {
1110 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1111 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_NS_CTRL_NOT_ATTACHED,
1112 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1113 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_NS_CTRL_ATTACHED,
1114 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_OK,
1115 };
1116 
1117 static const nvme_ioctl_errno_t nvme_format_nvm_states[] = {
1118 	[NVME_NS_STATE_UNALLOCATED] = NVME_IOCTL_E_NS_NO_NS,
1119 	[NVME_NS_STATE_ALLOCATED] = NVME_IOCTL_E_OK,
1120 	[NVME_NS_STATE_ACTIVE] = NVME_IOCTL_E_OK,
1121 	[NVME_NS_STATE_NOT_IGNORED] = NVME_IOCTL_E_OK,
1122 	[NVME_NS_STATE_ATTACHED] = NVME_IOCTL_E_NS_BLKDEV_ATTACH
1123 };
1124 
1125 static struct cb_ops nvme_cb_ops = {
1126 	.cb_open	= nvme_open,
1127 	.cb_close	= nvme_close,
1128 	.cb_strategy	= nodev,
1129 	.cb_print	= nodev,
1130 	.cb_dump	= nodev,
1131 	.cb_read	= nodev,
1132 	.cb_write	= nodev,
1133 	.cb_ioctl	= nvme_ioctl,
1134 	.cb_devmap	= nodev,
1135 	.cb_mmap	= nodev,
1136 	.cb_segmap	= nodev,
1137 	.cb_chpoll	= nochpoll,
1138 	.cb_prop_op	= ddi_prop_op,
1139 	.cb_str		= 0,
1140 	.cb_flag	= D_NEW | D_MP,
1141 	.cb_rev		= CB_REV,
1142 	.cb_aread	= nodev,
1143 	.cb_awrite	= nodev
1144 };
1145 
1146 static struct dev_ops nvme_dev_ops = {
1147 	.devo_rev	= DEVO_REV,
1148 	.devo_refcnt	= 0,
1149 	.devo_getinfo	= ddi_no_info,
1150 	.devo_identify	= nulldev,
1151 	.devo_probe	= nulldev,
1152 	.devo_attach	= nvme_attach,
1153 	.devo_detach	= nvme_detach,
1154 	.devo_reset	= nodev,
1155 	.devo_cb_ops	= &nvme_cb_ops,
1156 	.devo_bus_ops	= NULL,
1157 	.devo_power	= NULL,
1158 	.devo_quiesce	= nvme_quiesce,
1159 };
1160 
1161 static struct modldrv nvme_modldrv = {
1162 	.drv_modops	= &mod_driverops,
1163 	.drv_linkinfo	= "NVMe driver",
1164 	.drv_dev_ops	= &nvme_dev_ops
1165 };
1166 
1167 static struct modlinkage nvme_modlinkage = {
1168 	.ml_rev		= MODREV_1,
1169 	.ml_linkage	= { &nvme_modldrv, NULL }
1170 };
1171 
1172 static bd_ops_t nvme_bd_ops = {
1173 	.o_version	= BD_OPS_CURRENT_VERSION,
1174 	.o_drive_info	= nvme_bd_driveinfo,
1175 	.o_media_info	= nvme_bd_mediainfo,
1176 	.o_devid_init	= nvme_bd_devid,
1177 	.o_sync_cache	= nvme_bd_sync,
1178 	.o_read		= nvme_bd_read,
1179 	.o_write	= nvme_bd_write,
1180 	.o_free_space	= nvme_bd_free_space,
1181 };
1182 
1183 /*
1184  * This list will hold commands that have timed out and couldn't be aborted.
1185  * As we don't know what the hardware may still do with the DMA memory we can't
1186  * free them, so we'll keep them forever on this list where we can easily look
1187  * at them with mdb.
1188  */
1189 static struct list nvme_lost_cmds;
1190 static kmutex_t nvme_lc_mutex;
1191 
1192 int
_init(void)1193 _init(void)
1194 {
1195 	int error;
1196 
1197 	error = ddi_soft_state_init(&nvme_state, sizeof (nvme_t), 1);
1198 	if (error != DDI_SUCCESS)
1199 		return (error);
1200 
1201 	if ((nvme_open_minors = id_space_create("nvme_open_minors",
1202 	    NVME_OPEN_MINOR_MIN, NVME_OPEN_MINOR_MAX_EXCL)) == NULL) {
1203 		ddi_soft_state_fini(&nvme_state);
1204 		return (ENOMEM);
1205 	}
1206 
1207 	nvme_cmd_cache = kmem_cache_create("nvme_cmd_cache",
1208 	    sizeof (nvme_cmd_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1209 
1210 	mutex_init(&nvme_lc_mutex, NULL, MUTEX_DRIVER, NULL);
1211 	list_create(&nvme_lost_cmds, sizeof (nvme_cmd_t),
1212 	    offsetof(nvme_cmd_t, nc_list));
1213 
1214 	mutex_init(&nvme_open_minors_mutex, NULL, MUTEX_DRIVER, NULL);
1215 	avl_create(&nvme_open_minors_avl, nvme_minor_comparator,
1216 	    sizeof (nvme_minor_t), offsetof(nvme_minor_t, nm_avl));
1217 
1218 	nvme_dead_taskq = taskq_create("nvme_dead_taskq", 1, minclsyspri, 1, 1,
1219 	    TASKQ_PREPOPULATE);
1220 
1221 	bd_mod_init(&nvme_dev_ops);
1222 
1223 	error = mod_install(&nvme_modlinkage);
1224 	if (error != DDI_SUCCESS) {
1225 		ddi_soft_state_fini(&nvme_state);
1226 		id_space_destroy(nvme_open_minors);
1227 		mutex_destroy(&nvme_lc_mutex);
1228 		list_destroy(&nvme_lost_cmds);
1229 		bd_mod_fini(&nvme_dev_ops);
1230 		mutex_destroy(&nvme_open_minors_mutex);
1231 		avl_destroy(&nvme_open_minors_avl);
1232 		taskq_destroy(nvme_dead_taskq);
1233 	}
1234 
1235 	return (error);
1236 }
1237 
1238 int
_fini(void)1239 _fini(void)
1240 {
1241 	int error;
1242 
1243 	if (!list_is_empty(&nvme_lost_cmds))
1244 		return (DDI_FAILURE);
1245 
1246 	error = mod_remove(&nvme_modlinkage);
1247 	if (error == DDI_SUCCESS) {
1248 		ddi_soft_state_fini(&nvme_state);
1249 		id_space_destroy(nvme_open_minors);
1250 		kmem_cache_destroy(nvme_cmd_cache);
1251 		mutex_destroy(&nvme_lc_mutex);
1252 		list_destroy(&nvme_lost_cmds);
1253 		bd_mod_fini(&nvme_dev_ops);
1254 		mutex_destroy(&nvme_open_minors_mutex);
1255 		avl_destroy(&nvme_open_minors_avl);
1256 		taskq_destroy(nvme_dead_taskq);
1257 	}
1258 
1259 	return (error);
1260 }
1261 
1262 int
_info(struct modinfo * modinfop)1263 _info(struct modinfo *modinfop)
1264 {
1265 	return (mod_info(&nvme_modlinkage, modinfop));
1266 }
1267 
1268 static inline void
nvme_put64(nvme_t * nvme,uintptr_t reg,uint64_t val)1269 nvme_put64(nvme_t *nvme, uintptr_t reg, uint64_t val)
1270 {
1271 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
1272 
1273 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
1274 	ddi_put64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg), val);
1275 }
1276 
1277 static inline void
nvme_put32(nvme_t * nvme,uintptr_t reg,uint32_t val)1278 nvme_put32(nvme_t *nvme, uintptr_t reg, uint32_t val)
1279 {
1280 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
1281 
1282 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
1283 	ddi_put32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg), val);
1284 }
1285 
1286 static inline uint64_t
nvme_get64(nvme_t * nvme,uintptr_t reg)1287 nvme_get64(nvme_t *nvme, uintptr_t reg)
1288 {
1289 	uint64_t val;
1290 
1291 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
1292 
1293 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
1294 	val = ddi_get64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg));
1295 
1296 	return (val);
1297 }
1298 
1299 static inline uint32_t
nvme_get32(nvme_t * nvme,uintptr_t reg)1300 nvme_get32(nvme_t *nvme, uintptr_t reg)
1301 {
1302 	uint32_t val;
1303 
1304 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
1305 
1306 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
1307 	val = ddi_get32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg));
1308 
1309 	return (val);
1310 }
1311 
1312 static void
nvme_mgmt_lock_fini(nvme_mgmt_lock_t * lock)1313 nvme_mgmt_lock_fini(nvme_mgmt_lock_t *lock)
1314 {
1315 	ASSERT3U(lock->nml_bd_own, ==, 0);
1316 	mutex_destroy(&lock->nml_lock);
1317 	cv_destroy(&lock->nml_cv);
1318 }
1319 
1320 static void
nvme_mgmt_lock_init(nvme_mgmt_lock_t * lock)1321 nvme_mgmt_lock_init(nvme_mgmt_lock_t *lock)
1322 {
1323 	mutex_init(&lock->nml_lock, NULL, MUTEX_DRIVER, NULL);
1324 	cv_init(&lock->nml_cv, NULL, CV_DRIVER, NULL);
1325 	lock->nml_bd_own = 0;
1326 }
1327 
1328 static void
nvme_mgmt_unlock(nvme_t * nvme)1329 nvme_mgmt_unlock(nvme_t *nvme)
1330 {
1331 	nvme_mgmt_lock_t *lock = &nvme->n_mgmt;
1332 
1333 	cv_broadcast(&lock->nml_cv);
1334 	mutex_exit(&lock->nml_lock);
1335 }
1336 
1337 static boolean_t
nvme_mgmt_lock_held(const nvme_t * nvme)1338 nvme_mgmt_lock_held(const nvme_t *nvme)
1339 {
1340 	return (MUTEX_HELD(&nvme->n_mgmt.nml_lock) != 0);
1341 }
1342 
1343 static void
nvme_mgmt_lock(nvme_t * nvme,nvme_mgmt_lock_level_t level)1344 nvme_mgmt_lock(nvme_t *nvme, nvme_mgmt_lock_level_t level)
1345 {
1346 	nvme_mgmt_lock_t *lock = &nvme->n_mgmt;
1347 	mutex_enter(&lock->nml_lock);
1348 	while (lock->nml_bd_own != 0) {
1349 		if (level == NVME_MGMT_LOCK_BDRO)
1350 			break;
1351 		cv_wait(&lock->nml_cv, &lock->nml_lock);
1352 	}
1353 }
1354 
1355 /*
1356  * This and nvme_mgmt_bd_end() are used to indicate that the driver is going to
1357  * be calling into a re-entrant blkdev related function. We cannot hold the lock
1358  * across such an operation and therefore must indicate that this is logically
1359  * held, while allowing other operations to proceed. This nvme_mgmt_bd_end() may
1360  * only be called by a thread that already holds the nmve_mgmt_lock().
1361  */
1362 static void
nvme_mgmt_bd_start(nvme_t * nvme)1363 nvme_mgmt_bd_start(nvme_t *nvme)
1364 {
1365 	nvme_mgmt_lock_t *lock = &nvme->n_mgmt;
1366 
1367 	VERIFY(MUTEX_HELD(&lock->nml_lock));
1368 	VERIFY3U(lock->nml_bd_own, ==, 0);
1369 	lock->nml_bd_own = (uintptr_t)curthread;
1370 	mutex_exit(&lock->nml_lock);
1371 }
1372 
1373 static void
nvme_mgmt_bd_end(nvme_t * nvme)1374 nvme_mgmt_bd_end(nvme_t *nvme)
1375 {
1376 	nvme_mgmt_lock_t *lock = &nvme->n_mgmt;
1377 
1378 	mutex_enter(&lock->nml_lock);
1379 	VERIFY3U(lock->nml_bd_own, ==, (uintptr_t)curthread);
1380 	lock->nml_bd_own = 0;
1381 }
1382 
1383 static boolean_t
nvme_ns_state_check(const nvme_namespace_t * ns,nvme_ioctl_common_t * ioc,const nvme_ioctl_errno_t states[NVME_NS_NSTATES])1384 nvme_ns_state_check(const nvme_namespace_t *ns, nvme_ioctl_common_t *ioc,
1385     const nvme_ioctl_errno_t states[NVME_NS_NSTATES])
1386 {
1387 	VERIFY(nvme_mgmt_lock_held(ns->ns_nvme));
1388 	VERIFY3U(ns->ns_state, <, NVME_NS_NSTATES);
1389 
1390 	if (states[ns->ns_state] == NVME_IOCTL_E_OK) {
1391 		return (B_TRUE);
1392 	}
1393 
1394 	return (nvme_ioctl_error(ioc, states[ns->ns_state], 0, 0));
1395 }
1396 
1397 /*
1398  * This is a central clearing house for marking an NVMe controller dead and/or
1399  * removed. This takes care of setting the flag, taking care of outstanding
1400  * blocked locks, and sending a DDI FMA impact. This is called from a precarious
1401  * place where locking is suspect. The only guarantee we have is that the nvme_t
1402  * is valid and won't disappear until we return.
1403  */
1404 static void
nvme_ctrl_mark_dead(nvme_t * nvme,boolean_t removed)1405 nvme_ctrl_mark_dead(nvme_t *nvme, boolean_t removed)
1406 {
1407 	boolean_t was_dead;
1408 
1409 	/*
1410 	 * See if we win the race to set things up here. If someone beat us to
1411 	 * it, we do not do anything.
1412 	 */
1413 	was_dead = atomic_cas_32((volatile uint32_t *)&nvme->n_dead, B_FALSE,
1414 	    B_TRUE);
1415 
1416 	/*
1417 	 * If we were removed, note this in our death status, regardless of
1418 	 * whether or not we were already dead.  We need to know this so that we
1419 	 * can decide if it is safe to try and interact the the device in e.g.
1420 	 * reset and shutdown.
1421 	 */
1422 	if (removed) {
1423 		nvme->n_dead_status = NVME_IOCTL_E_CTRL_GONE;
1424 	}
1425 
1426 	if (was_dead) {
1427 		return;
1428 	}
1429 
1430 	/*
1431 	 * If this was removed, there is no reason to change the service impact.
1432 	 * Otherwise, we need to change our default return code to indicate that
1433 	 * the device is truly dead, and not simply gone.
1434 	 */
1435 	if (!removed) {
1436 		ASSERT3U(nvme->n_dead_status, ==, NVME_IOCTL_E_CTRL_DEAD);
1437 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1438 	}
1439 
1440 	taskq_dispatch_ent(nvme_dead_taskq, nvme_rwlock_ctrl_dead, nvme,
1441 	    TQ_NOSLEEP, &nvme->n_dead_tqent);
1442 }
1443 
1444 static boolean_t
nvme_ctrl_is_gone(const nvme_t * nvme)1445 nvme_ctrl_is_gone(const nvme_t *nvme)
1446 {
1447 	if (nvme->n_dead && nvme->n_dead_status == NVME_IOCTL_E_CTRL_GONE)
1448 		return (B_TRUE);
1449 
1450 	return (B_FALSE);
1451 }
1452 
1453 static boolean_t
nvme_check_regs_hdl(nvme_t * nvme)1454 nvme_check_regs_hdl(nvme_t *nvme)
1455 {
1456 	ddi_fm_error_t error;
1457 
1458 	ddi_fm_acc_err_get(nvme->n_regh, &error, DDI_FME_VERSION);
1459 
1460 	if (error.fme_status != DDI_FM_OK)
1461 		return (B_TRUE);
1462 
1463 	return (B_FALSE);
1464 }
1465 
1466 static boolean_t
nvme_check_dma_hdl(nvme_dma_t * dma)1467 nvme_check_dma_hdl(nvme_dma_t *dma)
1468 {
1469 	ddi_fm_error_t error;
1470 
1471 	if (dma == NULL)
1472 		return (B_FALSE);
1473 
1474 	ddi_fm_dma_err_get(dma->nd_dmah, &error, DDI_FME_VERSION);
1475 
1476 	if (error.fme_status != DDI_FM_OK)
1477 		return (B_TRUE);
1478 
1479 	return (B_FALSE);
1480 }
1481 
1482 static void
nvme_free_dma_common(nvme_dma_t * dma)1483 nvme_free_dma_common(nvme_dma_t *dma)
1484 {
1485 	if (dma->nd_dmah != NULL)
1486 		(void) ddi_dma_unbind_handle(dma->nd_dmah);
1487 	if (dma->nd_acch != NULL)
1488 		ddi_dma_mem_free(&dma->nd_acch);
1489 	if (dma->nd_dmah != NULL)
1490 		ddi_dma_free_handle(&dma->nd_dmah);
1491 }
1492 
1493 static void
nvme_free_dma(nvme_dma_t * dma)1494 nvme_free_dma(nvme_dma_t *dma)
1495 {
1496 	nvme_free_dma_common(dma);
1497 	kmem_free(dma, sizeof (*dma));
1498 }
1499 
1500 static void
nvme_prp_dma_destructor(void * buf,void * private __unused)1501 nvme_prp_dma_destructor(void *buf, void *private __unused)
1502 {
1503 	nvme_dma_t *dma = (nvme_dma_t *)buf;
1504 
1505 	nvme_free_dma_common(dma);
1506 }
1507 
1508 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)1509 nvme_alloc_dma_common(nvme_t *nvme, nvme_dma_t *dma,
1510     size_t len, uint_t flags, ddi_dma_attr_t *dma_attr)
1511 {
1512 	if (ddi_dma_alloc_handle(nvme->n_dip, dma_attr, DDI_DMA_SLEEP, NULL,
1513 	    &dma->nd_dmah) != DDI_SUCCESS) {
1514 		/*
1515 		 * Due to DDI_DMA_SLEEP this can't be DDI_DMA_NORESOURCES, and
1516 		 * the only other possible error is DDI_DMA_BADATTR which
1517 		 * indicates a driver bug which should cause a panic.
1518 		 */
1519 		dev_err(nvme->n_dip, CE_PANIC,
1520 		    "!failed to get DMA handle, check DMA attributes");
1521 		return (DDI_FAILURE);
1522 	}
1523 
1524 	/*
1525 	 * ddi_dma_mem_alloc() can only fail when DDI_DMA_NOSLEEP is specified
1526 	 * or the flags are conflicting, which isn't the case here.
1527 	 */
1528 	(void) ddi_dma_mem_alloc(dma->nd_dmah, len, &nvme->n_reg_acc_attr,
1529 	    DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, &dma->nd_memp,
1530 	    &dma->nd_len, &dma->nd_acch);
1531 
1532 	if (ddi_dma_addr_bind_handle(dma->nd_dmah, NULL, dma->nd_memp,
1533 	    dma->nd_len, flags | DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL,
1534 	    &dma->nd_cookie, &dma->nd_ncookie) != DDI_DMA_MAPPED) {
1535 		dev_err(nvme->n_dip, CE_WARN,
1536 		    "!failed to bind DMA memory");
1537 		NVME_BUMP_STAT(nvme, dma_bind_err);
1538 		nvme_free_dma_common(dma);
1539 		return (DDI_FAILURE);
1540 	}
1541 
1542 	return (DDI_SUCCESS);
1543 }
1544 
1545 static int
nvme_zalloc_dma(nvme_t * nvme,size_t len,uint_t flags,ddi_dma_attr_t * dma_attr,nvme_dma_t ** ret)1546 nvme_zalloc_dma(nvme_t *nvme, size_t len, uint_t flags,
1547     ddi_dma_attr_t *dma_attr, nvme_dma_t **ret)
1548 {
1549 	nvme_dma_t *dma = kmem_zalloc(sizeof (nvme_dma_t), KM_SLEEP);
1550 
1551 	if (nvme_alloc_dma_common(nvme, dma, len, flags, dma_attr) !=
1552 	    DDI_SUCCESS) {
1553 		*ret = NULL;
1554 		kmem_free(dma, sizeof (nvme_dma_t));
1555 		return (DDI_FAILURE);
1556 	}
1557 
1558 	bzero(dma->nd_memp, dma->nd_len);
1559 
1560 	*ret = dma;
1561 	return (DDI_SUCCESS);
1562 }
1563 
1564 static int
nvme_prp_dma_constructor(void * buf,void * private,int flags __unused)1565 nvme_prp_dma_constructor(void *buf, void *private, int flags __unused)
1566 {
1567 	nvme_dma_t *dma = (nvme_dma_t *)buf;
1568 	nvme_t *nvme = (nvme_t *)private;
1569 
1570 	dma->nd_dmah = NULL;
1571 	dma->nd_acch = NULL;
1572 
1573 	if (nvme_alloc_dma_common(nvme, dma, nvme->n_pagesize,
1574 	    DDI_DMA_READ, &nvme->n_prp_dma_attr) != DDI_SUCCESS) {
1575 		return (-1);
1576 	}
1577 
1578 	ASSERT(dma->nd_ncookie == 1);
1579 
1580 	dma->nd_cached = B_TRUE;
1581 
1582 	return (0);
1583 }
1584 
1585 static int
nvme_zalloc_queue_dma(nvme_t * nvme,uint32_t nentry,uint16_t qe_len,uint_t flags,nvme_dma_t ** dma)1586 nvme_zalloc_queue_dma(nvme_t *nvme, uint32_t nentry, uint16_t qe_len,
1587     uint_t flags, nvme_dma_t **dma)
1588 {
1589 	uint32_t len = nentry * qe_len;
1590 	ddi_dma_attr_t q_dma_attr = nvme->n_queue_dma_attr;
1591 
1592 	len = roundup(len, nvme->n_pagesize);
1593 
1594 	if (nvme_zalloc_dma(nvme, len, flags, &q_dma_attr, dma)
1595 	    != DDI_SUCCESS) {
1596 		dev_err(nvme->n_dip, CE_WARN,
1597 		    "!failed to get DMA memory for queue");
1598 		goto fail;
1599 	}
1600 
1601 	if ((*dma)->nd_ncookie != 1) {
1602 		dev_err(nvme->n_dip, CE_WARN,
1603 		    "!got too many cookies for queue DMA");
1604 		goto fail;
1605 	}
1606 
1607 	return (DDI_SUCCESS);
1608 
1609 fail:
1610 	if (*dma) {
1611 		nvme_free_dma(*dma);
1612 		*dma = NULL;
1613 	}
1614 
1615 	return (DDI_FAILURE);
1616 }
1617 
1618 static void
nvme_free_cq(nvme_cq_t * cq)1619 nvme_free_cq(nvme_cq_t *cq)
1620 {
1621 	mutex_destroy(&cq->ncq_mutex);
1622 
1623 	if (cq->ncq_cmd_taskq != NULL)
1624 		taskq_destroy(cq->ncq_cmd_taskq);
1625 
1626 	if (cq->ncq_dma != NULL)
1627 		nvme_free_dma(cq->ncq_dma);
1628 
1629 	kmem_free(cq, sizeof (*cq));
1630 }
1631 
1632 static void
nvme_free_qpair(nvme_qpair_t * qp)1633 nvme_free_qpair(nvme_qpair_t *qp)
1634 {
1635 	int i;
1636 
1637 	mutex_destroy(&qp->nq_mutex);
1638 	sema_destroy(&qp->nq_sema);
1639 
1640 	if (qp->nq_sqdma != NULL)
1641 		nvme_free_dma(qp->nq_sqdma);
1642 
1643 	if (qp->nq_active_cmds > 0)
1644 		for (i = 0; i != qp->nq_nentry; i++)
1645 			if (qp->nq_cmd[i] != NULL)
1646 				nvme_free_cmd(qp->nq_cmd[i]);
1647 
1648 	if (qp->nq_cmd != NULL)
1649 		kmem_free(qp->nq_cmd, sizeof (nvme_cmd_t *) * qp->nq_nentry);
1650 
1651 	kmem_free(qp, sizeof (nvme_qpair_t));
1652 }
1653 
1654 /*
1655  * Destroy the pre-allocated cq array, but only free individual completion
1656  * queues from the given starting index.
1657  */
1658 static void
nvme_destroy_cq_array(nvme_t * nvme,uint_t start)1659 nvme_destroy_cq_array(nvme_t *nvme, uint_t start)
1660 {
1661 	uint_t i;
1662 
1663 	for (i = start; i < nvme->n_cq_count; i++)
1664 		if (nvme->n_cq[i] != NULL)
1665 			nvme_free_cq(nvme->n_cq[i]);
1666 
1667 	kmem_free(nvme->n_cq, sizeof (*nvme->n_cq) * nvme->n_cq_count);
1668 }
1669 
1670 static int
nvme_alloc_cq(nvme_t * nvme,uint32_t nentry,nvme_cq_t ** cqp,uint16_t idx,uint_t nthr)1671 nvme_alloc_cq(nvme_t *nvme, uint32_t nentry, nvme_cq_t **cqp, uint16_t idx,
1672     uint_t nthr)
1673 {
1674 	nvme_cq_t *cq = kmem_zalloc(sizeof (*cq), KM_SLEEP);
1675 	char name[64];		/* large enough for the taskq name */
1676 
1677 	mutex_init(&cq->ncq_mutex, NULL, MUTEX_DRIVER,
1678 	    DDI_INTR_PRI(nvme->n_intr_pri));
1679 
1680 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_cqe_t),
1681 	    DDI_DMA_READ, &cq->ncq_dma) != DDI_SUCCESS)
1682 		goto fail;
1683 
1684 	cq->ncq_cq = (nvme_cqe_t *)cq->ncq_dma->nd_memp;
1685 	cq->ncq_nentry = nentry;
1686 	cq->ncq_id = idx;
1687 	cq->ncq_hdbl = NVME_REG_CQHDBL(nvme, idx);
1688 
1689 	/*
1690 	 * Each completion queue has its own command taskq.
1691 	 */
1692 	(void) snprintf(name, sizeof (name), "%s%d_cmd_taskq%u",
1693 	    ddi_driver_name(nvme->n_dip), ddi_get_instance(nvme->n_dip), idx);
1694 
1695 	cq->ncq_cmd_taskq = taskq_create(name, nthr, minclsyspri, 64, INT_MAX,
1696 	    TASKQ_PREPOPULATE);
1697 
1698 	if (cq->ncq_cmd_taskq == NULL) {
1699 		dev_err(nvme->n_dip, CE_WARN, "!failed to create cmd "
1700 		    "taskq for cq %u", idx);
1701 		goto fail;
1702 	}
1703 
1704 	*cqp = cq;
1705 	return (DDI_SUCCESS);
1706 
1707 fail:
1708 	nvme_free_cq(cq);
1709 	*cqp = NULL;
1710 
1711 	return (DDI_FAILURE);
1712 }
1713 
1714 /*
1715  * Create the n_cq array big enough to hold "ncq" completion queues.
1716  * If the array already exists it will be re-sized (but only larger).
1717  * The admin queue is included in this array, which boosts the
1718  * max number of entries to UINT16_MAX + 1.
1719  */
1720 static int
nvme_create_cq_array(nvme_t * nvme,uint_t ncq,uint32_t nentry,uint_t nthr)1721 nvme_create_cq_array(nvme_t *nvme, uint_t ncq, uint32_t nentry, uint_t nthr)
1722 {
1723 	nvme_cq_t **cq;
1724 	uint_t i, cq_count;
1725 
1726 	ASSERT3U(ncq, >, nvme->n_cq_count);
1727 
1728 	cq = nvme->n_cq;
1729 	cq_count = nvme->n_cq_count;
1730 
1731 	nvme->n_cq = kmem_zalloc(sizeof (*nvme->n_cq) * ncq, KM_SLEEP);
1732 	nvme->n_cq_count = ncq;
1733 
1734 	for (i = 0; i < cq_count; i++)
1735 		nvme->n_cq[i] = cq[i];
1736 
1737 	for (; i < nvme->n_cq_count; i++)
1738 		if (nvme_alloc_cq(nvme, nentry, &nvme->n_cq[i], i, nthr) !=
1739 		    DDI_SUCCESS)
1740 			goto fail;
1741 
1742 	if (cq != NULL)
1743 		kmem_free(cq, sizeof (*cq) * cq_count);
1744 
1745 	return (DDI_SUCCESS);
1746 
1747 fail:
1748 	nvme_destroy_cq_array(nvme, cq_count);
1749 	/*
1750 	 * Restore the original array
1751 	 */
1752 	nvme->n_cq_count = cq_count;
1753 	nvme->n_cq = cq;
1754 
1755 	return (DDI_FAILURE);
1756 }
1757 
1758 static int
nvme_alloc_qpair(nvme_t * nvme,uint32_t nentry,nvme_qpair_t ** nqp,uint_t idx)1759 nvme_alloc_qpair(nvme_t *nvme, uint32_t nentry, nvme_qpair_t **nqp,
1760     uint_t idx)
1761 {
1762 	nvme_qpair_t *qp = kmem_zalloc(sizeof (*qp), KM_SLEEP);
1763 	uint_t cq_idx;
1764 
1765 	mutex_init(&qp->nq_mutex, NULL, MUTEX_DRIVER,
1766 	    DDI_INTR_PRI(nvme->n_intr_pri));
1767 
1768 	/*
1769 	 * The NVMe spec defines that a full queue has one empty (unused) slot;
1770 	 * initialize the semaphore accordingly.
1771 	 */
1772 	sema_init(&qp->nq_sema, nentry - 1, NULL, SEMA_DRIVER, NULL);
1773 
1774 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_sqe_t),
1775 	    DDI_DMA_WRITE, &qp->nq_sqdma) != DDI_SUCCESS)
1776 		goto fail;
1777 
1778 	/*
1779 	 * idx == 0 is adminq, those above 0 are shared io completion queues.
1780 	 */
1781 	cq_idx = idx == 0 ? 0 : 1 + (idx - 1) % (nvme->n_cq_count - 1);
1782 	qp->nq_cq = nvme->n_cq[cq_idx];
1783 	qp->nq_sq = (nvme_sqe_t *)qp->nq_sqdma->nd_memp;
1784 	qp->nq_nentry = nentry;
1785 
1786 	qp->nq_sqtdbl = NVME_REG_SQTDBL(nvme, idx);
1787 
1788 	qp->nq_cmd = kmem_zalloc(sizeof (nvme_cmd_t *) * nentry, KM_SLEEP);
1789 	qp->nq_next_cmd = 0;
1790 
1791 	*nqp = qp;
1792 	return (DDI_SUCCESS);
1793 
1794 fail:
1795 	nvme_free_qpair(qp);
1796 	*nqp = NULL;
1797 
1798 	return (DDI_FAILURE);
1799 }
1800 
1801 /*
1802  * One might reasonably consider that the nvme_cmd_cache should have a cache
1803  * constructor and destructor that takes care of the mutex/cv init/destroy, and
1804  * that nvme_free_cmd should reset more fields such that allocation becomes
1805  * simpler. This is not currently implemented as:
1806  * - nvme_cmd_cache is a global cache, shared across nvme instances and
1807  *   therefore there is no easy access to the corresponding nvme_t in the
1808  *   constructor to determine the required interrupt priority.
1809  * - Most fields in nvme_cmd_t would need to be zeroed in nvme_free_cmd while
1810  *   preserving the mutex/cv. It is easier to able to zero the entire
1811  *   structure and then init the mutex/cv only in the unlikely event that we
1812  *   want an admin command.
1813  */
1814 static nvme_cmd_t *
nvme_alloc_cmd(nvme_t * nvme,int kmflag)1815 nvme_alloc_cmd(nvme_t *nvme, int kmflag)
1816 {
1817 	nvme_cmd_t *cmd = kmem_cache_alloc(nvme_cmd_cache, kmflag);
1818 
1819 	if (cmd != NULL) {
1820 		bzero(cmd, sizeof (nvme_cmd_t));
1821 		cmd->nc_nvme = nvme;
1822 	}
1823 
1824 	return (cmd);
1825 }
1826 
1827 static nvme_cmd_t *
nvme_alloc_admin_cmd(nvme_t * nvme,int kmflag)1828 nvme_alloc_admin_cmd(nvme_t *nvme, int kmflag)
1829 {
1830 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, kmflag);
1831 
1832 	if (cmd != NULL) {
1833 		cmd->nc_flags |= NVME_CMD_F_USELOCK;
1834 		mutex_init(&cmd->nc_mutex, NULL, MUTEX_DRIVER,
1835 		    DDI_INTR_PRI(nvme->n_intr_pri));
1836 		cv_init(&cmd->nc_cv, NULL, CV_DRIVER, NULL);
1837 	}
1838 
1839 	return (cmd);
1840 }
1841 
1842 static void
nvme_free_cmd(nvme_cmd_t * cmd)1843 nvme_free_cmd(nvme_cmd_t *cmd)
1844 {
1845 	/* Don't free commands on the lost commands list. */
1846 	if (list_link_active(&cmd->nc_list))
1847 		return;
1848 
1849 	if (cmd->nc_dma) {
1850 		nvme_free_dma(cmd->nc_dma);
1851 		cmd->nc_dma = NULL;
1852 	}
1853 
1854 	if (cmd->nc_prp) {
1855 		kmem_cache_free(cmd->nc_nvme->n_prp_cache, cmd->nc_prp);
1856 		cmd->nc_prp = NULL;
1857 	}
1858 
1859 	if ((cmd->nc_flags & NVME_CMD_F_USELOCK) != 0) {
1860 		cv_destroy(&cmd->nc_cv);
1861 		mutex_destroy(&cmd->nc_mutex);
1862 	}
1863 
1864 	kmem_cache_free(nvme_cmd_cache, cmd);
1865 }
1866 
1867 static void
nvme_submit_admin_cmd(nvme_qpair_t * qp,nvme_cmd_t * cmd,uint32_t * qtimeoutp)1868 nvme_submit_admin_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd, uint32_t *qtimeoutp)
1869 {
1870 	sema_p(&qp->nq_sema);
1871 	nvme_submit_cmd_common(qp, cmd, qtimeoutp);
1872 }
1873 
1874 static int
nvme_submit_io_cmd(nvme_qpair_t * qp,nvme_cmd_t * cmd)1875 nvme_submit_io_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd)
1876 {
1877 	if (cmd->nc_nvme->n_dead) {
1878 		return (EIO);
1879 	}
1880 
1881 	sema_p(&qp->nq_sema);
1882 	nvme_submit_cmd_common(qp, cmd, NULL);
1883 	return (0);
1884 }
1885 
1886 /*
1887  * Common command submission routine. If `qtimeoutp` is not NULL then it will
1888  * be set to the sum of the timeouts of any active commands ahead of the one
1889  * being submitted.
1890  */
1891 static void
nvme_submit_cmd_common(nvme_qpair_t * qp,nvme_cmd_t * cmd,uint32_t * qtimeoutp)1892 nvme_submit_cmd_common(nvme_qpair_t *qp, nvme_cmd_t *cmd, uint32_t *qtimeoutp)
1893 {
1894 	nvme_reg_sqtdbl_t tail = { 0 };
1895 
1896 	/*
1897 	 * We don't need to take a lock on cmd since it is not yet enqueued.
1898 	 */
1899 	cmd->nc_submit_ts = gethrtime();
1900 	cmd->nc_state = NVME_CMD_SUBMITTED;
1901 
1902 	mutex_enter(&qp->nq_mutex);
1903 
1904 	/*
1905 	 * Now that we hold the queue pair lock, we must check whether or not
1906 	 * the controller has been listed as dead (e.g. was removed due to
1907 	 * hotplug). This is necessary as otherwise we could race with
1908 	 * nvme_remove_callback(). Because this has not been enqueued, we don't
1909 	 * call nvme_unqueue_cmd(), which is why we must manually decrement the
1910 	 * semaphore.
1911 	 */
1912 	if (cmd->nc_nvme->n_dead) {
1913 		cmd->nc_queue_ts = gethrtime();
1914 		cmd->nc_state = NVME_CMD_QUEUED;
1915 		taskq_dispatch_ent(qp->nq_cq->ncq_cmd_taskq, cmd->nc_callback,
1916 		    cmd, TQ_NOSLEEP, &cmd->nc_tqent);
1917 		sema_v(&qp->nq_sema);
1918 		mutex_exit(&qp->nq_mutex);
1919 		return;
1920 	}
1921 
1922 	/*
1923 	 * Try to insert the cmd into the active cmd array at the nq_next_cmd
1924 	 * slot. If the slot is already occupied advance to the next slot and
1925 	 * try again. This can happen for long running commands like async event
1926 	 * requests.
1927 	 */
1928 	while (qp->nq_cmd[qp->nq_next_cmd] != NULL)
1929 		qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
1930 	qp->nq_cmd[qp->nq_next_cmd] = cmd;
1931 
1932 	/*
1933 	 * We keep track of the number of active commands in this queue, and
1934 	 * the sum of the timeouts for those active commands.
1935 	 */
1936 	qp->nq_active_cmds++;
1937 	if (qtimeoutp != NULL)
1938 		*qtimeoutp = qp->nq_active_timeout;
1939 	qp->nq_active_timeout += cmd->nc_timeout;
1940 
1941 	cmd->nc_sqe.sqe_cid = qp->nq_next_cmd;
1942 	bcopy(&cmd->nc_sqe, &qp->nq_sq[qp->nq_sqtail], sizeof (nvme_sqe_t));
1943 	(void) ddi_dma_sync(qp->nq_sqdma->nd_dmah,
1944 	    sizeof (nvme_sqe_t) * qp->nq_sqtail,
1945 	    sizeof (nvme_sqe_t), DDI_DMA_SYNC_FORDEV);
1946 	qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
1947 
1948 	tail.b.sqtdbl_sqt = qp->nq_sqtail = (qp->nq_sqtail + 1) % qp->nq_nentry;
1949 	nvme_put32(cmd->nc_nvme, qp->nq_sqtdbl, tail.r);
1950 
1951 	mutex_exit(&qp->nq_mutex);
1952 }
1953 
1954 static nvme_cmd_t *
nvme_unqueue_cmd(nvme_t * nvme,nvme_qpair_t * qp,int cid)1955 nvme_unqueue_cmd(nvme_t *nvme, nvme_qpair_t *qp, int cid)
1956 {
1957 	nvme_cmd_t *cmd;
1958 
1959 	ASSERT(mutex_owned(&qp->nq_mutex));
1960 	ASSERT3S(cid, <, qp->nq_nentry);
1961 
1962 	cmd = qp->nq_cmd[cid];
1963 	/*
1964 	 * Some controllers will erroneously add things to the completion queue
1965 	 * for which there is no matching outstanding command. If this happens,
1966 	 * it is almost certainly a controller firmware bug since nq_mutex
1967 	 * is held across command submission and ringing the queue doorbell,
1968 	 * and is also held in this function.
1969 	 *
1970 	 * If we see such an unexpected command, there is not much we can do.
1971 	 * These will be logged and counted in nvme_get_completed(), but
1972 	 * otherwise ignored.
1973 	 */
1974 	if (cmd == NULL)
1975 		return (NULL);
1976 	qp->nq_cmd[cid] = NULL;
1977 	ASSERT3U(qp->nq_active_cmds, >, 0);
1978 	qp->nq_active_cmds--;
1979 	ASSERT3U(qp->nq_active_timeout, >=, cmd->nc_timeout);
1980 	qp->nq_active_timeout -= cmd->nc_timeout;
1981 	sema_v(&qp->nq_sema);
1982 
1983 	ASSERT3P(cmd, !=, NULL);
1984 	ASSERT3P(cmd->nc_nvme, ==, nvme);
1985 	ASSERT3S(cmd->nc_sqe.sqe_cid, ==, cid);
1986 
1987 	return (cmd);
1988 }
1989 
1990 /*
1991  * This is called when an admin abort has failed to complete, once for the
1992  * original command and once for the abort itself. At this point the controller
1993  * has been marked dead. The commands are considered lost, de-queued if
1994  * possible, and placed on a global lost commands list so that they cannot be
1995  * freed and so that any DMA memory they have have is not re-used.
1996  */
1997 static void
nvme_lost_cmd(nvme_t * nvme,nvme_cmd_t * cmd)1998 nvme_lost_cmd(nvme_t *nvme, nvme_cmd_t *cmd)
1999 {
2000 	ASSERT(mutex_owned(&cmd->nc_mutex));
2001 
2002 	switch (cmd->nc_state) {
2003 	case NVME_CMD_SUBMITTED: {
2004 		nvme_qpair_t *qp = nvme->n_ioq[cmd->nc_sqid];
2005 
2006 		/*
2007 		 * The command is still in the submitted state, meaning that we
2008 		 * have not processed a completion queue entry for it. De-queue
2009 		 * should be successful and if the hardware does later report
2010 		 * completion we'll skip it as a command for which we aren't
2011 		 * expecting a response (see nvme_unqueue_cmd()).
2012 		 */
2013 		mutex_enter(&qp->nq_mutex);
2014 		(void) nvme_unqueue_cmd(nvme, qp, cmd->nc_sqe.sqe_cid);
2015 		mutex_exit(&qp->nq_mutex);
2016 	}
2017 	case NVME_CMD_ALLOCATED:
2018 	case NVME_CMD_COMPLETED:
2019 		/*
2020 		 * If the command has not been submitted, or has completed,
2021 		 * there is nothing to do here. In the event of an abort
2022 		 * command timeout, we can end up here in the process of
2023 		 * "losing" the original command. It's possible that command
2024 		 * has actually completed (or been queued on the taskq) in the
2025 		 * interim.
2026 		 */
2027 		break;
2028 	case NVME_CMD_QUEUED:
2029 		/*
2030 		 * The command is on the taskq, awaiting callback. This should
2031 		 * be fairly rapid so wait for completion.
2032 		 */
2033 		while (cmd->nc_state != NVME_CMD_COMPLETED)
2034 			cv_wait(&cmd->nc_cv, &cmd->nc_mutex);
2035 		break;
2036 	case NVME_CMD_LOST:
2037 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
2038 		    "%s: command %p already lost", __func__, (void *)cmd);
2039 		break;
2040 	}
2041 
2042 	cmd->nc_state = NVME_CMD_LOST;
2043 
2044 	mutex_enter(&nvme_lc_mutex);
2045 	list_insert_head(&nvme_lost_cmds, cmd);
2046 	mutex_exit(&nvme_lc_mutex);
2047 }
2048 
2049 /*
2050  * Get the command tied to the next completed cqe and bump along completion
2051  * queue head counter.
2052  */
2053 static nvme_cmd_t *
nvme_get_completed(nvme_t * nvme,nvme_cq_t * cq)2054 nvme_get_completed(nvme_t *nvme, nvme_cq_t *cq)
2055 {
2056 	nvme_qpair_t *qp;
2057 	nvme_cqe_t *cqe;
2058 	nvme_cmd_t *cmd;
2059 
2060 	ASSERT(mutex_owned(&cq->ncq_mutex));
2061 
2062 retry:
2063 	cqe = &cq->ncq_cq[cq->ncq_head];
2064 
2065 	/* Check phase tag of CQE. Hardware inverts it for new entries. */
2066 	if (cqe->cqe_sf.sf_p == cq->ncq_phase)
2067 		return (NULL);
2068 
2069 	qp = nvme->n_ioq[cqe->cqe_sqid];
2070 
2071 	mutex_enter(&qp->nq_mutex);
2072 	cmd = nvme_unqueue_cmd(nvme, qp, cqe->cqe_cid);
2073 	mutex_exit(&qp->nq_mutex);
2074 
2075 	qp->nq_sqhead = cqe->cqe_sqhd;
2076 	cq->ncq_head = (cq->ncq_head + 1) % cq->ncq_nentry;
2077 
2078 	/* Toggle phase on wrap-around. */
2079 	if (cq->ncq_head == 0)
2080 		cq->ncq_phase = cq->ncq_phase != 0 ? 0 : 1;
2081 
2082 	if (cmd == NULL) {
2083 		dev_err(nvme->n_dip, CE_WARN,
2084 		    "!received completion for unknown cid 0x%x", cqe->cqe_cid);
2085 		NVME_BUMP_STAT(nvme, unknown_cid);
2086 		/*
2087 		 * We want to ignore this unexpected completion entry as it
2088 		 * is most likely a result of a bug in the controller firmware.
2089 		 * However, if we return NULL, then callers will assume there
2090 		 * are no more pending commands for this wakeup. Retry to keep
2091 		 * enumerating commands until the phase tag indicates there are
2092 		 * no more and we are really done.
2093 		 */
2094 		goto retry;
2095 	}
2096 
2097 	ASSERT3U(cmd->nc_sqid, ==, cqe->cqe_sqid);
2098 	bcopy(cqe, &cmd->nc_cqe, sizeof (nvme_cqe_t));
2099 
2100 	return (cmd);
2101 }
2102 
2103 /*
2104  * Process all completed commands on the io completion queue.
2105  */
2106 static uint_t
nvme_process_iocq(nvme_t * nvme,nvme_cq_t * cq)2107 nvme_process_iocq(nvme_t *nvme, nvme_cq_t *cq)
2108 {
2109 	nvme_reg_cqhdbl_t head = { 0 };
2110 	nvme_cmd_t *cmd;
2111 	uint_t completed = 0;
2112 
2113 	if (ddi_dma_sync(cq->ncq_dma->nd_dmah, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
2114 	    DDI_SUCCESS)
2115 		dev_err(nvme->n_dip, CE_WARN, "!ddi_dma_sync() failed in %s",
2116 		    __func__);
2117 
2118 	mutex_enter(&cq->ncq_mutex);
2119 
2120 	while ((cmd = nvme_get_completed(nvme, cq)) != NULL) {
2121 		/*
2122 		 * NVME_CMD_F_USELOCK is applied to all commands which are
2123 		 * going to be waited for by another thread in nvme_wait_cmd
2124 		 * and indicates that the lock should be taken before modifying
2125 		 * protected fields, and that the mutex has been initialised.
2126 		 * Commands which do not require the mutex to be held have not
2127 		 * initialised it (to reduce overhead).
2128 		 */
2129 		if ((cmd->nc_flags & NVME_CMD_F_USELOCK) != 0) {
2130 			mutex_enter(&cmd->nc_mutex);
2131 			/*
2132 			 * The command could have been de-queued as lost while
2133 			 * we waited on the lock, in which case we drop it.
2134 			 */
2135 			if (cmd->nc_state == NVME_CMD_LOST) {
2136 				mutex_exit(&cmd->nc_mutex);
2137 				completed++;
2138 				continue;
2139 			}
2140 		}
2141 		cmd->nc_queue_ts = gethrtime();
2142 		cmd->nc_state = NVME_CMD_QUEUED;
2143 		if ((cmd->nc_flags & NVME_CMD_F_USELOCK) != 0)
2144 			mutex_exit(&cmd->nc_mutex);
2145 		taskq_dispatch_ent(cq->ncq_cmd_taskq, cmd->nc_callback, cmd,
2146 		    TQ_NOSLEEP, &cmd->nc_tqent);
2147 
2148 		completed++;
2149 	}
2150 
2151 	if (completed > 0) {
2152 		/*
2153 		 * Update the completion queue head doorbell.
2154 		 */
2155 		head.b.cqhdbl_cqh = cq->ncq_head;
2156 		nvme_put32(nvme, cq->ncq_hdbl, head.r);
2157 	}
2158 
2159 	mutex_exit(&cq->ncq_mutex);
2160 
2161 	return (completed);
2162 }
2163 
2164 static nvme_cmd_t *
nvme_retrieve_cmd(nvme_t * nvme,nvme_qpair_t * qp)2165 nvme_retrieve_cmd(nvme_t *nvme, nvme_qpair_t *qp)
2166 {
2167 	nvme_cq_t *cq = qp->nq_cq;
2168 	nvme_reg_cqhdbl_t head = { 0 };
2169 	nvme_cmd_t *cmd;
2170 
2171 	if (ddi_dma_sync(cq->ncq_dma->nd_dmah, 0, 0, DDI_DMA_SYNC_FORKERNEL) !=
2172 	    DDI_SUCCESS)
2173 		dev_err(nvme->n_dip, CE_WARN, "!ddi_dma_sync() failed in %s",
2174 		    __func__);
2175 
2176 	mutex_enter(&cq->ncq_mutex);
2177 
2178 	if ((cmd = nvme_get_completed(nvme, cq)) != NULL) {
2179 		head.b.cqhdbl_cqh = cq->ncq_head;
2180 		nvme_put32(nvme, cq->ncq_hdbl, head.r);
2181 	}
2182 
2183 	mutex_exit(&cq->ncq_mutex);
2184 
2185 	return (cmd);
2186 }
2187 
2188 static int
nvme_check_unknown_cmd_status(nvme_cmd_t * cmd)2189 nvme_check_unknown_cmd_status(nvme_cmd_t *cmd)
2190 {
2191 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2192 
2193 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
2194 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
2195 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
2196 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
2197 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
2198 
2199 	if (cmd->nc_xfer != NULL)
2200 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
2201 
2202 	/*
2203 	 * User commands should never cause us to mark the controller dead.
2204 	 * Though whether we ever should mark it dead as there currently isn't a
2205 	 * useful recovery path is another question.
2206 	 */
2207 	if (((cmd->nc_flags & NVME_CMD_F_DONTPANIC) == 0) &&
2208 	    cmd->nc_nvme->n_strict_version) {
2209 		nvme_ctrl_mark_dead(cmd->nc_nvme, B_FALSE);
2210 	}
2211 
2212 	return (EIO);
2213 }
2214 
2215 static int
nvme_check_vendor_cmd_status(nvme_cmd_t * cmd)2216 nvme_check_vendor_cmd_status(nvme_cmd_t *cmd)
2217 {
2218 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2219 
2220 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
2221 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
2222 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
2223 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
2224 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
2225 	if (!cmd->nc_nvme->n_ignore_unknown_vendor_status) {
2226 		nvme_ctrl_mark_dead(cmd->nc_nvme, B_FALSE);
2227 	}
2228 
2229 	return (EIO);
2230 }
2231 
2232 static int
nvme_check_integrity_cmd_status(nvme_cmd_t * cmd)2233 nvme_check_integrity_cmd_status(nvme_cmd_t *cmd)
2234 {
2235 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2236 
2237 	switch (cqe->cqe_sf.sf_sc) {
2238 	case NVME_CQE_SC_INT_NVM_WRITE:
2239 		/* write fail */
2240 		/* TODO: post ereport */
2241 		if (cmd->nc_xfer != NULL)
2242 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
2243 		return (EIO);
2244 
2245 	case NVME_CQE_SC_INT_NVM_READ:
2246 		/* read fail */
2247 		/* TODO: post ereport */
2248 		if (cmd->nc_xfer != NULL)
2249 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
2250 		return (EIO);
2251 
2252 	default:
2253 		return (nvme_check_unknown_cmd_status(cmd));
2254 	}
2255 }
2256 
2257 static int
nvme_check_generic_cmd_status(nvme_cmd_t * cmd)2258 nvme_check_generic_cmd_status(nvme_cmd_t *cmd)
2259 {
2260 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2261 
2262 	switch (cqe->cqe_sf.sf_sc) {
2263 	case NVME_CQE_SC_GEN_SUCCESS:
2264 		return (0);
2265 
2266 	/*
2267 	 * Errors indicating a bug in the driver should cause a panic.
2268 	 */
2269 	case NVME_CQE_SC_GEN_INV_OPC:
2270 		/* Invalid Command Opcode */
2271 		NVME_BUMP_STAT(cmd->nc_nvme, inv_cmd_err);
2272 		if ((cmd->nc_flags & NVME_CMD_F_DONTPANIC) == 0) {
2273 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
2274 			    "programming error: invalid opcode in cmd %p",
2275 			    (void *)cmd);
2276 		}
2277 		return (EINVAL);
2278 
2279 	case NVME_CQE_SC_GEN_INV_FLD:
2280 		/* Invalid Field in Command */
2281 		NVME_BUMP_STAT(cmd->nc_nvme, inv_field_err);
2282 		if ((cmd->nc_flags & NVME_CMD_F_DONTPANIC) == 0) {
2283 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
2284 			    "programming error: invalid field in cmd %p",
2285 			    (void *)cmd);
2286 		}
2287 		return (EIO);
2288 
2289 	case NVME_CQE_SC_GEN_ID_CNFL:
2290 		/* Command ID Conflict */
2291 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
2292 		    "cmd ID conflict in cmd %p", (void *)cmd);
2293 		return (0);
2294 
2295 	case NVME_CQE_SC_GEN_INV_NS:
2296 		/* Invalid Namespace or Format */
2297 		NVME_BUMP_STAT(cmd->nc_nvme, inv_nsfmt_err);
2298 		if ((cmd->nc_flags & NVME_CMD_F_DONTPANIC) == 0) {
2299 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
2300 			    "programming error: invalid NS/format in cmd %p",
2301 			    (void *)cmd);
2302 		}
2303 		return (EINVAL);
2304 
2305 	case NVME_CQE_SC_GEN_CMD_SEQ_ERR:
2306 		/*
2307 		 * Command Sequence Error
2308 		 *
2309 		 * This can be generated normally by user log page requests that
2310 		 * come out of order (e.g. getting the persistent event log
2311 		 * without establishing the context). If the kernel manages this
2312 		 * on its own then that's problematic.
2313 		 */
2314 		NVME_BUMP_STAT(cmd->nc_nvme, inv_cmdseq_err);
2315 		if ((cmd->nc_flags & NVME_CMD_F_DONTPANIC) == 0) {
2316 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
2317 			    "programming error: command sequencing error %p",
2318 			    (void *)cmd);
2319 		}
2320 		return (EINVAL);
2321 
2322 	case NVME_CQE_SC_GEN_NVM_LBA_RANGE:
2323 		/* LBA Out Of Range */
2324 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
2325 		    "LBA out of range in cmd %p", (void *)cmd);
2326 		return (0);
2327 
2328 	/*
2329 	 * Non-fatal errors, handle gracefully.
2330 	 */
2331 	case NVME_CQE_SC_GEN_DATA_XFR_ERR:
2332 		/* Data Transfer Error (DMA) */
2333 		/* TODO: post ereport */
2334 		NVME_BUMP_STAT(cmd->nc_nvme, data_xfr_err);
2335 		if (cmd->nc_xfer != NULL)
2336 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
2337 		return (EIO);
2338 
2339 	case NVME_CQE_SC_GEN_INTERNAL_ERR:
2340 		/*
2341 		 * Internal Error. The spec (v1.0, section 4.5.1.2) says
2342 		 * detailed error information is returned as async event,
2343 		 * so we pretty much ignore the error here and handle it
2344 		 * in the async event handler.
2345 		 */
2346 		NVME_BUMP_STAT(cmd->nc_nvme, internal_err);
2347 		if (cmd->nc_xfer != NULL)
2348 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
2349 		return (EIO);
2350 
2351 	case NVME_CQE_SC_GEN_ABORT_REQUEST:
2352 		/*
2353 		 * Command Abort Requested. This normally happens only when a
2354 		 * command times out.
2355 		 */
2356 		/* TODO: post ereport or change blkdev to handle this? */
2357 		NVME_BUMP_STAT(cmd->nc_nvme, abort_rq_err);
2358 		return (ECANCELED);
2359 
2360 	case NVME_CQE_SC_GEN_ABORT_PWRLOSS:
2361 		/* Command Aborted due to Power Loss Notification */
2362 		NVME_BUMP_STAT(cmd->nc_nvme, abort_pwrloss_err);
2363 		nvme_ctrl_mark_dead(cmd->nc_nvme, B_FALSE);
2364 		return (EIO);
2365 
2366 	case NVME_CQE_SC_GEN_ABORT_SQ_DEL:
2367 		/* Command Aborted due to SQ Deletion */
2368 		NVME_BUMP_STAT(cmd->nc_nvme, abort_sq_del);
2369 		return (EIO);
2370 
2371 	case NVME_CQE_SC_GEN_NVM_CAP_EXC:
2372 		/* Capacity Exceeded */
2373 		NVME_BUMP_STAT(cmd->nc_nvme, nvm_cap_exc);
2374 		if (cmd->nc_xfer != NULL)
2375 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
2376 		return (EIO);
2377 
2378 	case NVME_CQE_SC_GEN_NVM_NS_NOTRDY:
2379 		/* Namespace Not Ready */
2380 		NVME_BUMP_STAT(cmd->nc_nvme, nvm_ns_notrdy);
2381 		if (cmd->nc_xfer != NULL)
2382 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
2383 		return (EIO);
2384 
2385 	case NVME_CQE_SC_GEN_NVM_FORMATTING:
2386 		/* Format in progress (1.2) */
2387 		if (!NVME_VERSION_ATLEAST(&cmd->nc_nvme->n_version, 1, 2))
2388 			return (nvme_check_unknown_cmd_status(cmd));
2389 		NVME_BUMP_STAT(cmd->nc_nvme, nvm_ns_formatting);
2390 		if (cmd->nc_xfer != NULL)
2391 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
2392 		return (EIO);
2393 
2394 	default:
2395 		return (nvme_check_unknown_cmd_status(cmd));
2396 	}
2397 }
2398 
2399 static int
nvme_check_specific_cmd_status(nvme_cmd_t * cmd)2400 nvme_check_specific_cmd_status(nvme_cmd_t *cmd)
2401 {
2402 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2403 
2404 	switch (cqe->cqe_sf.sf_sc) {
2405 	case NVME_CQE_SC_SPC_INV_CQ:
2406 		/* Completion Queue Invalid */
2407 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE);
2408 		NVME_BUMP_STAT(cmd->nc_nvme, inv_cq_err);
2409 		return (EINVAL);
2410 
2411 	case NVME_CQE_SC_SPC_INV_QID:
2412 		/* Invalid Queue Identifier */
2413 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
2414 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_SQUEUE ||
2415 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE ||
2416 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
2417 		NVME_BUMP_STAT(cmd->nc_nvme, inv_qid_err);
2418 		return (EINVAL);
2419 
2420 	case NVME_CQE_SC_SPC_MAX_QSZ_EXC:
2421 		/* Max Queue Size Exceeded */
2422 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
2423 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
2424 		NVME_BUMP_STAT(cmd->nc_nvme, max_qsz_exc);
2425 		return (EINVAL);
2426 
2427 	case NVME_CQE_SC_SPC_ABRT_CMD_EXC:
2428 		/* Abort Command Limit Exceeded */
2429 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT);
2430 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
2431 		    "abort command limit exceeded in cmd %p", (void *)cmd);
2432 		return (0);
2433 
2434 	case NVME_CQE_SC_SPC_ASYNC_EVREQ_EXC:
2435 		/* Async Event Request Limit Exceeded */
2436 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ASYNC_EVENT);
2437 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
2438 		    "async event request limit exceeded in cmd %p",
2439 		    (void *)cmd);
2440 		return (0);
2441 
2442 	case NVME_CQE_SC_SPC_INV_INT_VECT:
2443 		/* Invalid Interrupt Vector */
2444 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
2445 		NVME_BUMP_STAT(cmd->nc_nvme, inv_int_vect);
2446 		return (EINVAL);
2447 
2448 	case NVME_CQE_SC_SPC_INV_LOG_PAGE:
2449 		/* Invalid Log Page */
2450 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_GET_LOG_PAGE);
2451 		NVME_BUMP_STAT(cmd->nc_nvme, inv_log_page);
2452 		return (EINVAL);
2453 
2454 	case NVME_CQE_SC_SPC_INV_FORMAT:
2455 		/* Invalid Format */
2456 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_FORMAT ||
2457 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NS_MGMT);
2458 		NVME_BUMP_STAT(cmd->nc_nvme, inv_format);
2459 		if (cmd->nc_xfer != NULL)
2460 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
2461 		return (EINVAL);
2462 
2463 	case NVME_CQE_SC_SPC_INV_Q_DEL:
2464 		/* Invalid Queue Deletion */
2465 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
2466 		NVME_BUMP_STAT(cmd->nc_nvme, inv_q_del);
2467 		return (EINVAL);
2468 
2469 	case NVME_CQE_SC_SPC_NVM_CNFL_ATTR:
2470 		/* Conflicting Attributes */
2471 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_DSET_MGMT ||
2472 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
2473 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
2474 		NVME_BUMP_STAT(cmd->nc_nvme, cnfl_attr);
2475 		if (cmd->nc_xfer != NULL)
2476 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
2477 		return (EINVAL);
2478 
2479 	case NVME_CQE_SC_SPC_NVM_INV_PROT:
2480 		/* Invalid Protection Information */
2481 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_COMPARE ||
2482 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
2483 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
2484 		NVME_BUMP_STAT(cmd->nc_nvme, inv_prot);
2485 		if (cmd->nc_xfer != NULL)
2486 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
2487 		return (EINVAL);
2488 
2489 	case NVME_CQE_SC_SPC_NVM_READONLY:
2490 		/* Write to Read Only Range */
2491 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
2492 		NVME_BUMP_STAT(cmd->nc_nvme, readonly);
2493 		if (cmd->nc_xfer != NULL)
2494 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
2495 		return (EROFS);
2496 
2497 	case NVME_CQE_SC_SPC_INV_FW_SLOT:
2498 		/* Invalid Firmware Slot */
2499 		NVME_BUMP_STAT(cmd->nc_nvme, inv_fwslot);
2500 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2501 		return (EINVAL);
2502 
2503 	case NVME_CQE_SC_SPC_INV_FW_IMG:
2504 		/* Invalid Firmware Image */
2505 		NVME_BUMP_STAT(cmd->nc_nvme, inv_fwimg);
2506 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2507 		return (EINVAL);
2508 
2509 	case NVME_CQE_SC_SPC_FW_RESET:
2510 		/* Conventional Reset Required */
2511 		NVME_BUMP_STAT(cmd->nc_nvme, fwact_creset);
2512 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2513 		return (0);
2514 
2515 	case NVME_CQE_SC_SPC_FW_NSSR:
2516 		/* NVMe Subsystem Reset Required */
2517 		NVME_BUMP_STAT(cmd->nc_nvme, fwact_nssr);
2518 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2519 		return (0);
2520 
2521 	case NVME_CQE_SC_SPC_FW_NEXT_RESET:
2522 		/* Activation Requires Reset */
2523 		NVME_BUMP_STAT(cmd->nc_nvme, fwact_reset);
2524 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2525 		return (0);
2526 
2527 	case NVME_CQE_SC_SPC_FW_MTFA:
2528 		/* Activation Requires Maximum Time Violation */
2529 		NVME_BUMP_STAT(cmd->nc_nvme, fwact_mtfa);
2530 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2531 		return (EAGAIN);
2532 
2533 	case NVME_CQE_SC_SPC_FW_PROHIBITED:
2534 		/* Activation Prohibited */
2535 		NVME_BUMP_STAT(cmd->nc_nvme, fwact_prohibited);
2536 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2537 		return (EINVAL);
2538 
2539 	case NVME_CQE_SC_SPC_FW_OVERLAP:
2540 		/* Overlapping Firmware Ranges */
2541 		NVME_BUMP_STAT(cmd->nc_nvme, fw_overlap);
2542 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_FW_IMAGE_LOAD ||
2543 		    cmd->nc_sqe.sqe_opc == NVME_OPC_FW_ACTIVATE);
2544 		return (EINVAL);
2545 
2546 	case NVME_CQE_SC_SPC_NS_ATTACHED:
2547 		/* Namespace Already Attached */
2548 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2549 		NVME_BUMP_STAT(cmd->nc_nvme, ns_attached);
2550 		return (EEXIST);
2551 
2552 	case NVME_CQE_SC_SPC_NS_PRIV:
2553 		/* Namespace Is Private */
2554 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2555 		NVME_BUMP_STAT(cmd->nc_nvme, ns_priv);
2556 		return (EACCES);
2557 
2558 	case NVME_CQE_SC_SPC_NS_NOT_ATTACH:
2559 		/* Namespace Not Attached */
2560 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2561 		NVME_BUMP_STAT(cmd->nc_nvme, ns_not_attached);
2562 		return (ENOENT);
2563 
2564 	case NVME_CQE_SC_SPC_INV_CTRL_LIST:
2565 		/* Controller List Invalid */
2566 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2567 		NVME_BUMP_STAT(cmd->nc_nvme, ana_attach);
2568 		return (EINVAL);
2569 
2570 	case NVME_CQE_SC_SPC_ANA_ATTACH:
2571 		/* ANA Attach Failed */
2572 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2573 		NVME_BUMP_STAT(cmd->nc_nvme, ana_attach);
2574 		return (EIO);
2575 
2576 	case NVME_CQE_SC_SPC_NS_ATTACH_LIM:
2577 		/* Namespace Attachment Limit Exceeded */
2578 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NS_ATTACH);
2579 		NVME_BUMP_STAT(cmd->nc_nvme, ns_attach_lim);
2580 		return (EOVERFLOW);
2581 
2582 	default:
2583 		return (nvme_check_unknown_cmd_status(cmd));
2584 	}
2585 }
2586 
2587 static inline int
nvme_check_cmd_status(nvme_cmd_t * cmd)2588 nvme_check_cmd_status(nvme_cmd_t *cmd)
2589 {
2590 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2591 
2592 	/*
2593 	 * Take a shortcut if the controller is dead, or if
2594 	 * command status indicates no error.
2595 	 */
2596 	if (cmd->nc_nvme->n_dead)
2597 		return (EIO);
2598 
2599 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
2600 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
2601 		return (0);
2602 
2603 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC)
2604 		return (nvme_check_generic_cmd_status(cmd));
2605 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC)
2606 		return (nvme_check_specific_cmd_status(cmd));
2607 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY)
2608 		return (nvme_check_integrity_cmd_status(cmd));
2609 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR)
2610 		return (nvme_check_vendor_cmd_status(cmd));
2611 
2612 	return (nvme_check_unknown_cmd_status(cmd));
2613 }
2614 
2615 /*
2616  * Check the command status as used by an ioctl path and do not convert it to an
2617  * errno. We still allow all the command status checking to occur, but otherwise
2618  * will pass back the controller error as is.
2619  */
2620 static boolean_t
nvme_check_cmd_status_ioctl(nvme_cmd_t * cmd,nvme_ioctl_common_t * ioc)2621 nvme_check_cmd_status_ioctl(nvme_cmd_t *cmd, nvme_ioctl_common_t *ioc)
2622 {
2623 	nvme_cqe_t *cqe = &cmd->nc_cqe;
2624 	nvme_t *nvme = cmd->nc_nvme;
2625 
2626 	if (nvme->n_dead) {
2627 		return (nvme_ioctl_error(ioc, nvme->n_dead_status, 0, 0));
2628 	}
2629 
2630 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
2631 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
2632 		return (B_TRUE);
2633 
2634 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC) {
2635 		(void) nvme_check_generic_cmd_status(cmd);
2636 	} else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC) {
2637 		(void) nvme_check_specific_cmd_status(cmd);
2638 	} else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY) {
2639 		(void) nvme_check_integrity_cmd_status(cmd);
2640 	} else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR) {
2641 		(void) nvme_check_vendor_cmd_status(cmd);
2642 	} else {
2643 		(void) nvme_check_unknown_cmd_status(cmd);
2644 	}
2645 
2646 	return (nvme_ioctl_error(ioc, NVME_IOCTL_E_CTRL_ERROR,
2647 	    cqe->cqe_sf.sf_sct, cqe->cqe_sf.sf_sc));
2648 }
2649 
2650 static int
nvme_abort_cmd(nvme_cmd_t * cmd,const uint32_t sec)2651 nvme_abort_cmd(nvme_cmd_t *cmd, const uint32_t sec)
2652 {
2653 	nvme_t *nvme = cmd->nc_nvme;
2654 	nvme_cmd_t *abort_cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
2655 	nvme_abort_cmd_t ac = { 0 };
2656 	int ret = 0;
2657 
2658 	sema_p(&nvme->n_abort_sema);
2659 
2660 	ac.b.ac_cid = cmd->nc_sqe.sqe_cid;
2661 	ac.b.ac_sqid = cmd->nc_sqid;
2662 
2663 	abort_cmd->nc_sqid = 0;
2664 	abort_cmd->nc_sqe.sqe_opc = NVME_OPC_ABORT;
2665 	abort_cmd->nc_callback = nvme_wakeup_cmd;
2666 	abort_cmd->nc_sqe.sqe_cdw10 = ac.r;
2667 
2668 	/*
2669 	 * Send the ABORT to the hardware. The ABORT command will return _after_
2670 	 * the aborted command has completed (aborted or otherwise) so we must
2671 	 * drop the aborted command's lock to allow it to complete.
2672 	 * We want to allow at least `nvme_abort_cmd_timeout` seconds for the
2673 	 * abort to be processed, but more if we are aborting a long-running
2674 	 * command to give that time to complete/abort too.
2675 	 */
2676 	mutex_exit(&cmd->nc_mutex);
2677 	nvme_admin_cmd(abort_cmd, MAX(nvme_abort_cmd_timeout, sec));
2678 	mutex_enter(&cmd->nc_mutex);
2679 
2680 	sema_v(&nvme->n_abort_sema);
2681 
2682 	/* BEGIN CSTYLED */
2683 	/*
2684 	 * If the abort command itself has timed out, it will have been
2685 	 * de-queued so that its callback will not be called after this point,
2686 	 * and its state will be NVME_CMD_LOST.
2687 	 *
2688 	 * nvme_admin_cmd(abort_cmd)
2689 	 *   -> nvme_wait_cmd(abort_cmd)
2690 	 *     -> nvme_cmd(abort_cmd)
2691 	 *     | -> nvme_admin_cmd(cmd)
2692 	 *     |   -> nvme_wait_cmd(cmd)
2693 	 *     |     -> nvme_ctrl_mark_dead()
2694 	 *     |     -> nvme_lost_cmd(cmd)
2695 	 *     |       -> cmd->nc_stat = NVME_CMD_LOST
2696 	 *     and here we are.
2697 	 */
2698 	/* END CSTYLED */
2699 	if (abort_cmd->nc_state == NVME_CMD_LOST) {
2700 		dev_err(nvme->n_dip, CE_WARN,
2701 		    "!ABORT of command %d/%d timed out",
2702 		    cmd->nc_sqe.sqe_cid, cmd->nc_sqid);
2703 		NVME_BUMP_STAT(nvme, abort_timeout);
2704 		ret = EIO;
2705 	} else if ((ret = nvme_check_cmd_status(abort_cmd)) != 0) {
2706 		dev_err(nvme->n_dip, CE_WARN,
2707 		    "!ABORT of command %d/%d "
2708 		    "failed with sct = %x, sc = %x",
2709 		    cmd->nc_sqe.sqe_cid, cmd->nc_sqid,
2710 		    abort_cmd->nc_cqe.cqe_sf.sf_sct,
2711 		    abort_cmd->nc_cqe.cqe_sf.sf_sc);
2712 		NVME_BUMP_STAT(nvme, abort_failed);
2713 	} else {
2714 		boolean_t success = ((abort_cmd->nc_cqe.cqe_dw0 & 1) == 0);
2715 
2716 		dev_err(nvme->n_dip, CE_WARN,
2717 		    "!ABORT of command %d/%d %ssuccessful",
2718 		    cmd->nc_sqe.sqe_cid, cmd->nc_sqid,
2719 		    success ? "" : "un");
2720 
2721 		if (success) {
2722 			NVME_BUMP_STAT(nvme, abort_successful);
2723 		} else {
2724 			NVME_BUMP_STAT(nvme, abort_unsuccessful);
2725 		}
2726 	}
2727 
2728 	/*
2729 	 * This abort abort_cmd has either completed or been de-queued as
2730 	 * lost in nvme_wait_cmd. Either way it's safe to free it here.
2731 	 */
2732 	nvme_free_cmd(abort_cmd);
2733 
2734 	return (ret);
2735 }
2736 
2737 /*
2738  * nvme_wait_cmd -- wait for command completion or timeout
2739  *
2740  * In case of a serious error or a timeout of the abort command the hardware
2741  * will be declared dead and FMA will be notified.
2742  */
2743 static void
nvme_wait_cmd(nvme_cmd_t * cmd,uint32_t sec)2744 nvme_wait_cmd(nvme_cmd_t *cmd, uint32_t sec)
2745 {
2746 	nvme_t *nvme = cmd->nc_nvme;
2747 	nvme_reg_csts_t csts;
2748 	uint_t ccnt;
2749 
2750 	ASSERT(mutex_owned(&cmd->nc_mutex));
2751 
2752 	while (cmd->nc_state != NVME_CMD_COMPLETED) {
2753 		clock_t timeout = ddi_get_lbolt() +
2754 		    drv_usectohz((long)sec * MICROSEC);
2755 
2756 		if (cv_timedwait(&cmd->nc_cv, &cmd->nc_mutex, timeout) == -1) {
2757 			/*
2758 			 * If this command is on the task queue then we don't
2759 			 * consider it to have timed out. We are waiting for
2760 			 * the callback to be invoked, the timing of which can
2761 			 * be affected by system load and should not count
2762 			 * against the device; continue to wait.
2763 			 * While this doesn't help deal with the possibility of
2764 			 * a command timing out between being placed on the CQ
2765 			 * and arriving on the taskq, we expect interrupts to
2766 			 * run fairly promptly making this a small window.
2767 			 */
2768 			if (cmd->nc_state != NVME_CMD_QUEUED)
2769 				break;
2770 		}
2771 	}
2772 
2773 	if (cmd->nc_state == NVME_CMD_COMPLETED) {
2774 		DTRACE_PROBE1(nvme_admin_cmd_completed, nvme_cmd_t *, cmd);
2775 		nvme_admin_stat_cmd(nvme, cmd);
2776 		return;
2777 	}
2778 
2779 	/*
2780 	 * The command timed out.
2781 	 */
2782 
2783 	DTRACE_PROBE1(nvme_admin_cmd_timeout, nvme_cmd_t *, cmd);
2784 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2785 	dev_err(nvme->n_dip, CE_WARN, "!command %d/%d timeout, "
2786 	    "OPC = 0x%x, CFS = %u, STATUS = 0x%x",
2787 	    cmd->nc_sqe.sqe_cid, cmd->nc_sqid, cmd->nc_sqe.sqe_opc,
2788 	    csts.b.csts_cfs, csts.r);
2789 	NVME_BUMP_STAT(nvme, cmd_timeout);
2790 
2791 	/*
2792 	 * Check controller for fatal status, any errors associated with the
2793 	 * register or DMA handle, or for a double timeout (abort command timed
2794 	 * out). If necessary log a warning and call FMA.
2795 	 */
2796 	if (csts.b.csts_cfs ||
2797 	    nvme_check_regs_hdl(nvme) ||
2798 	    nvme_check_dma_hdl(cmd->nc_dma) ||
2799 	    cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT) {
2800 		nvme_ctrl_mark_dead(cmd->nc_nvme, B_FALSE);
2801 		nvme_lost_cmd(nvme, cmd);
2802 		return;
2803 	}
2804 
2805 	/*
2806 	 * Poll admin completion queue to see if we missed an interrupt or the
2807 	 * controller never gave us one. Some buggy controller firmwares (e.g.
2808 	 * SK hynix PE1030 FW v1.0 and Solidigm D7-PS1010) do this, especially
2809 	 * on the first admin command.
2810 	 *
2811 	 * At this point we are holding the cmd's nc_mutex and we need to go
2812 	 * grab the adminq's ncq_mutex to check for completions. Grabbing it
2813 	 * would violate our lock ordering, but we can safely drop nc_mutex
2814 	 * here and pick it back up, as long as the following hold:
2815 	 *
2816 	 * - We don't assume the cmd's state remains the same after doing
2817 	 *   this (and also don't assume we are the only ones who could
2818 	 *   change it, since an interrupt may arrive)
2819 	 *   => we re-check it below, even if we don't find any polled CQ
2820 	 *	entries
2821 	 * - Only one thread can be waiting on this specific command at a time
2822 	 *   so that we can't race against someone else freeing this command
2823 	 *   after waiting on it
2824 	 *   => true for admin commands, since nvme_admin_cmd always calls
2825 	 *	this function to wait and we don't dispatch them any other
2826 	 *	way
2827 	 * - The nc_callback for this command will never free the command
2828 	 *   => true, since admin commands always use nvme_wakeup_cmd
2829 	 * - nvme_process_iocq is safe to call concurrently against the same
2830 	 *   adminq from here and also from an interrupt
2831 	 *   => true, since nvme_process_iocq holds ncq_mutex for its entire
2832 	 *	duration and handles being called on a queue with nothing
2833 	 *	to do
2834 	 */
2835 	mutex_exit(&cmd->nc_mutex);
2836 	ccnt = nvme_process_iocq(nvme, nvme->n_adminq->nq_cq);
2837 	mutex_enter(&cmd->nc_mutex);
2838 	if (ccnt > 0) {
2839 		dev_err(nvme->n_dip, CE_WARN, "!possible missed interrupt "
2840 		    "(%u completions found on admin CQ at timeout)", ccnt);
2841 	}
2842 
2843 	/*
2844 	 * Re-check the command's state now, it may have changed while we
2845 	 * dropped nc_mutex.
2846 	 */
2847 	if (cmd->nc_state == NVME_CMD_COMPLETED) {
2848 		DTRACE_PROBE1(nvme_admin_cmd_completed, nvme_cmd_t *,
2849 		    cmd);
2850 		nvme_admin_stat_cmd(nvme, cmd);
2851 		return;
2852 	}
2853 
2854 	/*
2855 	 * At this point, we're out of ideas: issue an abort for the command
2856 	 * that has timed out.
2857 	 */
2858 	if (nvme_abort_cmd(cmd, sec) == 0) {
2859 		/*
2860 		 * If the abort completed, whether or not it was
2861 		 * successful in aborting the command, that command
2862 		 * will also have completed with an appropriate
2863 		 * status.
2864 		 */
2865 		while (cmd->nc_state != NVME_CMD_COMPLETED)
2866 			cv_wait(&cmd->nc_cv, &cmd->nc_mutex);
2867 		return;
2868 	}
2869 
2870 	/*
2871 	 * Otherwise, the abort has also timed out or failed, which
2872 	 * will have marked the controller dead. De-queue the original command
2873 	 * and add it to the lost commands list.
2874 	 */
2875 	VERIFY(cmd->nc_nvme->n_dead);
2876 	nvme_lost_cmd(nvme, cmd);
2877 }
2878 
2879 static void
nvme_wakeup_cmd(void * arg)2880 nvme_wakeup_cmd(void *arg)
2881 {
2882 	nvme_cmd_t *cmd = arg;
2883 
2884 	ASSERT(cmd->nc_flags & NVME_CMD_F_USELOCK);
2885 
2886 	mutex_enter(&cmd->nc_mutex);
2887 	cmd->nc_state = NVME_CMD_COMPLETED;
2888 	cv_signal(&cmd->nc_cv);
2889 	mutex_exit(&cmd->nc_mutex);
2890 }
2891 
2892 static void
nvme_async_event_task(void * arg)2893 nvme_async_event_task(void *arg)
2894 {
2895 	nvme_cmd_t *cmd = arg;
2896 	nvme_t *nvme = cmd->nc_nvme;
2897 	nvme_error_log_entry_t *error_log = NULL;
2898 	nvme_health_log_t *health_log = NULL;
2899 	nvme_nschange_list_t *nslist = NULL;
2900 	size_t logsize = 0;
2901 	nvme_async_event_t event;
2902 
2903 	/*
2904 	 * Check for errors associated with the async request itself. The only
2905 	 * command-specific error is "async event limit exceeded", which
2906 	 * indicates a programming error in the driver and causes a panic in
2907 	 * nvme_check_cmd_status().
2908 	 *
2909 	 * Other possible errors are various scenarios where the async request
2910 	 * was aborted, or internal errors in the device. Internal errors are
2911 	 * reported to FMA, the command aborts need no special handling here.
2912 	 *
2913 	 * And finally, at least qemu nvme does not support async events,
2914 	 * and will return NVME_CQE_SC_GEN_INV_OPC | DNR. If so, we
2915 	 * will avoid posting async events.
2916 	 */
2917 
2918 	if (nvme_check_cmd_status(cmd) != 0) {
2919 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
2920 		    "!async event request returned failure, sct = 0x%x, "
2921 		    "sc = 0x%x, dnr = %d, m = %d", cmd->nc_cqe.cqe_sf.sf_sct,
2922 		    cmd->nc_cqe.cqe_sf.sf_sc, cmd->nc_cqe.cqe_sf.sf_dnr,
2923 		    cmd->nc_cqe.cqe_sf.sf_m);
2924 
2925 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
2926 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INTERNAL_ERR) {
2927 			nvme_ctrl_mark_dead(cmd->nc_nvme, B_FALSE);
2928 		}
2929 
2930 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
2931 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INV_OPC &&
2932 		    cmd->nc_cqe.cqe_sf.sf_dnr == 1) {
2933 			nvme->n_async_event_supported = B_FALSE;
2934 		}
2935 
2936 		nvme_free_cmd(cmd);
2937 		return;
2938 	}
2939 
2940 	event.r = cmd->nc_cqe.cqe_dw0;
2941 
2942 	/* Clear CQE and re-submit the async request. */
2943 	bzero(&cmd->nc_cqe, sizeof (nvme_cqe_t));
2944 	nvme_submit_admin_cmd(nvme->n_adminq, cmd, NULL);
2945 	cmd = NULL;	/* cmd can no longer be used after resubmission */
2946 
2947 	switch (event.b.ae_type) {
2948 	case NVME_ASYNC_TYPE_ERROR:
2949 		if (event.b.ae_logpage == NVME_LOGPAGE_ERROR) {
2950 			if (!nvme_get_logpage_int(nvme, B_FALSE,
2951 			    (void **)&error_log, &logsize,
2952 			    NVME_LOGPAGE_ERROR)) {
2953 				return;
2954 			}
2955 		} else {
2956 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
2957 			    "async event reply: type=0x%x logpage=0x%x",
2958 			    event.b.ae_type, event.b.ae_logpage);
2959 			NVME_BUMP_STAT(nvme, wrong_logpage);
2960 			return;
2961 		}
2962 
2963 		switch (event.b.ae_info) {
2964 		case NVME_ASYNC_ERROR_INV_SQ:
2965 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
2966 			    "invalid submission queue");
2967 			return;
2968 
2969 		case NVME_ASYNC_ERROR_INV_DBL:
2970 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
2971 			    "invalid doorbell write value");
2972 			return;
2973 
2974 		case NVME_ASYNC_ERROR_DIAGFAIL:
2975 			dev_err(nvme->n_dip, CE_WARN, "!diagnostic failure");
2976 			nvme_ctrl_mark_dead(nvme, B_FALSE);
2977 			NVME_BUMP_STAT(nvme, diagfail_event);
2978 			break;
2979 
2980 		case NVME_ASYNC_ERROR_PERSISTENT:
2981 			dev_err(nvme->n_dip, CE_WARN, "!persistent internal "
2982 			    "device error");
2983 			nvme_ctrl_mark_dead(nvme, B_FALSE);
2984 			NVME_BUMP_STAT(nvme, persistent_event);
2985 			break;
2986 
2987 		case NVME_ASYNC_ERROR_TRANSIENT:
2988 			dev_err(nvme->n_dip, CE_WARN, "!transient internal "
2989 			    "device error");
2990 			/* TODO: send ereport */
2991 			NVME_BUMP_STAT(nvme, transient_event);
2992 			break;
2993 
2994 		case NVME_ASYNC_ERROR_FW_LOAD:
2995 			dev_err(nvme->n_dip, CE_WARN,
2996 			    "!firmware image load error");
2997 			NVME_BUMP_STAT(nvme, fw_load_event);
2998 			break;
2999 		}
3000 		break;
3001 
3002 	case NVME_ASYNC_TYPE_HEALTH:
3003 		if (event.b.ae_logpage == NVME_LOGPAGE_HEALTH) {
3004 			if (!nvme_get_logpage_int(nvme, B_FALSE,
3005 			    (void **)&health_log, &logsize,
3006 			    NVME_LOGPAGE_HEALTH)) {
3007 				return;
3008 			}
3009 		} else {
3010 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
3011 			    "type=0x%x logpage=0x%x", event.b.ae_type,
3012 			    event.b.ae_logpage);
3013 			NVME_BUMP_STAT(nvme, wrong_logpage);
3014 			return;
3015 		}
3016 
3017 		switch (event.b.ae_info) {
3018 		case NVME_ASYNC_HEALTH_RELIABILITY:
3019 			dev_err(nvme->n_dip, CE_WARN,
3020 			    "!device reliability compromised");
3021 			/* TODO: send ereport */
3022 			NVME_BUMP_STAT(nvme, reliability_event);
3023 			break;
3024 
3025 		case NVME_ASYNC_HEALTH_TEMPERATURE:
3026 			dev_err(nvme->n_dip, CE_WARN,
3027 			    "!temperature above threshold");
3028 			/* TODO: send ereport */
3029 			NVME_BUMP_STAT(nvme, temperature_event);
3030 			break;
3031 
3032 		case NVME_ASYNC_HEALTH_SPARE:
3033 			dev_err(nvme->n_dip, CE_WARN,
3034 			    "!spare space below threshold");
3035 			/* TODO: send ereport */
3036 			NVME_BUMP_STAT(nvme, spare_event);
3037 			break;
3038 		}
3039 		break;
3040 
3041 	case NVME_ASYNC_TYPE_NOTICE:
3042 		switch (event.b.ae_info) {
3043 		case NVME_ASYNC_NOTICE_NS_CHANGE:
3044 			if (event.b.ae_logpage != NVME_LOGPAGE_NSCHANGE) {
3045 				dev_err(nvme->n_dip, CE_WARN,
3046 				    "!wrong logpage in async event reply: "
3047 				    "type=0x%x logpage=0x%x",
3048 				    event.b.ae_type, event.b.ae_logpage);
3049 				NVME_BUMP_STAT(nvme, wrong_logpage);
3050 				break;
3051 			}
3052 
3053 			dev_err(nvme->n_dip, CE_NOTE,
3054 			    "namespace attribute change event, "
3055 			    "logpage = 0x%x", event.b.ae_logpage);
3056 			NVME_BUMP_STAT(nvme, notice_event);
3057 
3058 			if (!nvme_get_logpage_int(nvme, B_FALSE,
3059 			    (void **)&nslist, &logsize,
3060 			    NVME_LOGPAGE_NSCHANGE)) {
3061 				break;
3062 			}
3063 
3064 			if (nslist->nscl_ns[0] == UINT32_MAX) {
3065 				dev_err(nvme->n_dip, CE_CONT,
3066 				    "more than %u namespaces have changed.\n",
3067 				    NVME_NSCHANGE_LIST_SIZE);
3068 				break;
3069 			}
3070 
3071 			nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
3072 			for (uint_t i = 0; i < NVME_NSCHANGE_LIST_SIZE; i++) {
3073 				uint32_t nsid = nslist->nscl_ns[i];
3074 				nvme_namespace_t *ns;
3075 
3076 				if (nsid == 0)	/* end of list */
3077 					break;
3078 
3079 				dev_err(nvme->n_dip, CE_NOTE,
3080 				    "!namespace nvme%d/%u has changed.",
3081 				    ddi_get_instance(nvme->n_dip), nsid);
3082 
3083 				if (nvme_init_ns(nvme, nsid) != DDI_SUCCESS)
3084 					continue;
3085 
3086 				ns = nvme_nsid2ns(nvme, nsid);
3087 				if (ns->ns_state <= NVME_NS_STATE_NOT_IGNORED)
3088 					continue;
3089 
3090 				nvme_mgmt_bd_start(nvme);
3091 				bd_state_change(ns->ns_bd_hdl);
3092 				nvme_mgmt_bd_end(nvme);
3093 			}
3094 			nvme_mgmt_unlock(nvme);
3095 
3096 			break;
3097 
3098 		case NVME_ASYNC_NOTICE_FW_ACTIVATE:
3099 			dev_err(nvme->n_dip, CE_NOTE,
3100 			    "firmware activation starting, "
3101 			    "logpage = 0x%x", event.b.ae_logpage);
3102 			NVME_BUMP_STAT(nvme, notice_event);
3103 			break;
3104 
3105 		case NVME_ASYNC_NOTICE_TELEMETRY:
3106 			dev_err(nvme->n_dip, CE_NOTE,
3107 			    "telemetry log changed, "
3108 			    "logpage = 0x%x", event.b.ae_logpage);
3109 			NVME_BUMP_STAT(nvme, notice_event);
3110 			break;
3111 
3112 		case NVME_ASYNC_NOTICE_NS_ASYMM:
3113 			dev_err(nvme->n_dip, CE_NOTE,
3114 			    "asymmetric namespace access change, "
3115 			    "logpage = 0x%x", event.b.ae_logpage);
3116 			NVME_BUMP_STAT(nvme, notice_event);
3117 			break;
3118 
3119 		case NVME_ASYNC_NOTICE_LATENCYLOG:
3120 			dev_err(nvme->n_dip, CE_NOTE,
3121 			    "predictable latency event aggregate log change, "
3122 			    "logpage = 0x%x", event.b.ae_logpage);
3123 			NVME_BUMP_STAT(nvme, notice_event);
3124 			break;
3125 
3126 		case NVME_ASYNC_NOTICE_LBASTATUS:
3127 			dev_err(nvme->n_dip, CE_NOTE,
3128 			    "LBA status information alert, "
3129 			    "logpage = 0x%x", event.b.ae_logpage);
3130 			NVME_BUMP_STAT(nvme, notice_event);
3131 			break;
3132 
3133 		case NVME_ASYNC_NOTICE_ENDURANCELOG:
3134 			dev_err(nvme->n_dip, CE_NOTE,
3135 			    "endurance group event aggregate log page change, "
3136 			    "logpage = 0x%x", event.b.ae_logpage);
3137 			NVME_BUMP_STAT(nvme, notice_event);
3138 			break;
3139 
3140 		default:
3141 			dev_err(nvme->n_dip, CE_WARN,
3142 			    "!unknown notice async event received, "
3143 			    "info = 0x%x, logpage = 0x%x", event.b.ae_info,
3144 			    event.b.ae_logpage);
3145 			NVME_BUMP_STAT(nvme, unknown_event);
3146 			break;
3147 		}
3148 		break;
3149 
3150 	case NVME_ASYNC_TYPE_VENDOR:
3151 		dev_err(nvme->n_dip, CE_WARN, "!vendor specific async event "
3152 		    "received, info = 0x%x, logpage = 0x%x", event.b.ae_info,
3153 		    event.b.ae_logpage);
3154 		NVME_BUMP_STAT(nvme, vendor_event);
3155 		break;
3156 
3157 	default:
3158 		dev_err(nvme->n_dip, CE_WARN, "!unknown async event received, "
3159 		    "type = 0x%x, info = 0x%x, logpage = 0x%x", event.b.ae_type,
3160 		    event.b.ae_info, event.b.ae_logpage);
3161 		NVME_BUMP_STAT(nvme, unknown_event);
3162 		break;
3163 	}
3164 
3165 	if (error_log != NULL)
3166 		kmem_free(error_log, logsize);
3167 
3168 	if (health_log != NULL)
3169 		kmem_free(health_log, logsize);
3170 
3171 	if (nslist != NULL)
3172 		kmem_free(nslist, logsize);
3173 }
3174 
3175 static void
nvme_admin_cmd(nvme_cmd_t * cmd,uint32_t sec)3176 nvme_admin_cmd(nvme_cmd_t *cmd, uint32_t sec)
3177 {
3178 	uint32_t qtimeout;
3179 
3180 	ASSERT(cmd->nc_flags & NVME_CMD_F_USELOCK);
3181 
3182 	mutex_enter(&cmd->nc_mutex);
3183 	cmd->nc_timeout = sec;
3184 	nvme_submit_admin_cmd(cmd->nc_nvme->n_adminq, cmd, &qtimeout);
3185 	/*
3186 	 * We will wait for a total of this command's specified timeout plus
3187 	 * the sum of the timeouts of any commands queued ahead of this one. If
3188 	 * we aren't first in the queue, this will inflate the timeout somewhat
3189 	 * but these times are not critical and it means that if we get stuck
3190 	 * behind a long running command such as a namespace format then we
3191 	 * won't time out and trigger an abort.
3192 	 */
3193 	nvme_wait_cmd(cmd, sec + qtimeout);
3194 	mutex_exit(&cmd->nc_mutex);
3195 }
3196 
3197 static void
nvme_async_event(nvme_t * nvme)3198 nvme_async_event(nvme_t *nvme)
3199 {
3200 	nvme_cmd_t *cmd;
3201 
3202 	cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3203 	cmd->nc_sqid = 0;
3204 	cmd->nc_sqe.sqe_opc = NVME_OPC_ASYNC_EVENT;
3205 	cmd->nc_callback = nvme_async_event_task;
3206 	cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3207 
3208 	nvme_submit_admin_cmd(nvme->n_adminq, cmd, NULL);
3209 }
3210 
3211 /*
3212  * There are commands such as format or vendor unique commands that are going to
3213  * manipulate the data in a namespace or destroy them, we make sure that none of
3214  * the ones that will be impacted are actually attached.
3215  */
3216 static boolean_t
nvme_no_blkdev_attached(nvme_t * nvme,uint32_t nsid)3217 nvme_no_blkdev_attached(nvme_t *nvme, uint32_t nsid)
3218 {
3219 	ASSERT(nvme_mgmt_lock_held(nvme));
3220 	ASSERT3U(nsid, !=, 0);
3221 
3222 	if (nsid != NVME_NSID_BCAST) {
3223 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, nsid);
3224 		return (ns->ns_state < NVME_NS_STATE_ATTACHED);
3225 	}
3226 
3227 	for (uint32_t i = 1; i <= nvme->n_namespace_count; i++) {
3228 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, i);
3229 
3230 		if (ns->ns_state >= NVME_NS_STATE_ATTACHED) {
3231 			return (B_FALSE);
3232 		}
3233 	}
3234 
3235 	return (B_TRUE);
3236 }
3237 
3238 static boolean_t
nvme_format_nvm(nvme_t * nvme,nvme_ioctl_format_t * ioc)3239 nvme_format_nvm(nvme_t *nvme, nvme_ioctl_format_t *ioc)
3240 {
3241 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3242 	nvme_format_nvm_t format_nvm = { 0 };
3243 	boolean_t ret;
3244 
3245 	format_nvm.b.fm_lbaf = bitx32(ioc->nif_lbaf, 3, 0);
3246 	format_nvm.b.fm_ses = bitx32(ioc->nif_ses, 2, 0);
3247 
3248 	cmd->nc_sqid = 0;
3249 	cmd->nc_callback = nvme_wakeup_cmd;
3250 	cmd->nc_sqe.sqe_nsid = ioc->nif_common.nioc_nsid;
3251 	cmd->nc_sqe.sqe_opc = NVME_OPC_NVM_FORMAT;
3252 	cmd->nc_sqe.sqe_cdw10 = format_nvm.r;
3253 
3254 	/*
3255 	 * We don't want to panic on any format commands. There are two reasons
3256 	 * for this:
3257 	 *
3258 	 * 1) All format commands are initiated by users. We don't want to panic
3259 	 * on user commands.
3260 	 *
3261 	 * 2) Several devices like the Samsung SM951 don't allow formatting of
3262 	 * all namespaces in one command and we'd prefer to handle that
3263 	 * gracefully.
3264 	 */
3265 	cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3266 
3267 	nvme_admin_cmd(cmd, nvme_format_cmd_timeout);
3268 
3269 	if (!nvme_check_cmd_status_ioctl(cmd, &ioc->nif_common) != 0) {
3270 		dev_err(nvme->n_dip, CE_WARN,
3271 		    "!FORMAT failed with sct = %x, sc = %x",
3272 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
3273 		ret = B_FALSE;
3274 		goto fail;
3275 	}
3276 
3277 	ret = B_TRUE;
3278 fail:
3279 	nvme_free_cmd(cmd);
3280 	return (ret);
3281 }
3282 
3283 /*
3284  * Retrieve a specific log page. The contents of the log page request should
3285  * have already been validated by the system.
3286  */
3287 static boolean_t
nvme_get_logpage(nvme_t * nvme,boolean_t user,nvme_ioctl_get_logpage_t * log,void ** buf)3288 nvme_get_logpage(nvme_t *nvme, boolean_t user, nvme_ioctl_get_logpage_t *log,
3289     void **buf)
3290 {
3291 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3292 	nvme_getlogpage_dw10_t dw10;
3293 	uint32_t offlo, offhi;
3294 	nvme_getlogpage_dw11_t dw11;
3295 	nvme_getlogpage_dw14_t dw14;
3296 	uint32_t ndw;
3297 	boolean_t ret = B_FALSE;
3298 
3299 	bzero(&dw10, sizeof (dw10));
3300 	bzero(&dw11, sizeof (dw11));
3301 	bzero(&dw14, sizeof (dw14));
3302 
3303 	cmd->nc_sqid = 0;
3304 	cmd->nc_callback = nvme_wakeup_cmd;
3305 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_LOG_PAGE;
3306 	cmd->nc_sqe.sqe_nsid = log->nigl_common.nioc_nsid;
3307 
3308 	if (user)
3309 		cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3310 
3311 	/*
3312 	 * The size field is the number of double words, but is a zeros based
3313 	 * value. We need to store our actual value minus one.
3314 	 */
3315 	ndw = (uint32_t)(log->nigl_len / 4);
3316 	ASSERT3U(ndw, >, 0);
3317 	ndw--;
3318 
3319 	dw10.b.lp_lid = bitx32(log->nigl_lid, 7, 0);
3320 	dw10.b.lp_lsp = bitx32(log->nigl_lsp, 6, 0);
3321 	dw10.b.lp_rae = bitx32(log->nigl_lsp, 0, 0);
3322 	dw10.b.lp_lnumdl = bitx32(ndw, 15, 0);
3323 
3324 	dw11.b.lp_numdu = bitx32(ndw, 31, 16);
3325 	dw11.b.lp_lsi = bitx32(log->nigl_lsi, 15, 0);
3326 
3327 	offlo = bitx64(log->nigl_offset, 31, 0);
3328 	offhi = bitx64(log->nigl_offset, 63, 32);
3329 
3330 	dw14.b.lp_csi = bitx32(log->nigl_csi, 7, 0);
3331 
3332 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
3333 	cmd->nc_sqe.sqe_cdw11 = dw11.r;
3334 	cmd->nc_sqe.sqe_cdw12 = offlo;
3335 	cmd->nc_sqe.sqe_cdw13 = offhi;
3336 	cmd->nc_sqe.sqe_cdw14 = dw14.r;
3337 
3338 	if (nvme_zalloc_dma(nvme, log->nigl_len, DDI_DMA_READ,
3339 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
3340 		dev_err(nvme->n_dip, CE_WARN,
3341 		    "!nvme_zalloc_dma failed for GET LOG PAGE");
3342 		ret = nvme_ioctl_error(&log->nigl_common,
3343 		    NVME_IOCTL_E_NO_DMA_MEM, 0, 0);
3344 		goto fail;
3345 	}
3346 
3347 	if (nvme_fill_prp(cmd, cmd->nc_dma->nd_dmah) != 0) {
3348 		ret = nvme_ioctl_error(&log->nigl_common,
3349 		    NVME_IOCTL_E_NO_DMA_MEM, 0, 0);
3350 		goto fail;
3351 	}
3352 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3353 
3354 	if (!nvme_check_cmd_status_ioctl(cmd, &log->nigl_common)) {
3355 		if (!user) {
3356 			dev_err(nvme->n_dip, CE_WARN,
3357 			    "!GET LOG PAGE failed with sct = %x, sc = %x",
3358 			    cmd->nc_cqe.cqe_sf.sf_sct,
3359 			    cmd->nc_cqe.cqe_sf.sf_sc);
3360 		}
3361 		ret = B_FALSE;
3362 		goto fail;
3363 	}
3364 
3365 	*buf = kmem_alloc(log->nigl_len, KM_SLEEP);
3366 	bcopy(cmd->nc_dma->nd_memp, *buf, log->nigl_len);
3367 
3368 	ret = B_TRUE;
3369 fail:
3370 	nvme_free_cmd(cmd);
3371 
3372 	return (ret);
3373 }
3374 
3375 /*
3376  * This is an internal wrapper for when the kernel wants to get a log page.
3377  * Currently this assumes that the only thing that is required is the log page
3378  * ID. If more information is required, we'll be better served to just use the
3379  * general ioctl interface.
3380  */
3381 static boolean_t
nvme_get_logpage_int(nvme_t * nvme,boolean_t user,void ** buf,size_t * bufsize,uint8_t lid)3382 nvme_get_logpage_int(nvme_t *nvme, boolean_t user, void **buf, size_t *bufsize,
3383     uint8_t lid)
3384 {
3385 	const nvme_log_page_info_t *info = NULL;
3386 	nvme_ioctl_get_logpage_t log;
3387 	nvme_valid_ctrl_data_t data;
3388 	boolean_t bret;
3389 	bool var;
3390 
3391 	for (size_t i = 0; i < nvme_std_log_npages; i++) {
3392 		if (nvme_std_log_pages[i].nlpi_lid == lid &&
3393 		    nvme_std_log_pages[i].nlpi_csi == NVME_CSI_NVM) {
3394 			info = &nvme_std_log_pages[i];
3395 			break;
3396 		}
3397 	}
3398 
3399 	if (info == NULL) {
3400 		return (B_FALSE);
3401 	}
3402 
3403 	data.vcd_vers = &nvme->n_version;
3404 	data.vcd_id = nvme->n_idctl;
3405 	bzero(&log, sizeof (log));
3406 	log.nigl_common.nioc_nsid = NVME_NSID_BCAST;
3407 	log.nigl_csi = info->nlpi_csi;
3408 	log.nigl_lid = info->nlpi_lid;
3409 	log.nigl_len = nvme_log_page_info_size(info, &data, &var);
3410 
3411 	/*
3412 	 * We only support getting standard fixed-length log pages through the
3413 	 * kernel interface at this time. If a log page either has an unknown
3414 	 * size or has a variable length, then we cannot get it.
3415 	 */
3416 	if (log.nigl_len == 0 || var) {
3417 		return (B_FALSE);
3418 	}
3419 
3420 	bret = nvme_get_logpage(nvme, user, &log, buf);
3421 	if (!bret) {
3422 		return (B_FALSE);
3423 	}
3424 
3425 	*bufsize = log.nigl_len;
3426 	return (B_TRUE);
3427 }
3428 
3429 static boolean_t
nvme_identify(nvme_t * nvme,boolean_t user,nvme_ioctl_identify_t * ioc,void ** buf)3430 nvme_identify(nvme_t *nvme, boolean_t user, nvme_ioctl_identify_t *ioc,
3431     void **buf)
3432 {
3433 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3434 	boolean_t ret = B_FALSE;
3435 	nvme_identify_dw10_t dw10;
3436 
3437 	ASSERT3P(buf, !=, NULL);
3438 
3439 	bzero(&dw10, sizeof (dw10));
3440 
3441 	cmd->nc_sqid = 0;
3442 	cmd->nc_callback = nvme_wakeup_cmd;
3443 	cmd->nc_sqe.sqe_opc = NVME_OPC_IDENTIFY;
3444 	cmd->nc_sqe.sqe_nsid = ioc->nid_common.nioc_nsid;
3445 
3446 	dw10.b.id_cns = bitx32(ioc->nid_cns, 7, 0);
3447 	dw10.b.id_cntid = bitx32(ioc->nid_ctrlid, 15, 0);
3448 
3449 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
3450 
3451 	if (nvme_zalloc_dma(nvme, NVME_IDENTIFY_BUFSIZE, DDI_DMA_READ,
3452 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
3453 		dev_err(nvme->n_dip, CE_WARN,
3454 		    "!nvme_zalloc_dma failed for IDENTIFY");
3455 		ret = nvme_ioctl_error(&ioc->nid_common,
3456 		    NVME_IOCTL_E_NO_DMA_MEM, 0, 0);
3457 		goto fail;
3458 	}
3459 
3460 	if (cmd->nc_dma->nd_ncookie > 2) {
3461 		dev_err(nvme->n_dip, CE_WARN,
3462 		    "!too many DMA cookies for IDENTIFY");
3463 		NVME_BUMP_STAT(nvme, too_many_cookies);
3464 		ret = nvme_ioctl_error(&ioc->nid_common,
3465 		    NVME_IOCTL_E_BAD_PRP, 0, 0);
3466 		goto fail;
3467 	}
3468 
3469 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
3470 	if (cmd->nc_dma->nd_ncookie > 1) {
3471 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
3472 		    &cmd->nc_dma->nd_cookie);
3473 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
3474 		    cmd->nc_dma->nd_cookie.dmac_laddress;
3475 	}
3476 
3477 	if (user)
3478 		cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3479 
3480 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3481 
3482 	if (!nvme_check_cmd_status_ioctl(cmd, &ioc->nid_common)) {
3483 		dev_err(nvme->n_dip, CE_WARN,
3484 		    "!IDENTIFY failed with sct = %x, sc = %x",
3485 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
3486 		ret = B_FALSE;
3487 		goto fail;
3488 	}
3489 
3490 	*buf = kmem_alloc(NVME_IDENTIFY_BUFSIZE, KM_SLEEP);
3491 	bcopy(cmd->nc_dma->nd_memp, *buf, NVME_IDENTIFY_BUFSIZE);
3492 	ret = B_TRUE;
3493 
3494 fail:
3495 	nvme_free_cmd(cmd);
3496 
3497 	return (ret);
3498 }
3499 
3500 static boolean_t
nvme_identify_int(nvme_t * nvme,uint32_t nsid,uint8_t cns,void ** buf)3501 nvme_identify_int(nvme_t *nvme, uint32_t nsid, uint8_t cns, void **buf)
3502 {
3503 	nvme_ioctl_identify_t id;
3504 
3505 	bzero(&id, sizeof (nvme_ioctl_identify_t));
3506 	id.nid_common.nioc_nsid = nsid;
3507 	id.nid_cns = cns;
3508 
3509 	return (nvme_identify(nvme, B_FALSE, &id, buf));
3510 }
3511 
3512 static boolean_t
nvme_get_current_nqueues(nvme_t * nvme,nvme_nqueues_t * nq)3513 nvme_get_current_nqueues(nvme_t *nvme, nvme_nqueues_t *nq)
3514 {
3515 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3516 	nvme_get_features_dw10_t gf_dw10 = { 0 };
3517 	boolean_t ret = B_FALSE;
3518 
3519 	gf_dw10.b.gt_fid = NVME_FEAT_NQUEUES;
3520 
3521 	cmd->nc_sqid = 0;
3522 	cmd->nc_callback = nvme_wakeup_cmd;
3523 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_FEATURES;
3524 	cmd->nc_sqe.sqe_cdw10 = gf_dw10.r;
3525 	cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3526 
3527 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3528 
3529 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
3530 		dev_err(nvme->n_dip, CE_WARN,
3531 		    "!GET FEATURES NQUEUES failed with sct = %x, sc = %x",
3532 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
3533 		goto fail;
3534 	}
3535 
3536 	nq->r = cmd->nc_cqe.cqe_dw0;
3537 	ret = B_TRUE;
3538 
3539 fail:
3540 	nvme_free_cmd(cmd);
3541 	return (ret);
3542 }
3543 
3544 static int
nvme_set_features(nvme_t * nvme,boolean_t user,uint32_t nsid,uint8_t feature,uint32_t val,uint32_t * res)3545 nvme_set_features(nvme_t *nvme, boolean_t user, uint32_t nsid, uint8_t feature,
3546     uint32_t val, uint32_t *res)
3547 {
3548 	_NOTE(ARGUNUSED(nsid));
3549 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3550 	int ret = EINVAL;
3551 
3552 	ASSERT(res != NULL);
3553 
3554 	cmd->nc_sqid = 0;
3555 	cmd->nc_callback = nvme_wakeup_cmd;
3556 	cmd->nc_sqe.sqe_opc = NVME_OPC_SET_FEATURES;
3557 	cmd->nc_sqe.sqe_cdw10 = feature;
3558 	cmd->nc_sqe.sqe_cdw11 = val;
3559 
3560 	if (user)
3561 		cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
3562 
3563 	switch (feature) {
3564 	case NVME_FEAT_WRITE_CACHE:
3565 		if (!nvme->n_write_cache_present)
3566 			goto fail;
3567 		break;
3568 
3569 	case NVME_FEAT_NQUEUES:
3570 		break;
3571 
3572 	default:
3573 		goto fail;
3574 	}
3575 
3576 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3577 
3578 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
3579 		dev_err(nvme->n_dip, CE_WARN,
3580 		    "!SET FEATURES %d failed with sct = %x, sc = %x",
3581 		    feature, cmd->nc_cqe.cqe_sf.sf_sct,
3582 		    cmd->nc_cqe.cqe_sf.sf_sc);
3583 		goto fail;
3584 	}
3585 
3586 	*res = cmd->nc_cqe.cqe_dw0;
3587 
3588 fail:
3589 	nvme_free_cmd(cmd);
3590 	return (ret);
3591 }
3592 
3593 static int
nvme_write_cache_set(nvme_t * nvme,boolean_t enable)3594 nvme_write_cache_set(nvme_t *nvme, boolean_t enable)
3595 {
3596 	nvme_write_cache_t nwc = { 0 };
3597 
3598 	if (enable)
3599 		nwc.b.wc_wce = 1;
3600 
3601 	/*
3602 	 * We've seen some cases where this fails due to us being told we've
3603 	 * specified an invalid namespace when operating against the Xen xcp-ng
3604 	 * qemu NVMe virtual device. As such, we generally ensure that trying to
3605 	 * enable this doesn't lead us to panic. It's not completely clear why
3606 	 * specifying namespace zero here fails, but not when we're setting the
3607 	 * number of queues below.
3608 	 */
3609 	return (nvme_set_features(nvme, B_TRUE, 0, NVME_FEAT_WRITE_CACHE,
3610 	    nwc.r, &nwc.r));
3611 }
3612 
3613 static int
nvme_set_nqueues(nvme_t * nvme)3614 nvme_set_nqueues(nvme_t *nvme)
3615 {
3616 	nvme_nqueues_t nq = { 0 };
3617 	int ret;
3618 
3619 	/*
3620 	 * The default is to allocate one completion queue per vector.
3621 	 */
3622 	if (nvme->n_completion_queues == -1)
3623 		nvme->n_completion_queues = nvme->n_intr_cnt;
3624 
3625 	/*
3626 	 * There is no point in having more completion queues than
3627 	 * interrupt vectors.
3628 	 */
3629 	nvme->n_completion_queues = MIN(nvme->n_completion_queues,
3630 	    nvme->n_intr_cnt);
3631 
3632 	/*
3633 	 * The default is to use one submission queue per completion queue.
3634 	 */
3635 	if (nvme->n_submission_queues == -1)
3636 		nvme->n_submission_queues = nvme->n_completion_queues;
3637 
3638 	/*
3639 	 * There is no point in having more completion queues than
3640 	 * submission queues.
3641 	 */
3642 	nvme->n_completion_queues = MIN(nvme->n_completion_queues,
3643 	    nvme->n_submission_queues);
3644 
3645 	ASSERT(nvme->n_submission_queues > 0);
3646 	ASSERT(nvme->n_completion_queues > 0);
3647 
3648 	nq.b.nq_nsq = nvme->n_submission_queues - 1;
3649 	nq.b.nq_ncq = nvme->n_completion_queues - 1;
3650 
3651 	ret = nvme_set_features(nvme, B_FALSE, 0, NVME_FEAT_NQUEUES, nq.r,
3652 	    &nq.r);
3653 
3654 	if (ret == 0) {
3655 		/*
3656 		 * Never use more than the requested number of queues.
3657 		 */
3658 		nvme->n_submission_queues = MIN(nvme->n_submission_queues,
3659 		    nq.b.nq_nsq + 1);
3660 		nvme->n_completion_queues = MIN(nvme->n_completion_queues,
3661 		    nq.b.nq_ncq + 1);
3662 	}
3663 
3664 	return (ret);
3665 }
3666 
3667 static int
nvme_create_completion_queue(nvme_t * nvme,nvme_cq_t * cq)3668 nvme_create_completion_queue(nvme_t *nvme, nvme_cq_t *cq)
3669 {
3670 	nvme_cmd_t *cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3671 	nvme_create_queue_dw10_t dw10 = { 0 };
3672 	nvme_create_cq_dw11_t c_dw11 = { 0 };
3673 	int ret;
3674 
3675 	dw10.b.q_qid = cq->ncq_id;
3676 	dw10.b.q_qsize = cq->ncq_nentry - 1;
3677 
3678 	c_dw11.b.cq_pc = 1;
3679 	c_dw11.b.cq_ien = 1;
3680 	c_dw11.b.cq_iv = cq->ncq_id % nvme->n_intr_cnt;
3681 
3682 	cmd->nc_sqid = 0;
3683 	cmd->nc_callback = nvme_wakeup_cmd;
3684 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_CQUEUE;
3685 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
3686 	cmd->nc_sqe.sqe_cdw11 = c_dw11.r;
3687 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cq->ncq_dma->nd_cookie.dmac_laddress;
3688 
3689 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3690 
3691 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
3692 		dev_err(nvme->n_dip, CE_WARN,
3693 		    "!CREATE CQUEUE failed with sct = %x, sc = %x",
3694 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
3695 	}
3696 
3697 	nvme_free_cmd(cmd);
3698 
3699 	return (ret);
3700 }
3701 
3702 static int
nvme_create_io_qpair(nvme_t * nvme,nvme_qpair_t * qp,uint16_t idx)3703 nvme_create_io_qpair(nvme_t *nvme, nvme_qpair_t *qp, uint16_t idx)
3704 {
3705 	nvme_cq_t *cq = qp->nq_cq;
3706 	nvme_cmd_t *cmd;
3707 	nvme_create_queue_dw10_t dw10 = { 0 };
3708 	nvme_create_sq_dw11_t s_dw11 = { 0 };
3709 	int ret;
3710 
3711 	/*
3712 	 * It is possible to have more qpairs than completion queues,
3713 	 * and when the idx > ncq_id, that completion queue is shared
3714 	 * and has already been created.
3715 	 */
3716 	if (idx <= cq->ncq_id &&
3717 	    nvme_create_completion_queue(nvme, cq) != DDI_SUCCESS)
3718 		return (DDI_FAILURE);
3719 
3720 	dw10.b.q_qid = idx;
3721 	dw10.b.q_qsize = qp->nq_nentry - 1;
3722 
3723 	s_dw11.b.sq_pc = 1;
3724 	s_dw11.b.sq_cqid = cq->ncq_id;
3725 
3726 	cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
3727 	cmd->nc_sqid = 0;
3728 	cmd->nc_callback = nvme_wakeup_cmd;
3729 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_SQUEUE;
3730 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
3731 	cmd->nc_sqe.sqe_cdw11 = s_dw11.r;
3732 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_sqdma->nd_cookie.dmac_laddress;
3733 
3734 	nvme_admin_cmd(cmd, nvme_admin_cmd_timeout);
3735 
3736 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
3737 		dev_err(nvme->n_dip, CE_WARN,
3738 		    "!CREATE SQUEUE failed with sct = %x, sc = %x",
3739 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
3740 	}
3741 
3742 	nvme_free_cmd(cmd);
3743 
3744 	return (ret);
3745 }
3746 
3747 static boolean_t
nvme_reset(nvme_t * nvme,boolean_t quiesce)3748 nvme_reset(nvme_t *nvme, boolean_t quiesce)
3749 {
3750 	nvme_reg_csts_t csts;
3751 	int i;
3752 
3753 	/*
3754 	 * If the device is gone, do not try to interact with it.  We define
3755 	 * that resetting such a device is impossible, and always fails.
3756 	 */
3757 	if (nvme_ctrl_is_gone(nvme)) {
3758 		return (B_FALSE);
3759 	}
3760 
3761 	nvme_put32(nvme, NVME_REG_CC, 0);
3762 
3763 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
3764 	if (csts.b.csts_rdy == 1) {
3765 		nvme_put32(nvme, NVME_REG_CC, 0);
3766 
3767 		/*
3768 		 * The timeout value is from the Controller Capabilities
3769 		 * register (CAP.TO, section 3.1.1). This is the worst case
3770 		 * time to wait for CSTS.RDY to transition from 1 to 0 after
3771 		 * CC.EN transitions from 1 to 0.
3772 		 *
3773 		 * The timeout units are in 500 ms units, and we are delaying
3774 		 * in 50ms chunks, hence counting to n_timeout * 10.
3775 		 */
3776 		for (i = 0; i < nvme->n_timeout * 10; i++) {
3777 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
3778 			if (csts.b.csts_rdy == 0)
3779 				break;
3780 
3781 			/*
3782 			 * Quiescing drivers should not use locks or timeouts,
3783 			 * so if this is the quiesce path, use a quiesce-safe
3784 			 * delay.
3785 			 */
3786 			if (quiesce) {
3787 				drv_usecwait(50000);
3788 			} else {
3789 				delay(drv_usectohz(50000));
3790 			}
3791 		}
3792 	}
3793 
3794 	nvme_put32(nvme, NVME_REG_AQA, 0);
3795 	nvme_put32(nvme, NVME_REG_ASQ, 0);
3796 	nvme_put32(nvme, NVME_REG_ACQ, 0);
3797 
3798 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
3799 	return (csts.b.csts_rdy == 0 ? B_TRUE : B_FALSE);
3800 }
3801 
3802 static void
nvme_shutdown(nvme_t * nvme,boolean_t quiesce)3803 nvme_shutdown(nvme_t *nvme, boolean_t quiesce)
3804 {
3805 	nvme_reg_cc_t cc;
3806 	nvme_reg_csts_t csts;
3807 	int i;
3808 
3809 	/*
3810 	 * Do not try to interact with the device if it is gone.  Since it is
3811 	 * not there, in some sense it must already be shut down anyway.
3812 	 */
3813 	if (nvme_ctrl_is_gone(nvme)) {
3814 		return;
3815 	}
3816 
3817 	cc.r = nvme_get32(nvme, NVME_REG_CC);
3818 	cc.b.cc_shn = NVME_CC_SHN_NORMAL;
3819 	nvme_put32(nvme, NVME_REG_CC, cc.r);
3820 
3821 	for (i = 0; i < 10; i++) {
3822 		csts.r = nvme_get32(nvme, NVME_REG_CSTS);
3823 		if (csts.b.csts_shst == NVME_CSTS_SHN_COMPLETE)
3824 			break;
3825 
3826 		if (quiesce) {
3827 			drv_usecwait(100000);
3828 		} else {
3829 			delay(drv_usectohz(100000));
3830 		}
3831 	}
3832 }
3833 
3834 /*
3835  * Return length of string without trailing spaces.
3836  */
3837 static size_t
nvme_strlen(const char * str,size_t len)3838 nvme_strlen(const char *str, size_t len)
3839 {
3840 	if (len <= 0)
3841 		return (0);
3842 
3843 	while (str[--len] == ' ')
3844 		;
3845 
3846 	return (++len);
3847 }
3848 
3849 static void
nvme_config_min_block_size(nvme_t * nvme,char * model,char * val)3850 nvme_config_min_block_size(nvme_t *nvme, char *model, char *val)
3851 {
3852 	ulong_t bsize = 0;
3853 	char *msg = "";
3854 
3855 	if (ddi_strtoul(val, NULL, 0, &bsize) != 0)
3856 		goto err;
3857 
3858 	if (!ISP2(bsize)) {
3859 		msg = ": not a power of 2";
3860 		goto err;
3861 	}
3862 
3863 	if (bsize < NVME_DEFAULT_MIN_BLOCK_SIZE) {
3864 		msg = ": too low";
3865 		goto err;
3866 	}
3867 
3868 	nvme->n_min_block_size = bsize;
3869 	return;
3870 
3871 err:
3872 	dev_err(nvme->n_dip, CE_WARN,
3873 	    "!nvme-config-list: ignoring invalid min-phys-block-size '%s' "
3874 	    "for model '%s'%s", val, model, msg);
3875 
3876 	nvme->n_min_block_size = NVME_DEFAULT_MIN_BLOCK_SIZE;
3877 }
3878 
3879 static void
nvme_config_boolean(nvme_t * nvme,char * model,char * name,char * val,boolean_t * b)3880 nvme_config_boolean(nvme_t *nvme, char *model, char *name, char *val,
3881     boolean_t *b)
3882 {
3883 	if (strcmp(val, "on") == 0 ||
3884 	    strcmp(val, "true") == 0)
3885 		*b = B_TRUE;
3886 	else if (strcmp(val, "off") == 0 ||
3887 	    strcmp(val, "false") == 0)
3888 		*b = B_FALSE;
3889 	else
3890 		dev_err(nvme->n_dip, CE_WARN,
3891 		    "!nvme-config-list: invalid value for %s '%s'"
3892 		    " for model '%s', ignoring", name, val, model);
3893 }
3894 
3895 static void
nvme_config_list(nvme_t * nvme)3896 nvme_config_list(nvme_t *nvme)
3897 {
3898 	char	**config_list;
3899 	uint_t	nelem;
3900 	int	rv;
3901 
3902 	/*
3903 	 * We're following the pattern of 'sd-config-list' here, but extend it.
3904 	 * Instead of two we have three separate strings for "model", "fwrev",
3905 	 * and "name-value-list".
3906 	 */
3907 	rv = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, nvme->n_dip,
3908 	    DDI_PROP_DONTPASS, "nvme-config-list", &config_list, &nelem);
3909 
3910 	if (rv != DDI_PROP_SUCCESS) {
3911 		if (rv == DDI_PROP_CANNOT_DECODE) {
3912 			dev_err(nvme->n_dip, CE_WARN,
3913 			    "!nvme-config-list: cannot be decoded");
3914 		}
3915 
3916 		return;
3917 	}
3918 
3919 	if ((nelem % 3) != 0) {
3920 		dev_err(nvme->n_dip, CE_WARN, "!nvme-config-list: must be "
3921 		    "triplets of <model>/<fwrev>/<name-value-list> strings ");
3922 		goto out;
3923 	}
3924 
3925 	for (uint_t i = 0; i < nelem; i += 3) {
3926 		char	*model = config_list[i];
3927 		char	*fwrev = config_list[i + 1];
3928 		char	*nvp, *save_nv;
3929 		size_t	id_model_len, id_fwrev_len;
3930 
3931 		id_model_len = nvme_strlen(nvme->n_idctl->id_model,
3932 		    sizeof (nvme->n_idctl->id_model));
3933 
3934 		if (strlen(model) != id_model_len)
3935 			continue;
3936 
3937 		if (strncmp(model, nvme->n_idctl->id_model, id_model_len) != 0)
3938 			continue;
3939 
3940 		id_fwrev_len = nvme_strlen(nvme->n_idctl->id_fwrev,
3941 		    sizeof (nvme->n_idctl->id_fwrev));
3942 
3943 		if (strlen(fwrev) != 0) {
3944 			boolean_t match = B_FALSE;
3945 			char *fwr, *last_fw;
3946 
3947 			for (fwr = strtok_r(fwrev, ",", &last_fw);
3948 			    fwr != NULL;
3949 			    fwr = strtok_r(NULL, ",", &last_fw)) {
3950 				if (strlen(fwr) != id_fwrev_len)
3951 					continue;
3952 
3953 				if (strncmp(fwr, nvme->n_idctl->id_fwrev,
3954 				    id_fwrev_len) == 0)
3955 					match = B_TRUE;
3956 			}
3957 
3958 			if (!match)
3959 				continue;
3960 		}
3961 
3962 		/*
3963 		 * We should now have a comma-separated list of name:value
3964 		 * pairs.
3965 		 */
3966 		for (nvp = strtok_r(config_list[i + 2], ",", &save_nv);
3967 		    nvp != NULL; nvp = strtok_r(NULL, ",", &save_nv)) {
3968 			char	*name = nvp;
3969 			char	*val = strchr(nvp, ':');
3970 
3971 			if (val == NULL || name == val) {
3972 				dev_err(nvme->n_dip, CE_WARN,
3973 				    "!nvme-config-list: <name-value-list> "
3974 				    "for model '%s' is malformed", model);
3975 				goto out;
3976 			}
3977 
3978 			/*
3979 			 * Null-terminate 'name', move 'val' past ':' sep.
3980 			 */
3981 			*val++ = '\0';
3982 
3983 			/*
3984 			 * Process the name:val pairs that we know about.
3985 			 */
3986 			if (strcmp(name, "ignore-unknown-vendor-status") == 0) {
3987 				nvme_config_boolean(nvme, model, name, val,
3988 				    &nvme->n_ignore_unknown_vendor_status);
3989 			} else if (strcmp(name, "min-phys-block-size") == 0) {
3990 				nvme_config_min_block_size(nvme, model, val);
3991 			} else if (strcmp(name, "volatile-write-cache") == 0) {
3992 				nvme_config_boolean(nvme, model, name, val,
3993 				    &nvme->n_write_cache_enabled);
3994 			} else {
3995 				/*
3996 				 * Unknown 'name'.
3997 				 */
3998 				dev_err(nvme->n_dip, CE_WARN,
3999 				    "!nvme-config-list: unknown config '%s' "
4000 				    "for model '%s', ignoring", name, model);
4001 			}
4002 		}
4003 	}
4004 
4005 out:
4006 	ddi_prop_free(config_list);
4007 }
4008 
4009 static void
nvme_prepare_devid(nvme_t * nvme,uint32_t nsid)4010 nvme_prepare_devid(nvme_t *nvme, uint32_t nsid)
4011 {
4012 	/*
4013 	 * Section 7.7 of the spec describes how to get a unique ID for
4014 	 * the controller: the vendor ID, the model name and the serial
4015 	 * number shall be unique when combined.
4016 	 *
4017 	 * If a namespace has no EUI64 we use the above and add the hex
4018 	 * namespace ID to get a unique ID for the namespace.
4019 	 */
4020 	char model[sizeof (nvme->n_idctl->id_model) + 1];
4021 	char serial[sizeof (nvme->n_idctl->id_serial) + 1];
4022 
4023 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
4024 	bcopy(nvme->n_idctl->id_serial, serial,
4025 	    sizeof (nvme->n_idctl->id_serial));
4026 
4027 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
4028 	serial[sizeof (nvme->n_idctl->id_serial)] = '\0';
4029 
4030 	nvme_nsid2ns(nvme, nsid)->ns_devid = kmem_asprintf("%4X-%s-%s-%X",
4031 	    nvme->n_idctl->id_vid, model, serial, nsid);
4032 }
4033 
4034 static nvme_identify_nsid_list_t *
nvme_update_nsid_list(nvme_t * nvme,int cns)4035 nvme_update_nsid_list(nvme_t *nvme, int cns)
4036 {
4037 	nvme_identify_nsid_list_t *nslist;
4038 
4039 	/*
4040 	 * We currently don't handle cases where there are more than
4041 	 * 1024 active namespaces, requiring several IDENTIFY commands.
4042 	 */
4043 	if (nvme_identify_int(nvme, 0, cns, (void **)&nslist))
4044 		return (nslist);
4045 
4046 	return (NULL);
4047 }
4048 
4049 nvme_namespace_t *
nvme_nsid2ns(nvme_t * nvme,uint32_t nsid)4050 nvme_nsid2ns(nvme_t *nvme, uint32_t nsid)
4051 {
4052 	ASSERT3U(nsid, !=, 0);
4053 	ASSERT3U(nsid, <=, nvme->n_namespace_count);
4054 	return (&nvme->n_ns[nsid - 1]);
4055 }
4056 
4057 static boolean_t
nvme_allocated_ns(nvme_namespace_t * ns)4058 nvme_allocated_ns(nvme_namespace_t *ns)
4059 {
4060 	nvme_t *nvme = ns->ns_nvme;
4061 	uint32_t i;
4062 
4063 	ASSERT(nvme_mgmt_lock_held(nvme));
4064 
4065 	/*
4066 	 * If supported, update the list of allocated namespace IDs.
4067 	 */
4068 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 2) &&
4069 	    nvme->n_idctl->id_oacs.oa_nsmgmt != 0) {
4070 		nvme_identify_nsid_list_t *nslist = nvme_update_nsid_list(nvme,
4071 		    NVME_IDENTIFY_NSID_ALLOC_LIST);
4072 		boolean_t found = B_FALSE;
4073 
4074 		/*
4075 		 * When namespace management is supported, this really shouldn't
4076 		 * be NULL. Treat all namespaces as allocated if it is.
4077 		 */
4078 		if (nslist == NULL)
4079 			return (B_TRUE);
4080 
4081 		for (i = 0; i < ARRAY_SIZE(nslist->nl_nsid); i++) {
4082 			if (ns->ns_id == 0)
4083 				break;
4084 
4085 			if (ns->ns_id == nslist->nl_nsid[i])
4086 				found = B_TRUE;
4087 		}
4088 
4089 		kmem_free(nslist, NVME_IDENTIFY_BUFSIZE);
4090 		return (found);
4091 	} else {
4092 		/*
4093 		 * If namespace management isn't supported, report all
4094 		 * namespaces as allocated.
4095 		 */
4096 		return (B_TRUE);
4097 	}
4098 }
4099 
4100 static boolean_t
nvme_active_ns(nvme_namespace_t * ns)4101 nvme_active_ns(nvme_namespace_t *ns)
4102 {
4103 	nvme_t *nvme = ns->ns_nvme;
4104 	uint64_t *ptr;
4105 	uint32_t i;
4106 
4107 	ASSERT(nvme_mgmt_lock_held(nvme));
4108 
4109 	/*
4110 	 * If supported, update the list of active namespace IDs.
4111 	 */
4112 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1)) {
4113 		nvme_identify_nsid_list_t *nslist = nvme_update_nsid_list(nvme,
4114 		    NVME_IDENTIFY_NSID_LIST);
4115 		boolean_t found = B_FALSE;
4116 
4117 		/*
4118 		 * When namespace management is supported, this really shouldn't
4119 		 * be NULL. Treat all namespaces as allocated if it is.
4120 		 */
4121 		if (nslist == NULL)
4122 			return (B_TRUE);
4123 
4124 		for (i = 0; i < ARRAY_SIZE(nslist->nl_nsid); i++) {
4125 			if (ns->ns_id == 0)
4126 				break;
4127 
4128 			if (ns->ns_id == nslist->nl_nsid[i])
4129 				found = B_TRUE;
4130 		}
4131 
4132 		kmem_free(nslist, NVME_IDENTIFY_BUFSIZE);
4133 		return (found);
4134 	}
4135 
4136 	/*
4137 	 * Workaround for revision 1.0:
4138 	 * Check whether the IDENTIFY NAMESPACE data is zero-filled.
4139 	 */
4140 	for (ptr = (uint64_t *)ns->ns_idns;
4141 	    ptr != (uint64_t *)(ns->ns_idns + 1);
4142 	    ptr++) {
4143 		if (*ptr != 0) {
4144 			return (B_TRUE);
4145 		}
4146 	}
4147 
4148 	return (B_FALSE);
4149 }
4150 
4151 static int
nvme_init_ns(nvme_t * nvme,uint32_t nsid)4152 nvme_init_ns(nvme_t *nvme, uint32_t nsid)
4153 {
4154 	nvme_namespace_t *ns = nvme_nsid2ns(nvme, nsid);
4155 	nvme_identify_nsid_t *idns;
4156 	nvme_ns_state_t orig_state;
4157 
4158 	ns->ns_nvme = nvme;
4159 
4160 	ASSERT(nvme_mgmt_lock_held(nvme));
4161 
4162 	/*
4163 	 * Because we might rescan a namespace and this will fail after boot
4164 	 * that'd leave us in a bad spot. We need to do something about this
4165 	 * longer term, but it's not clear how exactly we would recover right
4166 	 * now.
4167 	 */
4168 	if (!nvme_identify_int(nvme, nsid, NVME_IDENTIFY_NSID,
4169 	    (void **)&idns)) {
4170 		dev_err(nvme->n_dip, CE_WARN,
4171 		    "!failed to identify namespace %d", nsid);
4172 		return (DDI_FAILURE);
4173 	}
4174 
4175 	if (ns->ns_idns != NULL)
4176 		kmem_free(ns->ns_idns, sizeof (nvme_identify_nsid_t));
4177 
4178 	ns->ns_idns = idns;
4179 	ns->ns_id = nsid;
4180 
4181 	/*
4182 	 * Save the current state so we can tell what changed. Look at the
4183 	 * current state of the device. We will flag active devices that should
4184 	 * be ignored after this.
4185 	 */
4186 	orig_state = ns->ns_state;
4187 	if (nvme_active_ns(ns)) {
4188 		/*
4189 		 * If the device previously had blkdev active, then that is its
4190 		 * current state. Otherwise, we consider this an upgrade and
4191 		 * just set it to not ignored.
4192 		 */
4193 		if (orig_state == NVME_NS_STATE_ATTACHED) {
4194 			ns->ns_state = NVME_NS_STATE_ATTACHED;
4195 		} else {
4196 			ns->ns_state = NVME_NS_STATE_NOT_IGNORED;
4197 		}
4198 	} else if (nvme_allocated_ns(ns)) {
4199 		ns->ns_state = NVME_NS_STATE_ALLOCATED;
4200 	} else {
4201 		ns->ns_state = NVME_NS_STATE_UNALLOCATED;
4202 	}
4203 
4204 	ns->ns_block_count = idns->id_nsize;
4205 	ns->ns_block_size =
4206 	    1 << idns->id_lbaf[idns->id_flbas.lba_format].lbaf_lbads;
4207 	ns->ns_best_block_size = ns->ns_block_size;
4208 
4209 	/*
4210 	 * Get the EUI64 if present.
4211 	 */
4212 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1))
4213 		bcopy(idns->id_eui64, ns->ns_eui64, sizeof (ns->ns_eui64));
4214 
4215 	/*
4216 	 * Get the NGUID if present.
4217 	 */
4218 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 2))
4219 		bcopy(idns->id_nguid, ns->ns_nguid, sizeof (ns->ns_nguid));
4220 
4221 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
4222 	if (*(uint64_t *)ns->ns_eui64 == 0)
4223 		nvme_prepare_devid(nvme, ns->ns_id);
4224 
4225 	(void) snprintf(ns->ns_name, sizeof (ns->ns_name), "%u", ns->ns_id);
4226 
4227 	/*
4228 	 * Find the LBA format with no metadata and the best relative
4229 	 * performance. A value of 3 means "degraded", 0 is best.
4230 	 */
4231 	for (uint32_t j = 0, last_rp = 3; j <= idns->id_nlbaf; j++) {
4232 		if (idns->id_lbaf[j].lbaf_lbads == 0)
4233 			break;
4234 		if (idns->id_lbaf[j].lbaf_ms != 0)
4235 			continue;
4236 		if (idns->id_lbaf[j].lbaf_rp >= last_rp)
4237 			continue;
4238 		last_rp = idns->id_lbaf[j].lbaf_rp;
4239 		ns->ns_best_block_size =
4240 		    1 << idns->id_lbaf[j].lbaf_lbads;
4241 	}
4242 
4243 	if (ns->ns_best_block_size < nvme->n_min_block_size)
4244 		ns->ns_best_block_size = nvme->n_min_block_size;
4245 
4246 	/*
4247 	 * We currently don't support namespaces that are inactive, or use
4248 	 * either:
4249 	 * - protection information
4250 	 * - illegal block size (< 512)
4251 	 */
4252 	if (ns->ns_state >= NVME_NS_STATE_NOT_IGNORED) {
4253 		if (idns->id_dps.dp_pinfo) {
4254 			dev_err(nvme->n_dip, CE_WARN,
4255 			    "!ignoring namespace %d, unsupported feature: "
4256 			    "pinfo = %d", nsid, idns->id_dps.dp_pinfo);
4257 			ns->ns_state = NVME_NS_STATE_ACTIVE;
4258 		}
4259 
4260 		if (ns->ns_block_size < 512) {
4261 			dev_err(nvme->n_dip, CE_WARN,
4262 			    "!ignoring namespace %d, unsupported block size "
4263 			    "%"PRIu64, nsid, (uint64_t)ns->ns_block_size);
4264 			ns->ns_state = NVME_NS_STATE_ACTIVE;
4265 		}
4266 	}
4267 
4268 	/*
4269 	 * If we were previously in a state where blkdev was active and suddenly
4270 	 * we think it should not be because ignore is set, then something has
4271 	 * gone behind our backs and this is not going to be recoverable.
4272 	 */
4273 	if (orig_state == NVME_NS_STATE_ATTACHED &&
4274 	    ns->ns_state != NVME_NS_STATE_ATTACHED) {
4275 		dev_err(nvme->n_dip, CE_PANIC, "namespace %u state "
4276 		    "unexpectedly changed and removed blkdev support!", nsid);
4277 	}
4278 
4279 	/*
4280 	 * Keep a count of namespaces which are attachable.
4281 	 * See comments in nvme_bd_driveinfo() to understand its effect.
4282 	 */
4283 	if (orig_state > NVME_NS_STATE_ACTIVE) {
4284 		/*
4285 		 * Wasn't attachable previously, but now needs to be.
4286 		 * Discount it.
4287 		 */
4288 		if (ns->ns_state < NVME_NS_STATE_NOT_IGNORED)
4289 			nvme->n_namespaces_attachable--;
4290 	} else if (ns->ns_state >= NVME_NS_STATE_NOT_IGNORED) {
4291 		/*
4292 		 * Previously ignored, but now not. Count it.
4293 		 */
4294 		nvme->n_namespaces_attachable++;
4295 	}
4296 
4297 	return (DDI_SUCCESS);
4298 }
4299 
4300 static boolean_t
nvme_bd_attach_ns(nvme_t * nvme,nvme_ioctl_common_t * com)4301 nvme_bd_attach_ns(nvme_t *nvme, nvme_ioctl_common_t *com)
4302 {
4303 	nvme_namespace_t *ns = nvme_nsid2ns(nvme, com->nioc_nsid);
4304 	int ret;
4305 
4306 	ASSERT(nvme_mgmt_lock_held(nvme));
4307 
4308 	if (!nvme_ns_state_check(ns, com, nvme_bd_attach_states)) {
4309 		return (B_FALSE);
4310 	}
4311 
4312 	if (ns->ns_bd_hdl == NULL) {
4313 		bd_ops_t ops = nvme_bd_ops;
4314 
4315 		if (!nvme->n_idctl->id_oncs.on_dset_mgmt)
4316 			ops.o_free_space = NULL;
4317 
4318 		ns->ns_bd_hdl = bd_alloc_handle(ns, &ops, &nvme->n_prp_dma_attr,
4319 		    KM_SLEEP);
4320 
4321 		if (ns->ns_bd_hdl == NULL) {
4322 			dev_err(nvme->n_dip, CE_WARN, "!Failed to get blkdev "
4323 			    "handle for namespace id %u", com->nioc_nsid);
4324 			return (nvme_ioctl_error(com,
4325 			    NVME_IOCTL_E_BLKDEV_ATTACH, 0, 0));
4326 		}
4327 	}
4328 
4329 	nvme_mgmt_bd_start(nvme);
4330 	ret = bd_attach_handle(nvme->n_dip, ns->ns_bd_hdl);
4331 	nvme_mgmt_bd_end(nvme);
4332 	if (ret != DDI_SUCCESS) {
4333 		return (nvme_ioctl_error(com, NVME_IOCTL_E_BLKDEV_ATTACH,
4334 		    0, 0));
4335 	}
4336 
4337 	ns->ns_state = NVME_NS_STATE_ATTACHED;
4338 
4339 	return (B_TRUE);
4340 }
4341 
4342 static boolean_t
nvme_bd_detach_ns(nvme_t * nvme,nvme_ioctl_common_t * com)4343 nvme_bd_detach_ns(nvme_t *nvme, nvme_ioctl_common_t *com)
4344 {
4345 	nvme_namespace_t *ns = nvme_nsid2ns(nvme, com->nioc_nsid);
4346 	int ret;
4347 
4348 	ASSERT(nvme_mgmt_lock_held(nvme));
4349 
4350 	if (!nvme_ns_state_check(ns, com, nvme_bd_detach_states)) {
4351 		return (B_FALSE);
4352 	}
4353 
4354 	nvme_mgmt_bd_start(nvme);
4355 	ASSERT3P(ns->ns_bd_hdl, !=, NULL);
4356 	ret = bd_detach_handle(ns->ns_bd_hdl);
4357 	nvme_mgmt_bd_end(nvme);
4358 
4359 	if (ret != DDI_SUCCESS) {
4360 		return (nvme_ioctl_error(com, NVME_IOCTL_E_BLKDEV_DETACH, 0,
4361 		    0));
4362 	}
4363 
4364 	ns->ns_state = NVME_NS_STATE_NOT_IGNORED;
4365 	return (B_TRUE);
4366 
4367 }
4368 
4369 /*
4370  * Rescan the namespace information associated with the namespaces indicated by
4371  * ioc. They should not be attached to blkdev right now.
4372  */
4373 static void
nvme_rescan_ns(nvme_t * nvme,uint32_t nsid)4374 nvme_rescan_ns(nvme_t *nvme, uint32_t nsid)
4375 {
4376 	ASSERT(nvme_mgmt_lock_held(nvme));
4377 	ASSERT3U(nsid, !=, 0);
4378 
4379 	if (nsid != NVME_NSID_BCAST) {
4380 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, nsid);
4381 
4382 		ASSERT3U(ns->ns_state, <, NVME_NS_STATE_ATTACHED);
4383 		(void) nvme_init_ns(nvme, nsid);
4384 		return;
4385 	}
4386 
4387 	for (uint32_t i = 1; i <= nvme->n_namespace_count; i++) {
4388 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, i);
4389 
4390 		ASSERT3U(ns->ns_state, <, NVME_NS_STATE_ATTACHED);
4391 		(void) nvme_init_ns(nvme, i);
4392 	}
4393 }
4394 
4395 typedef struct nvme_quirk_table {
4396 	uint16_t nq_vendor_id;
4397 	uint16_t nq_device_id;
4398 	nvme_quirk_t nq_quirks;
4399 } nvme_quirk_table_t;
4400 
4401 static const nvme_quirk_table_t nvme_quirks[] = {
4402 	{ 0x1987, 0x5018, NVME_QUIRK_START_CID },	/* Phison E18 */
4403 };
4404 
4405 static void
nvme_detect_quirks(nvme_t * nvme)4406 nvme_detect_quirks(nvme_t *nvme)
4407 {
4408 	for (uint_t i = 0; i < ARRAY_SIZE(nvme_quirks); i++) {
4409 		const nvme_quirk_table_t *nqt = &nvme_quirks[i];
4410 
4411 		if (nqt->nq_vendor_id == nvme->n_vendor_id &&
4412 		    nqt->nq_device_id == nvme->n_device_id) {
4413 			nvme->n_quirks = nqt->nq_quirks;
4414 			return;
4415 		}
4416 	}
4417 }
4418 
4419 /*
4420  * Indicate to the controller that we support various behaviors. These are
4421  * things the controller needs to be proactively told. We only will do this if
4422  * the controller indicates support for something that we care about, otherwise
4423  * there is no need to talk to the controller and there is no separate way to
4424  * know that this feature is otherwise supported. Support for most features is
4425  * indicated by setting it to 1.
4426  *
4427  * The current behaviors we enable are:
4428  *
4429  *  - Extended Telemetry Data Area 4: This enables additional telemetry to be
4430  *    possibly generated and depends on the DA4S bit in the log page attributes.
4431  */
4432 static void
nvme_enable_host_behavior(nvme_t * nvme)4433 nvme_enable_host_behavior(nvme_t *nvme)
4434 {
4435 	nvme_host_behavior_t *hb;
4436 	nvme_ioc_cmd_args_t args = { NULL };
4437 	nvme_sqe_t sqe = {
4438 		.sqe_opc = NVME_OPC_SET_FEATURES,
4439 		.sqe_cdw10 = NVME_FEAT_HOST_BEHAVE,
4440 		.sqe_nsid = 0
4441 	};
4442 	nvme_ioctl_common_t err;
4443 
4444 	if (nvme->n_idctl->id_lpa.lp_da4s == 0)
4445 		return;
4446 
4447 	hb = kmem_zalloc(sizeof (nvme_host_behavior_t), KM_SLEEP);
4448 	hb->nhb_etdas = 1;
4449 
4450 	args.ica_sqe = &sqe;
4451 	args.ica_data = hb;
4452 	args.ica_data_len = sizeof (nvme_host_behavior_t);
4453 	args.ica_dma_flags = DDI_DMA_WRITE;
4454 	args.ica_copy_flags = FKIOCTL;
4455 	args.ica_timeout = nvme_admin_cmd_timeout;
4456 
4457 	if (!nvme_ioc_cmd(nvme, &err, &args)) {
4458 		dev_err(nvme->n_dip, CE_WARN, "failed to enable host behavior "
4459 		    "feature: 0x%x/0x%x/0x%x", err.nioc_drv_err,
4460 		    err.nioc_ctrl_sct, err.nioc_ctrl_sc);
4461 	}
4462 
4463 	kmem_free(hb, sizeof (nvme_host_behavior_t));
4464 }
4465 
4466 static int
nvme_init(nvme_t * nvme)4467 nvme_init(nvme_t *nvme)
4468 {
4469 	nvme_reg_cc_t cc = { 0 };
4470 	nvme_reg_aqa_t aqa = { 0 };
4471 	nvme_reg_asq_t asq = { 0 };
4472 	nvme_reg_acq_t acq = { 0 };
4473 	nvme_reg_cap_t cap;
4474 	nvme_reg_vs_t vs;
4475 	nvme_reg_csts_t csts;
4476 	nvme_nqueues_t nq;
4477 	int i = 0;
4478 	uint_t tq_threads;
4479 	char model[sizeof (nvme->n_idctl->id_model) + 1];
4480 	char *vendor, *product;
4481 	uint32_t nsid;
4482 
4483 	/* Check controller version */
4484 	vs.r = nvme_get32(nvme, NVME_REG_VS);
4485 	nvme->n_version.v_major = vs.b.vs_mjr;
4486 	nvme->n_version.v_minor = vs.b.vs_mnr;
4487 	dev_err(nvme->n_dip, CE_CONT, "?NVMe spec version %d.%d\n",
4488 	    nvme->n_version.v_major, nvme->n_version.v_minor);
4489 
4490 	if (nvme->n_version.v_major > nvme_version_major) {
4491 		dev_err(nvme->n_dip, CE_WARN, "!no support for version > %d.x",
4492 		    nvme_version_major);
4493 		if (nvme->n_strict_version)
4494 			goto fail;
4495 	}
4496 
4497 	/* retrieve controller configuration */
4498 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
4499 
4500 	if ((cap.b.cap_css & NVME_CAP_CSS_NVM) == 0) {
4501 		dev_err(nvme->n_dip, CE_WARN,
4502 		    "!NVM command set not supported by hardware");
4503 		goto fail;
4504 	}
4505 
4506 	nvme->n_nssr_supported = cap.b.cap_nssrs;
4507 	nvme->n_doorbell_stride = 4 << cap.b.cap_dstrd;
4508 	nvme->n_timeout = cap.b.cap_to;
4509 	nvme->n_arbitration_mechanisms = cap.b.cap_ams;
4510 	nvme->n_cont_queues_reqd = cap.b.cap_cqr;
4511 	nvme->n_max_queue_entries = cap.b.cap_mqes + 1;
4512 
4513 	/*
4514 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to specify
4515 	 * the base page size of 4k (1<<12), so add 12 here to get the real
4516 	 * page size value.
4517 	 */
4518 	nvme->n_pageshift = MIN(MAX(cap.b.cap_mpsmin + 12, PAGESHIFT),
4519 	    cap.b.cap_mpsmax + 12);
4520 	nvme->n_pagesize = 1UL << (nvme->n_pageshift);
4521 
4522 	/*
4523 	 * Set up Queue DMA to transfer at least 1 page-aligned page at a time.
4524 	 */
4525 	nvme->n_queue_dma_attr.dma_attr_align = nvme->n_pagesize;
4526 	nvme->n_queue_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
4527 
4528 	/*
4529 	 * Set up PRP DMA to transfer 1 page-aligned page at a time.
4530 	 * Maxxfer may be increased after we identified the controller limits.
4531 	 */
4532 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_pagesize;
4533 	nvme->n_prp_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
4534 	nvme->n_prp_dma_attr.dma_attr_align = nvme->n_pagesize;
4535 	nvme->n_prp_dma_attr.dma_attr_seg = nvme->n_pagesize - 1;
4536 
4537 	/*
4538 	 * Reset controller if it's still in ready state.
4539 	 */
4540 	if (nvme_reset(nvme, B_FALSE) == B_FALSE) {
4541 		dev_err(nvme->n_dip, CE_WARN, "!unable to reset controller");
4542 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
4543 		nvme->n_dead = B_TRUE;
4544 		goto fail;
4545 	}
4546 
4547 	/*
4548 	 * Create the cq array with one completion queue to be assigned
4549 	 * to the admin queue pair and a limited number of taskqs (4).
4550 	 */
4551 	if (nvme_create_cq_array(nvme, 1, nvme->n_admin_queue_len, 4) !=
4552 	    DDI_SUCCESS) {
4553 		dev_err(nvme->n_dip, CE_WARN,
4554 		    "!failed to pre-allocate admin completion queue");
4555 		goto fail;
4556 	}
4557 	/*
4558 	 * Create the admin queue pair.
4559 	 */
4560 	if (nvme_alloc_qpair(nvme, nvme->n_admin_queue_len, &nvme->n_adminq, 0)
4561 	    != DDI_SUCCESS) {
4562 		dev_err(nvme->n_dip, CE_WARN,
4563 		    "!unable to allocate admin qpair");
4564 		goto fail;
4565 	}
4566 	nvme->n_ioq = kmem_alloc(sizeof (nvme_qpair_t *), KM_SLEEP);
4567 	nvme->n_ioq[0] = nvme->n_adminq;
4568 
4569 	if (nvme->n_quirks & NVME_QUIRK_START_CID)
4570 		nvme->n_adminq->nq_next_cmd++;
4571 
4572 	nvme->n_progress |= NVME_ADMIN_QUEUE;
4573 
4574 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
4575 	    "admin-queue-len", nvme->n_admin_queue_len);
4576 
4577 	aqa.b.aqa_asqs = aqa.b.aqa_acqs = nvme->n_admin_queue_len - 1;
4578 	asq = nvme->n_adminq->nq_sqdma->nd_cookie.dmac_laddress;
4579 	acq = nvme->n_adminq->nq_cq->ncq_dma->nd_cookie.dmac_laddress;
4580 
4581 	ASSERT((asq & (nvme->n_pagesize - 1)) == 0);
4582 	ASSERT((acq & (nvme->n_pagesize - 1)) == 0);
4583 
4584 	nvme_put32(nvme, NVME_REG_AQA, aqa.r);
4585 	nvme_put64(nvme, NVME_REG_ASQ, asq);
4586 	nvme_put64(nvme, NVME_REG_ACQ, acq);
4587 
4588 	cc.b.cc_ams = 0;	/* use Round-Robin arbitration */
4589 	cc.b.cc_css = 0;	/* use NVM command set */
4590 	cc.b.cc_mps = nvme->n_pageshift - 12;
4591 	cc.b.cc_shn = 0;	/* no shutdown in progress */
4592 	cc.b.cc_en = 1;		/* enable controller */
4593 	cc.b.cc_iosqes = 6;	/* submission queue entry is 2^6 bytes long */
4594 	cc.b.cc_iocqes = 4;	/* completion queue entry is 2^4 bytes long */
4595 
4596 	nvme_put32(nvme, NVME_REG_CC, cc.r);
4597 
4598 	/*
4599 	 * Wait for the controller to become ready.
4600 	 */
4601 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
4602 	if (csts.b.csts_rdy == 0) {
4603 		for (i = 0; i != nvme->n_timeout * 10; i++) {
4604 			delay(drv_usectohz(50000));
4605 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
4606 
4607 			if (csts.b.csts_cfs == 1) {
4608 				dev_err(nvme->n_dip, CE_WARN,
4609 				    "!controller fatal status at init "
4610 				    "(STATUS = 0x%x)", csts.r);
4611 				ddi_fm_service_impact(nvme->n_dip,
4612 				    DDI_SERVICE_LOST);
4613 				nvme->n_dead = B_TRUE;
4614 				goto fail;
4615 			}
4616 
4617 			if (csts.b.csts_rdy == 1)
4618 				break;
4619 		}
4620 	}
4621 
4622 	if (csts.b.csts_rdy == 0) {
4623 		dev_err(nvme->n_dip, CE_WARN, "!controller not ready");
4624 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
4625 		nvme->n_dead = B_TRUE;
4626 		goto fail;
4627 	}
4628 
4629 	/*
4630 	 * Assume an abort command limit of 1. We'll destroy and re-init
4631 	 * that later when we know the true abort command limit.
4632 	 */
4633 	sema_init(&nvme->n_abort_sema, 1, NULL, SEMA_DRIVER, NULL);
4634 
4635 	/*
4636 	 * Set up initial interrupt for admin queue.
4637 	 */
4638 	if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX, 1)
4639 	    != DDI_SUCCESS) &&
4640 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI, 1)
4641 	    != DDI_SUCCESS) &&
4642 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_FIXED, 1)
4643 	    != DDI_SUCCESS)) {
4644 		dev_err(nvme->n_dip, CE_WARN,
4645 		    "!failed to set up initial interrupt");
4646 		goto fail;
4647 	}
4648 
4649 	/*
4650 	 * Initialize the failure status we should use if we mark the controller
4651 	 * dead. Do this ahead of issuing any commands.
4652 	 */
4653 	nvme->n_dead_status = NVME_IOCTL_E_CTRL_DEAD;
4654 
4655 	/*
4656 	 * Identify Controller
4657 	 */
4658 	if (!nvme_identify_int(nvme, 0, NVME_IDENTIFY_CTRL,
4659 	    (void **)&nvme->n_idctl)) {
4660 		dev_err(nvme->n_dip, CE_WARN, "!failed to identify controller");
4661 		goto fail;
4662 	}
4663 
4664 	/*
4665 	 * Process nvme-config-list (if present) in nvme.conf.
4666 	 */
4667 	nvme_config_list(nvme);
4668 
4669 	/*
4670 	 * Get Vendor & Product ID
4671 	 */
4672 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
4673 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
4674 	sata_split_model(model, &vendor, &product);
4675 
4676 	if (vendor == NULL)
4677 		nvme->n_vendor = strdup("NVMe");
4678 	else
4679 		nvme->n_vendor = strdup(vendor);
4680 
4681 	nvme->n_product = strdup(product);
4682 
4683 	/*
4684 	 * Get controller limits.
4685 	 */
4686 	nvme->n_async_event_limit = MAX(NVME_MIN_ASYNC_EVENT_LIMIT,
4687 	    MIN(nvme->n_admin_queue_len / 10,
4688 	    MIN(nvme->n_idctl->id_aerl + 1, nvme->n_async_event_limit)));
4689 
4690 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
4691 	    "async-event-limit", nvme->n_async_event_limit);
4692 
4693 	nvme->n_abort_command_limit = nvme->n_idctl->id_acl + 1;
4694 
4695 	/*
4696 	 * Reinitialize the semaphore with the true abort command limit
4697 	 * supported by the hardware. It's not necessary to disable interrupts
4698 	 * as only command aborts use the semaphore, and no commands are
4699 	 * executed or aborted while we're here.
4700 	 */
4701 	sema_destroy(&nvme->n_abort_sema);
4702 	sema_init(&nvme->n_abort_sema, nvme->n_abort_command_limit - 1, NULL,
4703 	    SEMA_DRIVER, NULL);
4704 
4705 	nvme->n_progress |= NVME_CTRL_LIMITS;
4706 
4707 	if (nvme->n_idctl->id_mdts == 0)
4708 		nvme->n_max_data_transfer_size = nvme->n_pagesize * 65536;
4709 	else
4710 		nvme->n_max_data_transfer_size =
4711 		    1ull << (nvme->n_pageshift + nvme->n_idctl->id_mdts);
4712 
4713 	nvme->n_error_log_len = nvme->n_idctl->id_elpe + 1;
4714 
4715 	/*
4716 	 * Limit n_max_data_transfer_size to what we can handle in one PRP.
4717 	 * Chained PRPs are currently unsupported.
4718 	 *
4719 	 * This is a no-op on hardware which doesn't support a transfer size
4720 	 * big enough to require chained PRPs.
4721 	 */
4722 	nvme->n_max_data_transfer_size = MIN(nvme->n_max_data_transfer_size,
4723 	    (nvme->n_pagesize / sizeof (uint64_t) * nvme->n_pagesize));
4724 
4725 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_max_data_transfer_size;
4726 
4727 	/*
4728 	 * Make sure the minimum/maximum queue entry sizes are not
4729 	 * larger/smaller than the default.
4730 	 */
4731 
4732 	if (((1 << nvme->n_idctl->id_sqes.qes_min) > sizeof (nvme_sqe_t)) ||
4733 	    ((1 << nvme->n_idctl->id_sqes.qes_max) < sizeof (nvme_sqe_t)) ||
4734 	    ((1 << nvme->n_idctl->id_cqes.qes_min) > sizeof (nvme_cqe_t)) ||
4735 	    ((1 << nvme->n_idctl->id_cqes.qes_max) < sizeof (nvme_cqe_t)))
4736 		goto fail;
4737 
4738 	/*
4739 	 * Check for the presence of a Volatile Write Cache. If present,
4740 	 * enable or disable based on the value of the property
4741 	 * volatile-write-cache-enable (default is enabled).
4742 	 */
4743 	nvme->n_write_cache_present =
4744 	    nvme->n_idctl->id_vwc.vwc_present == 0 ? B_FALSE : B_TRUE;
4745 
4746 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
4747 	    "volatile-write-cache-present",
4748 	    nvme->n_write_cache_present ? 1 : 0);
4749 
4750 	if (!nvme->n_write_cache_present) {
4751 		nvme->n_write_cache_enabled = B_FALSE;
4752 	} else if (nvme_write_cache_set(nvme, nvme->n_write_cache_enabled)
4753 	    != 0) {
4754 		dev_err(nvme->n_dip, CE_WARN,
4755 		    "!failed to %sable volatile write cache",
4756 		    nvme->n_write_cache_enabled ? "en" : "dis");
4757 		/*
4758 		 * Assume the cache is (still) enabled.
4759 		 */
4760 		nvme->n_write_cache_enabled = B_TRUE;
4761 	}
4762 
4763 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
4764 	    "volatile-write-cache-enable",
4765 	    nvme->n_write_cache_enabled ? 1 : 0);
4766 
4767 	/*
4768 	 * Get number of supported namespaces and allocate namespace array.
4769 	 */
4770 	nvme->n_namespace_count = nvme->n_idctl->id_nn;
4771 
4772 	if (nvme->n_namespace_count == 0) {
4773 		dev_err(nvme->n_dip, CE_WARN,
4774 		    "!controllers without namespaces are not supported");
4775 		goto fail;
4776 	}
4777 
4778 	nvme->n_ns = kmem_zalloc(sizeof (nvme_namespace_t) *
4779 	    nvme->n_namespace_count, KM_SLEEP);
4780 
4781 	/*
4782 	 * Get the common namespace information if available. If not, we use the
4783 	 * information for nsid 1.
4784 	 */
4785 	if (nvme_ctrl_atleast(nvme, &nvme_vers_1v2) &&
4786 	    nvme->n_idctl->id_oacs.oa_nsmgmt != 0) {
4787 		nsid = NVME_NSID_BCAST;
4788 	} else {
4789 		nsid = 1;
4790 	}
4791 
4792 	if (!nvme_identify_int(nvme, nsid, NVME_IDENTIFY_NSID,
4793 	    (void **)&nvme->n_idcomns)) {
4794 		dev_err(nvme->n_dip, CE_WARN, "!failed to identify common "
4795 		    "namespace information");
4796 		goto fail;
4797 	}
4798 
4799 	if (nvme_get_current_nqueues(nvme, &nq)) {
4800 		nvme->n_submission_queues_supported = nq.b.nq_nsq + 1;
4801 		nvme->n_completion_queues_supported = nq.b.nq_ncq + 1;
4802 	} else {
4803 		dev_err(nvme->n_dip, CE_WARN,
4804 		    "!failed to retrieve number of supported queues");
4805 		goto fail;
4806 	}
4807 
4808 	/*
4809 	 * Try to set up MSI/MSI-X interrupts.
4810 	 */
4811 	if ((nvme->n_intr_types & (DDI_INTR_TYPE_MSI | DDI_INTR_TYPE_MSIX))
4812 	    != 0) {
4813 		const uint16_t nqueues = MIN(
4814 		    nvme->n_submission_queues_supported,
4815 		    nvme->n_completion_queues_supported);
4816 
4817 		nvme_release_interrupts(nvme);
4818 		if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX,
4819 		    nqueues) != DDI_SUCCESS) &&
4820 		    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI,
4821 		    nqueues) != DDI_SUCCESS)) {
4822 			dev_err(nvme->n_dip, CE_WARN,
4823 			    "!failed to set up MSI/MSI-X interrupts");
4824 			goto fail;
4825 		}
4826 	}
4827 
4828 	/*
4829 	 * Create I/O queue pairs.
4830 	 */
4831 
4832 	if (nvme_set_nqueues(nvme) != 0) {
4833 		dev_err(nvme->n_dip, CE_WARN,
4834 		    "!failed to set number of I/O queues to %d",
4835 		    nvme->n_intr_cnt);
4836 		goto fail;
4837 	}
4838 
4839 	/*
4840 	 * Reallocate I/O queue array
4841 	 */
4842 	kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *));
4843 	nvme->n_ioq = kmem_zalloc(sizeof (nvme_qpair_t *) *
4844 	    (nvme->n_submission_queues + 1), KM_SLEEP);
4845 	nvme->n_ioq[0] = nvme->n_adminq;
4846 
4847 	/*
4848 	 * There should always be at least as many submission queues
4849 	 * as completion queues.
4850 	 */
4851 	ASSERT(nvme->n_submission_queues >= nvme->n_completion_queues);
4852 
4853 	nvme->n_ioq_count = nvme->n_submission_queues;
4854 
4855 	nvme->n_io_squeue_len =
4856 	    MIN(nvme->n_io_squeue_len, nvme->n_max_queue_entries);
4857 
4858 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-squeue-len",
4859 	    nvme->n_io_squeue_len);
4860 
4861 	/*
4862 	 * Pre-allocate completion queues.
4863 	 * When there are the same number of submission and completion
4864 	 * queues there is no value in having a larger completion
4865 	 * queue length.
4866 	 */
4867 	if (nvme->n_submission_queues == nvme->n_completion_queues)
4868 		nvme->n_io_cqueue_len = MIN(nvme->n_io_cqueue_len,
4869 		    nvme->n_io_squeue_len);
4870 
4871 	nvme->n_io_cqueue_len = MIN(nvme->n_io_cqueue_len,
4872 	    nvme->n_max_queue_entries);
4873 
4874 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-cqueue-len",
4875 	    nvme->n_io_cqueue_len);
4876 
4877 	/*
4878 	 * Assign taskq threads per completion queue based on CPU budget.
4879 	 * Note: if n_completion_queues exceeds the number of CPUs, the
4880 	 * MAX(1, ...) rule will oversubscribe CPUs (one thread per CQ). If we
4881 	 * attach early, ncpus may be 1 even on an SMP system. In that case
4882 	 * max_ncpus can be used as a sizing proxy.
4883 	 */
4884 	uint_t ncpus_eff = ncpus;
4885 	if (ncpus_eff < 2)
4886 		ncpus_eff = (boot_max_ncpus == -1) ? max_ncpus : boot_max_ncpus;
4887 
4888 	tq_threads = ncpus_eff / nvme->n_completion_queues;
4889 
4890 	/*
4891 	 * In case the calculation above is zero, we need at least one
4892 	 * thread per completion queue.
4893 	 */
4894 	tq_threads = MAX(1, tq_threads);
4895 
4896 	if (nvme_create_cq_array(nvme, nvme->n_completion_queues + 1,
4897 	    nvme->n_io_cqueue_len, tq_threads) != DDI_SUCCESS) {
4898 		dev_err(nvme->n_dip, CE_WARN,
4899 		    "!failed to pre-allocate completion queues");
4900 		goto fail;
4901 	}
4902 
4903 	/*
4904 	 * If we use less completion queues than interrupt vectors return
4905 	 * some of the interrupt vectors back to the system.
4906 	 */
4907 	if (nvme->n_completion_queues + 1 < nvme->n_intr_cnt) {
4908 		nvme_release_interrupts(nvme);
4909 
4910 		if (nvme_setup_interrupts(nvme, nvme->n_intr_type,
4911 		    nvme->n_completion_queues + 1) != DDI_SUCCESS) {
4912 			dev_err(nvme->n_dip, CE_WARN,
4913 			    "!failed to reduce number of interrupts");
4914 			goto fail;
4915 		}
4916 	}
4917 
4918 	/*
4919 	 * Alloc & register I/O queue pairs
4920 	 */
4921 
4922 	for (i = 1; i != nvme->n_ioq_count + 1; i++) {
4923 		if (nvme_alloc_qpair(nvme, nvme->n_io_squeue_len,
4924 		    &nvme->n_ioq[i], i) != DDI_SUCCESS) {
4925 			dev_err(nvme->n_dip, CE_WARN,
4926 			    "!unable to allocate I/O qpair %d", i);
4927 			goto fail;
4928 		}
4929 
4930 		if (nvme_create_io_qpair(nvme, nvme->n_ioq[i], i) != 0) {
4931 			dev_err(nvme->n_dip, CE_WARN,
4932 			    "!unable to create I/O qpair %d", i);
4933 			goto fail;
4934 		}
4935 	}
4936 
4937 	/*
4938 	 * Enable any host behavior features that make sense for us.
4939 	 */
4940 	nvme_enable_host_behavior(nvme);
4941 
4942 	return (DDI_SUCCESS);
4943 
4944 fail:
4945 	(void) nvme_reset(nvme, B_FALSE);
4946 	return (DDI_FAILURE);
4947 }
4948 
4949 static uint_t
nvme_intr(caddr_t arg1,caddr_t arg2)4950 nvme_intr(caddr_t arg1, caddr_t arg2)
4951 {
4952 	nvme_t *nvme = (nvme_t *)arg1;
4953 	int inum = (int)(uintptr_t)arg2;
4954 	int ccnt = 0;
4955 	int qnum;
4956 
4957 	if (inum >= nvme->n_intr_cnt)
4958 		return (DDI_INTR_UNCLAIMED);
4959 
4960 	if (nvme->n_dead) {
4961 		return (nvme->n_intr_type == DDI_INTR_TYPE_FIXED ?
4962 		    DDI_INTR_UNCLAIMED : DDI_INTR_CLAIMED);
4963 	}
4964 
4965 	/*
4966 	 * The interrupt vector a queue uses is calculated as queue_idx %
4967 	 * intr_cnt in nvme_create_completion_queue(). Iterate through the
4968 	 * queue array in steps of n_intr_cnt to process all queues using this
4969 	 * vector.
4970 	 */
4971 	for (qnum = inum;
4972 	    qnum < nvme->n_cq_count && nvme->n_cq[qnum] != NULL;
4973 	    qnum += nvme->n_intr_cnt) {
4974 		ccnt += nvme_process_iocq(nvme, nvme->n_cq[qnum]);
4975 	}
4976 
4977 	return (ccnt > 0 ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
4978 }
4979 
4980 static void
nvme_release_interrupts(nvme_t * nvme)4981 nvme_release_interrupts(nvme_t *nvme)
4982 {
4983 	int i;
4984 
4985 	for (i = 0; i < nvme->n_intr_cnt; i++) {
4986 		if (nvme->n_inth[i] == NULL)
4987 			break;
4988 
4989 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
4990 			(void) ddi_intr_block_disable(&nvme->n_inth[i], 1);
4991 		else
4992 			(void) ddi_intr_disable(nvme->n_inth[i]);
4993 
4994 		(void) ddi_intr_remove_handler(nvme->n_inth[i]);
4995 		(void) ddi_intr_free(nvme->n_inth[i]);
4996 	}
4997 
4998 	kmem_free(nvme->n_inth, nvme->n_inth_sz);
4999 	nvme->n_inth = NULL;
5000 	nvme->n_inth_sz = 0;
5001 
5002 	nvme->n_progress &= ~NVME_INTERRUPTS;
5003 }
5004 
5005 static int
nvme_setup_interrupts(nvme_t * nvme,int intr_type,int nqpairs)5006 nvme_setup_interrupts(nvme_t *nvme, int intr_type, int nqpairs)
5007 {
5008 	int nintrs, navail, count;
5009 	int ret;
5010 	int i;
5011 
5012 	if (nvme->n_intr_types == 0) {
5013 		ret = ddi_intr_get_supported_types(nvme->n_dip,
5014 		    &nvme->n_intr_types);
5015 		if (ret != DDI_SUCCESS) {
5016 			dev_err(nvme->n_dip, CE_WARN,
5017 			    "!%s: ddi_intr_get_supported types failed",
5018 			    __func__);
5019 			return (ret);
5020 		}
5021 #ifdef __x86
5022 		if (get_hwenv() == HW_VMWARE)
5023 			nvme->n_intr_types &= ~DDI_INTR_TYPE_MSIX;
5024 #endif
5025 	}
5026 
5027 	if ((nvme->n_intr_types & intr_type) == 0)
5028 		return (DDI_FAILURE);
5029 
5030 	ret = ddi_intr_get_nintrs(nvme->n_dip, intr_type, &nintrs);
5031 	if (ret != DDI_SUCCESS) {
5032 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_nintrs failed",
5033 		    __func__);
5034 		return (ret);
5035 	}
5036 
5037 	ret = ddi_intr_get_navail(nvme->n_dip, intr_type, &navail);
5038 	if (ret != DDI_SUCCESS) {
5039 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_navail failed",
5040 		    __func__);
5041 		return (ret);
5042 	}
5043 
5044 	/* We want at most one interrupt per queue pair. */
5045 	if (navail > nqpairs)
5046 		navail = nqpairs;
5047 
5048 	nvme->n_inth_sz = sizeof (ddi_intr_handle_t) * navail;
5049 	nvme->n_inth = kmem_zalloc(nvme->n_inth_sz, KM_SLEEP);
5050 
5051 	ret = ddi_intr_alloc(nvme->n_dip, nvme->n_inth, intr_type, 0, navail,
5052 	    &count, 0);
5053 	if (ret != DDI_SUCCESS) {
5054 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_alloc failed",
5055 		    __func__);
5056 		goto fail;
5057 	}
5058 
5059 	nvme->n_intr_cnt = count;
5060 
5061 	ret = ddi_intr_get_pri(nvme->n_inth[0], &nvme->n_intr_pri);
5062 	if (ret != DDI_SUCCESS) {
5063 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_pri failed",
5064 		    __func__);
5065 		goto fail;
5066 	}
5067 
5068 	for (i = 0; i < count; i++) {
5069 		ret = ddi_intr_add_handler(nvme->n_inth[i], nvme_intr,
5070 		    (void *)nvme, (void *)(uintptr_t)i);
5071 		if (ret != DDI_SUCCESS) {
5072 			dev_err(nvme->n_dip, CE_WARN,
5073 			    "!%s: ddi_intr_add_handler failed", __func__);
5074 			goto fail;
5075 		}
5076 	}
5077 
5078 	(void) ddi_intr_get_cap(nvme->n_inth[0], &nvme->n_intr_cap);
5079 
5080 	for (i = 0; i < count; i++) {
5081 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
5082 			ret = ddi_intr_block_enable(&nvme->n_inth[i], 1);
5083 		else
5084 			ret = ddi_intr_enable(nvme->n_inth[i]);
5085 
5086 		if (ret != DDI_SUCCESS) {
5087 			dev_err(nvme->n_dip, CE_WARN,
5088 			    "!%s: enabling interrupt %d failed", __func__, i);
5089 			goto fail;
5090 		}
5091 	}
5092 
5093 	nvme->n_intr_type = intr_type;
5094 
5095 	nvme->n_progress |= NVME_INTERRUPTS;
5096 
5097 	return (DDI_SUCCESS);
5098 
5099 fail:
5100 	nvme_release_interrupts(nvme);
5101 
5102 	return (ret);
5103 }
5104 
5105 static int
nvme_fm_errcb(dev_info_t * dip,ddi_fm_error_t * fm_error,const void * arg)5106 nvme_fm_errcb(dev_info_t *dip, ddi_fm_error_t *fm_error, const void *arg)
5107 {
5108 	_NOTE(ARGUNUSED(arg));
5109 
5110 	pci_ereport_post(dip, fm_error, NULL);
5111 	return (fm_error->fme_status);
5112 }
5113 
5114 static void
nvme_remove_callback(dev_info_t * dip,ddi_eventcookie_t cookie,void * a,void * b)5115 nvme_remove_callback(dev_info_t *dip, ddi_eventcookie_t cookie, void *a,
5116     void *b)
5117 {
5118 	nvme_t *nvme = a;
5119 
5120 	nvme_ctrl_mark_dead(nvme, B_TRUE);
5121 
5122 	/*
5123 	 * Fail all outstanding commands, including those in the admin queue
5124 	 * (queue 0).
5125 	 */
5126 	for (uint_t i = 0; i < nvme->n_ioq_count + 1; i++) {
5127 		nvme_qpair_t *qp = nvme->n_ioq[i];
5128 
5129 		mutex_enter(&qp->nq_mutex);
5130 		for (size_t j = 0; j < qp->nq_nentry; j++) {
5131 			nvme_cmd_t *cmd = qp->nq_cmd[j];
5132 			nvme_cmd_t *u_cmd;
5133 
5134 			if (cmd == NULL) {
5135 				continue;
5136 			}
5137 
5138 			/*
5139 			 * Since we have the queue lock held the entire time we
5140 			 * iterate over it, it's not possible for the queue to
5141 			 * change underneath us. Thus, we don't need to check
5142 			 * that the return value of nvme_unqueue_cmd matches the
5143 			 * requested cmd to unqueue.
5144 			 */
5145 			u_cmd = nvme_unqueue_cmd(nvme, qp, cmd->nc_sqe.sqe_cid);
5146 			taskq_dispatch_ent(qp->nq_cq->ncq_cmd_taskq,
5147 			    cmd->nc_callback, cmd, TQ_NOSLEEP, &cmd->nc_tqent);
5148 
5149 			ASSERT3P(u_cmd, ==, cmd);
5150 		}
5151 		mutex_exit(&qp->nq_mutex);
5152 	}
5153 }
5154 
5155 /*
5156  * Open minor management
5157  */
5158 static int
nvme_minor_comparator(const void * l,const void * r)5159 nvme_minor_comparator(const void *l, const void *r)
5160 {
5161 	const nvme_minor_t *lm = l;
5162 	const nvme_minor_t *rm = r;
5163 
5164 	if (lm->nm_minor > rm->nm_minor) {
5165 		return (1);
5166 	} else if (lm->nm_minor < rm->nm_minor) {
5167 		return (-1);
5168 	} else {
5169 		return (0);
5170 	}
5171 }
5172 
5173 static void
nvme_minor_free(nvme_minor_t * minor)5174 nvme_minor_free(nvme_minor_t *minor)
5175 {
5176 	if (minor->nm_minor > 0) {
5177 		ASSERT3S(minor->nm_minor, >=, NVME_OPEN_MINOR_MIN);
5178 		id_free(nvme_open_minors, minor->nm_minor);
5179 		minor->nm_minor = 0;
5180 	}
5181 	VERIFY0(list_link_active(&minor->nm_ctrl_lock.nli_node));
5182 	VERIFY0(list_link_active(&minor->nm_ns_lock.nli_node));
5183 	cv_destroy(&minor->nm_cv);
5184 	kmem_free(minor, sizeof (nvme_minor_t));
5185 }
5186 
5187 static nvme_minor_t *
nvme_minor_find_by_dev(dev_t dev)5188 nvme_minor_find_by_dev(dev_t dev)
5189 {
5190 	id_t id = (id_t)getminor(dev);
5191 	nvme_minor_t search = { .nm_minor = id };
5192 	nvme_minor_t *ret;
5193 
5194 	mutex_enter(&nvme_open_minors_mutex);
5195 	ret = avl_find(&nvme_open_minors_avl, &search, NULL);
5196 	mutex_exit(&nvme_open_minors_mutex);
5197 
5198 	return (ret);
5199 }
5200 
5201 static int
nvme_attach(dev_info_t * dip,ddi_attach_cmd_t cmd)5202 nvme_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
5203 {
5204 	nvme_t *nvme;
5205 	int instance;
5206 	int nregs;
5207 	off_t regsize;
5208 	char name[32];
5209 
5210 	if (cmd != DDI_ATTACH)
5211 		return (DDI_FAILURE);
5212 
5213 	instance = ddi_get_instance(dip);
5214 
5215 	if (ddi_soft_state_zalloc(nvme_state, instance) != DDI_SUCCESS)
5216 		return (DDI_FAILURE);
5217 
5218 	nvme = ddi_get_soft_state(nvme_state, instance);
5219 	ddi_set_driver_private(dip, nvme);
5220 	nvme->n_dip = dip;
5221 
5222 	/*
5223 	 * Map PCI config space
5224 	 */
5225 	if (pci_config_setup(dip, &nvme->n_pcicfg_handle) != DDI_SUCCESS) {
5226 		dev_err(dip, CE_WARN, "!failed to map PCI config space");
5227 		goto fail;
5228 	}
5229 	nvme->n_progress |= NVME_PCI_CONFIG;
5230 
5231 	/*
5232 	 * Get the various PCI IDs from config space
5233 	 */
5234 	nvme->n_vendor_id =
5235 	    pci_config_get16(nvme->n_pcicfg_handle, PCI_CONF_VENID);
5236 	nvme->n_device_id =
5237 	    pci_config_get16(nvme->n_pcicfg_handle, PCI_CONF_DEVID);
5238 	nvme->n_revision_id =
5239 	    pci_config_get8(nvme->n_pcicfg_handle, PCI_CONF_REVID);
5240 	nvme->n_subsystem_device_id =
5241 	    pci_config_get16(nvme->n_pcicfg_handle, PCI_CONF_SUBSYSID);
5242 	nvme->n_subsystem_vendor_id =
5243 	    pci_config_get16(nvme->n_pcicfg_handle, PCI_CONF_SUBVENID);
5244 
5245 	nvme_detect_quirks(nvme);
5246 
5247 	/*
5248 	 * Set up event handlers for hot removal. While npe(4D) supports the hot
5249 	 * removal event being injected for devices, the same is not true of all
5250 	 * of our possible parents (i.e. pci(4D) as of this writing). The most
5251 	 * common case this shows up is in some virtualization environments. We
5252 	 * should treat this as non-fatal so that way devices work but leave
5253 	 * this set up in such a way that if a nexus does grow support for this
5254 	 * we're good to go.
5255 	 */
5256 	if (ddi_get_eventcookie(nvme->n_dip, DDI_DEVI_REMOVE_EVENT,
5257 	    &nvme->n_rm_cookie) == DDI_SUCCESS) {
5258 		if (ddi_add_event_handler(nvme->n_dip, nvme->n_rm_cookie,
5259 		    nvme_remove_callback, nvme, &nvme->n_ev_rm_cb_id) !=
5260 		    DDI_SUCCESS) {
5261 			goto fail;
5262 		}
5263 	} else {
5264 		nvme->n_ev_rm_cb_id = NULL;
5265 	}
5266 
5267 	mutex_init(&nvme->n_minor_mutex, NULL, MUTEX_DRIVER, NULL);
5268 	nvme->n_progress |= NVME_MUTEX_INIT;
5269 
5270 	nvme->n_strict_version = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5271 	    DDI_PROP_DONTPASS, "strict-version", 1) == 1 ? B_TRUE : B_FALSE;
5272 	nvme->n_ignore_unknown_vendor_status = ddi_prop_get_int(DDI_DEV_T_ANY,
5273 	    dip, DDI_PROP_DONTPASS, "ignore-unknown-vendor-status", 0) == 1 ?
5274 	    B_TRUE : B_FALSE;
5275 	nvme->n_admin_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5276 	    DDI_PROP_DONTPASS, "admin-queue-len", NVME_DEFAULT_ADMIN_QUEUE_LEN);
5277 	nvme->n_io_squeue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5278 	    DDI_PROP_DONTPASS, "io-squeue-len", NVME_DEFAULT_IO_QUEUE_LEN);
5279 	/*
5280 	 * Double up the default for completion queues in case of
5281 	 * queue sharing.
5282 	 */
5283 	nvme->n_io_cqueue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5284 	    DDI_PROP_DONTPASS, "io-cqueue-len", 2 * NVME_DEFAULT_IO_QUEUE_LEN);
5285 	nvme->n_async_event_limit = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5286 	    DDI_PROP_DONTPASS, "async-event-limit",
5287 	    NVME_DEFAULT_ASYNC_EVENT_LIMIT);
5288 	nvme->n_write_cache_enabled = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5289 	    DDI_PROP_DONTPASS, "volatile-write-cache-enable", 1) != 0 ?
5290 	    B_TRUE : B_FALSE;
5291 	nvme->n_min_block_size = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5292 	    DDI_PROP_DONTPASS, "min-phys-block-size",
5293 	    NVME_DEFAULT_MIN_BLOCK_SIZE);
5294 	nvme->n_submission_queues = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5295 	    DDI_PROP_DONTPASS, "max-submission-queues", -1);
5296 	nvme->n_completion_queues = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
5297 	    DDI_PROP_DONTPASS, "max-completion-queues", -1);
5298 
5299 	if (!ISP2(nvme->n_min_block_size) ||
5300 	    (nvme->n_min_block_size < NVME_DEFAULT_MIN_BLOCK_SIZE)) {
5301 		dev_err(dip, CE_WARN, "!min-phys-block-size %s, "
5302 		    "using default %d", ISP2(nvme->n_min_block_size) ?
5303 		    "too low" : "not a power of 2",
5304 		    NVME_DEFAULT_MIN_BLOCK_SIZE);
5305 		nvme->n_min_block_size = NVME_DEFAULT_MIN_BLOCK_SIZE;
5306 	}
5307 
5308 	if (nvme->n_submission_queues != -1 &&
5309 	    (nvme->n_submission_queues < 1 ||
5310 	    nvme->n_submission_queues > UINT16_MAX)) {
5311 		dev_err(dip, CE_WARN, "!\"submission-queues\"=%d is not "
5312 		    "valid. Must be [1..%d]", nvme->n_submission_queues,
5313 		    UINT16_MAX);
5314 		nvme->n_submission_queues = -1;
5315 	}
5316 
5317 	if (nvme->n_completion_queues != -1 &&
5318 	    (nvme->n_completion_queues < 1 ||
5319 	    nvme->n_completion_queues > UINT16_MAX)) {
5320 		dev_err(dip, CE_WARN, "!\"completion-queues\"=%d is not "
5321 		    "valid. Must be [1..%d]", nvme->n_completion_queues,
5322 		    UINT16_MAX);
5323 		nvme->n_completion_queues = -1;
5324 	}
5325 
5326 	if (nvme->n_admin_queue_len < NVME_MIN_ADMIN_QUEUE_LEN)
5327 		nvme->n_admin_queue_len = NVME_MIN_ADMIN_QUEUE_LEN;
5328 	else if (nvme->n_admin_queue_len > NVME_MAX_ADMIN_QUEUE_LEN)
5329 		nvme->n_admin_queue_len = NVME_MAX_ADMIN_QUEUE_LEN;
5330 
5331 	if (nvme->n_io_squeue_len < NVME_MIN_IO_QUEUE_LEN)
5332 		nvme->n_io_squeue_len = NVME_MIN_IO_QUEUE_LEN;
5333 	if (nvme->n_io_cqueue_len < NVME_MIN_IO_QUEUE_LEN)
5334 		nvme->n_io_cqueue_len = NVME_MIN_IO_QUEUE_LEN;
5335 
5336 	if (nvme->n_async_event_limit < 1)
5337 		nvme->n_async_event_limit = NVME_DEFAULT_ASYNC_EVENT_LIMIT;
5338 
5339 	nvme->n_reg_acc_attr = nvme_reg_acc_attr;
5340 	nvme->n_queue_dma_attr = nvme_queue_dma_attr;
5341 	nvme->n_prp_dma_attr = nvme_prp_dma_attr;
5342 	nvme->n_sgl_dma_attr = nvme_sgl_dma_attr;
5343 
5344 	/*
5345 	 * Set up FMA support.
5346 	 */
5347 	nvme->n_fm_cap = ddi_getprop(DDI_DEV_T_ANY, dip,
5348 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
5349 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
5350 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
5351 
5352 	ddi_fm_init(dip, &nvme->n_fm_cap, &nvme->n_fm_ibc);
5353 
5354 	if (nvme->n_fm_cap) {
5355 		if (nvme->n_fm_cap & DDI_FM_ACCCHK_CAPABLE)
5356 			nvme->n_reg_acc_attr.devacc_attr_access =
5357 			    DDI_FLAGERR_ACC;
5358 
5359 		if (nvme->n_fm_cap & DDI_FM_DMACHK_CAPABLE) {
5360 			nvme->n_prp_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
5361 			nvme->n_sgl_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
5362 		}
5363 
5364 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
5365 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
5366 			pci_ereport_setup(dip);
5367 
5368 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
5369 			ddi_fm_handler_register(dip, nvme_fm_errcb,
5370 			    (void *)nvme);
5371 	}
5372 
5373 	nvme->n_progress |= NVME_FMA_INIT;
5374 
5375 	/*
5376 	 * The spec defines several register sets. Only the controller
5377 	 * registers (set 1) are currently used.
5378 	 */
5379 	if (ddi_dev_nregs(dip, &nregs) == DDI_FAILURE ||
5380 	    nregs < 2 ||
5381 	    ddi_dev_regsize(dip, 1, &regsize) == DDI_FAILURE)
5382 		goto fail;
5383 
5384 	if (ddi_regs_map_setup(dip, 1, &nvme->n_regs, 0, regsize,
5385 	    &nvme->n_reg_acc_attr, &nvme->n_regh) != DDI_SUCCESS) {
5386 		dev_err(dip, CE_WARN, "!failed to map regset 1");
5387 		goto fail;
5388 	}
5389 
5390 	nvme->n_progress |= NVME_REGS_MAPPED;
5391 
5392 	/*
5393 	 * Set up kstats
5394 	 */
5395 	if (!nvme_stat_init(nvme)) {
5396 		dev_err(dip, CE_WARN, "!failed to create device kstats");
5397 		goto fail;
5398 	}
5399 	nvme->n_progress |= NVME_STAT_INIT;
5400 
5401 	/*
5402 	 * Create PRP DMA cache
5403 	 */
5404 	(void) snprintf(name, sizeof (name), "%s%d_prp_cache",
5405 	    ddi_driver_name(dip), ddi_get_instance(dip));
5406 	nvme->n_prp_cache = kmem_cache_create(name, sizeof (nvme_dma_t),
5407 	    0, nvme_prp_dma_constructor, nvme_prp_dma_destructor,
5408 	    NULL, (void *)nvme, NULL, 0);
5409 
5410 	if (nvme_init(nvme) != DDI_SUCCESS)
5411 		goto fail;
5412 
5413 	/*
5414 	 * Initialize the driver with the UFM subsystem
5415 	 */
5416 	if (ddi_ufm_init(dip, DDI_UFM_CURRENT_VERSION, &nvme_ufm_ops,
5417 	    &nvme->n_ufmh, nvme) != 0) {
5418 		dev_err(dip, CE_WARN, "!failed to initialize UFM subsystem");
5419 		goto fail;
5420 	}
5421 	mutex_init(&nvme->n_fwslot_mutex, NULL, MUTEX_DRIVER, NULL);
5422 	ddi_ufm_update(nvme->n_ufmh);
5423 	nvme->n_progress |= NVME_UFM_INIT;
5424 
5425 	nvme_mgmt_lock_init(&nvme->n_mgmt);
5426 	nvme_lock_init(&nvme->n_lock);
5427 	nvme->n_progress |= NVME_MGMT_INIT;
5428 
5429 	/*
5430 	 * Identify namespaces.
5431 	 */
5432 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
5433 
5434 	boolean_t minor_logged = B_FALSE;
5435 	for (uint32_t i = 1; i <= nvme->n_namespace_count; i++) {
5436 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, i);
5437 
5438 		nvme_lock_init(&ns->ns_lock);
5439 		ns->ns_progress |= NVME_NS_LOCK;
5440 
5441 		/*
5442 		 * Namespaces start out in the active state. This is the
5443 		 * default state until we find out information about the
5444 		 * namespaces in more detail. nvme_init_ns() will go through and
5445 		 * determine what the proper state should be. It will also use
5446 		 * this state change to keep an accurate count of attachable
5447 		 * namespaces.
5448 		 */
5449 		ns->ns_state = NVME_NS_STATE_ACTIVE;
5450 		if (nvme_init_ns(nvme, i) != 0) {
5451 			nvme_mgmt_unlock(nvme);
5452 			goto fail;
5453 		}
5454 
5455 		/*
5456 		 * We only create compat minor nodes for the namespace for the
5457 		 * first NVME_MINOR_MAX namespaces. Those that are beyond this
5458 		 * can only be accessed through the primary controller node,
5459 		 * which is generally fine as that's what libnvme uses and is
5460 		 * our preferred path. Not having a minor is better than not
5461 		 * having the namespace!
5462 		 */
5463 		if (i > NVME_MINOR_MAX) {
5464 			if (!minor_logged) {
5465 				dev_err(dip, CE_WARN, "namespace minor "
5466 				    "creation limited to the first %u "
5467 				    "namespaces, device has %u",
5468 				    NVME_MINOR_MAX, nvme->n_namespace_count);
5469 				minor_logged = B_TRUE;
5470 			}
5471 			continue;
5472 		}
5473 
5474 		if (ddi_create_minor_node(nvme->n_dip, ns->ns_name, S_IFCHR,
5475 		    NVME_MINOR(ddi_get_instance(nvme->n_dip), i),
5476 		    DDI_NT_NVME_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
5477 			nvme_mgmt_unlock(nvme);
5478 			dev_err(dip, CE_WARN,
5479 			    "!failed to create minor node for namespace %d", i);
5480 			goto fail;
5481 		}
5482 		ns->ns_progress |= NVME_NS_MINOR;
5483 	}
5484 
5485 	/*
5486 	 * Indicate that namespace initialization is complete and therefore
5487 	 * marking the controller dead can evaluate every namespace lock.
5488 	 */
5489 	nvme->n_progress |= NVME_NS_INIT;
5490 
5491 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
5492 	    NVME_MINOR(ddi_get_instance(dip), 0), DDI_NT_NVME_NEXUS, 0) !=
5493 	    DDI_SUCCESS) {
5494 		nvme_mgmt_unlock(nvme);
5495 		dev_err(dip, CE_WARN, "nvme_attach: "
5496 		    "cannot create devctl minor node");
5497 		goto fail;
5498 	}
5499 
5500 	/*
5501 	 * Attempt to attach all namespaces that are in a reasonable state. This
5502 	 * should not fail attach.
5503 	 */
5504 	for (uint32_t i = 1; i <= nvme->n_namespace_count; i++) {
5505 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, i);
5506 		nvme_ioctl_common_t com = { .nioc_nsid = i };
5507 
5508 		if (ns->ns_state < NVME_NS_STATE_NOT_IGNORED)
5509 			continue;
5510 
5511 		if (!nvme_bd_attach_ns(nvme, &com) && com.nioc_drv_err !=
5512 		    NVME_IOCTL_E_UNSUP_ATTACH_NS) {
5513 			dev_err(nvme->n_dip, CE_WARN, "!failed to attach "
5514 			    "namespace %d due to blkdev error (0x%x)", i,
5515 			    com.nioc_drv_err);
5516 		}
5517 	}
5518 
5519 	nvme_mgmt_unlock(nvme);
5520 
5521 	/*
5522 	 * As the last thing that we do, we finally go ahead and enable
5523 	 * asynchronous event notifications. Currently we rely upon whatever
5524 	 * defaults the device has for the events that we will receive. If we
5525 	 * enable this earlier, it's possible that we'll get events that we
5526 	 * cannot handle yet because all of our data structures are not valid.
5527 	 * The device will queue all asynchronous events on a per-log page basis
5528 	 * until we submit this. If the device is totally broken, it will have
5529 	 * likely failed our commands already. If we add support for configuring
5530 	 * which asynchronous events we would like to receive via the SET
5531 	 * FEATURES command, then we should do that as one of the first commands
5532 	 * we send in nvme_init().
5533 	 *
5534 	 * We start by assuming asynchronous events are supported. However, not
5535 	 * all devices (e.g. some versions of QEMU) support this, so we end up
5536 	 * tracking whether or not we think these actually work.
5537 	 */
5538 	nvme->n_async_event_supported = B_TRUE;
5539 	for (uint16_t i = 0; i < nvme->n_async_event_limit; i++) {
5540 		nvme_async_event(nvme);
5541 	}
5542 
5543 
5544 	return (DDI_SUCCESS);
5545 
5546 fail:
5547 	/* attach successful anyway so that FMA can retire the device */
5548 	if (nvme->n_dead)
5549 		return (DDI_SUCCESS);
5550 
5551 	(void) nvme_detach(dip, DDI_DETACH);
5552 
5553 	return (DDI_FAILURE);
5554 }
5555 
5556 static int
nvme_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)5557 nvme_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
5558 {
5559 	int instance;
5560 	nvme_t *nvme;
5561 
5562 	if (cmd != DDI_DETACH)
5563 		return (DDI_FAILURE);
5564 
5565 	instance = ddi_get_instance(dip);
5566 
5567 	nvme = ddi_get_soft_state(nvme_state, instance);
5568 
5569 	if (nvme == NULL)
5570 		return (DDI_FAILURE);
5571 
5572 	/*
5573 	 * Remove all minor nodes from the device regardless of the source in
5574 	 * one swoop.
5575 	 */
5576 	ddi_remove_minor_node(dip, NULL);
5577 
5578 	/*
5579 	 * We need to remove the event handler as one of the first things that
5580 	 * we do. If we proceed with other teardown without removing the event
5581 	 * handler, we could end up in a very unfortunate race with ourselves.
5582 	 * The DDI does not serialize these with detach (just like timeout(9F)
5583 	 * and others).
5584 	 */
5585 	if (nvme->n_ev_rm_cb_id != NULL) {
5586 		(void) ddi_remove_event_handler(nvme->n_ev_rm_cb_id);
5587 	}
5588 	nvme->n_ev_rm_cb_id = NULL;
5589 
5590 	/*
5591 	 * If the controller was marked dead, there is a slight chance that we
5592 	 * are asynchronusly processing the removal taskq. Because we have
5593 	 * removed the callback handler above and all minor nodes and commands
5594 	 * are closed, there is no other way to get in here. As such, we wait on
5595 	 * the nvme_dead_taskq to complete so we can avoid tracking if it's
5596 	 * running or not.
5597 	 */
5598 	taskq_wait(nvme_dead_taskq);
5599 
5600 	if (nvme->n_ns) {
5601 		for (uint32_t i = 1; i <= nvme->n_namespace_count; i++) {
5602 			nvme_namespace_t *ns = nvme_nsid2ns(nvme, i);
5603 
5604 			if (ns->ns_bd_hdl) {
5605 				(void) bd_detach_handle(ns->ns_bd_hdl);
5606 				bd_free_handle(ns->ns_bd_hdl);
5607 			}
5608 
5609 			if (ns->ns_idns)
5610 				kmem_free(ns->ns_idns,
5611 				    sizeof (nvme_identify_nsid_t));
5612 			if (ns->ns_devid)
5613 				strfree(ns->ns_devid);
5614 
5615 			if ((ns->ns_progress & NVME_NS_LOCK) != 0)
5616 				nvme_lock_fini(&ns->ns_lock);
5617 		}
5618 
5619 		kmem_free(nvme->n_ns, sizeof (nvme_namespace_t) *
5620 		    nvme->n_namespace_count);
5621 	}
5622 
5623 	if (nvme->n_progress & NVME_MGMT_INIT) {
5624 		nvme_lock_fini(&nvme->n_lock);
5625 		nvme_mgmt_lock_fini(&nvme->n_mgmt);
5626 	}
5627 
5628 	if (nvme->n_progress & NVME_UFM_INIT) {
5629 		ddi_ufm_fini(nvme->n_ufmh);
5630 		mutex_destroy(&nvme->n_fwslot_mutex);
5631 	}
5632 
5633 	if (nvme->n_progress & NVME_INTERRUPTS)
5634 		nvme_release_interrupts(nvme);
5635 
5636 	for (uint_t i = 0; i < nvme->n_cq_count; i++) {
5637 		if (nvme->n_cq[i]->ncq_cmd_taskq != NULL)
5638 			taskq_wait(nvme->n_cq[i]->ncq_cmd_taskq);
5639 	}
5640 
5641 	if (nvme->n_progress & NVME_MUTEX_INIT) {
5642 		mutex_destroy(&nvme->n_minor_mutex);
5643 	}
5644 
5645 	if (nvme->n_ioq_count > 0) {
5646 		for (uint_t i = 1; i != nvme->n_ioq_count + 1; i++) {
5647 			if (nvme->n_ioq[i] != NULL) {
5648 				/* TODO: send destroy queue commands */
5649 				nvme_free_qpair(nvme->n_ioq[i]);
5650 			}
5651 		}
5652 
5653 		kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *) *
5654 		    (nvme->n_ioq_count + 1));
5655 	}
5656 
5657 	if (nvme->n_prp_cache != NULL) {
5658 		kmem_cache_destroy(nvme->n_prp_cache);
5659 	}
5660 
5661 	if (nvme->n_progress & NVME_REGS_MAPPED) {
5662 		nvme_shutdown(nvme, B_FALSE);
5663 		(void) nvme_reset(nvme, B_FALSE);
5664 	}
5665 
5666 	if (nvme->n_progress & NVME_CTRL_LIMITS)
5667 		sema_destroy(&nvme->n_abort_sema);
5668 
5669 	if (nvme->n_progress & NVME_ADMIN_QUEUE)
5670 		nvme_free_qpair(nvme->n_adminq);
5671 
5672 	if (nvme->n_cq_count > 0) {
5673 		nvme_destroy_cq_array(nvme, 0);
5674 		nvme->n_cq = NULL;
5675 		nvme->n_cq_count = 0;
5676 	}
5677 
5678 	if (nvme->n_idcomns)
5679 		kmem_free(nvme->n_idcomns, NVME_IDENTIFY_BUFSIZE);
5680 
5681 	if (nvme->n_idctl)
5682 		kmem_free(nvme->n_idctl, NVME_IDENTIFY_BUFSIZE);
5683 
5684 	if (nvme->n_progress & NVME_REGS_MAPPED)
5685 		ddi_regs_map_free(&nvme->n_regh);
5686 
5687 	if (nvme->n_progress & NVME_STAT_INIT)
5688 		nvme_stat_cleanup(nvme);
5689 
5690 	if (nvme->n_progress & NVME_FMA_INIT) {
5691 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
5692 			ddi_fm_handler_unregister(nvme->n_dip);
5693 
5694 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
5695 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
5696 			pci_ereport_teardown(nvme->n_dip);
5697 
5698 		ddi_fm_fini(nvme->n_dip);
5699 	}
5700 
5701 	if (nvme->n_progress & NVME_PCI_CONFIG)
5702 		pci_config_teardown(&nvme->n_pcicfg_handle);
5703 
5704 	if (nvme->n_vendor != NULL)
5705 		strfree(nvme->n_vendor);
5706 
5707 	if (nvme->n_product != NULL)
5708 		strfree(nvme->n_product);
5709 
5710 	ddi_soft_state_free(nvme_state, instance);
5711 
5712 	return (DDI_SUCCESS);
5713 }
5714 
5715 static int
nvme_quiesce(dev_info_t * dip)5716 nvme_quiesce(dev_info_t *dip)
5717 {
5718 	int instance;
5719 	nvme_t *nvme;
5720 
5721 	instance = ddi_get_instance(dip);
5722 
5723 	nvme = ddi_get_soft_state(nvme_state, instance);
5724 
5725 	if (nvme == NULL)
5726 		return (DDI_FAILURE);
5727 
5728 	nvme_shutdown(nvme, B_TRUE);
5729 
5730 	(void) nvme_reset(nvme, B_TRUE);
5731 
5732 	return (DDI_SUCCESS);
5733 }
5734 
5735 static int
nvme_fill_prp(nvme_cmd_t * cmd,ddi_dma_handle_t dma)5736 nvme_fill_prp(nvme_cmd_t *cmd, ddi_dma_handle_t dma)
5737 {
5738 	nvme_t *nvme = cmd->nc_nvme;
5739 	uint_t nprp_per_page, nprp;
5740 	uint64_t *prp;
5741 	const ddi_dma_cookie_t *cookie;
5742 	uint_t idx;
5743 	uint_t ncookies = ddi_dma_ncookies(dma);
5744 
5745 	if (ncookies == 0)
5746 		return (DDI_FAILURE);
5747 
5748 	if ((cookie = ddi_dma_cookie_get(dma, 0)) == NULL)
5749 		return (DDI_FAILURE);
5750 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cookie->dmac_laddress;
5751 
5752 	if (ncookies == 1) {
5753 		cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
5754 		return (DDI_SUCCESS);
5755 	} else if (ncookies == 2) {
5756 		if ((cookie = ddi_dma_cookie_get(dma, 1)) == NULL)
5757 			return (DDI_FAILURE);
5758 		cmd->nc_sqe.sqe_dptr.d_prp[1] = cookie->dmac_laddress;
5759 		return (DDI_SUCCESS);
5760 	}
5761 
5762 	/*
5763 	 * At this point, we're always operating on cookies at
5764 	 * index >= 1 and writing the addresses of those cookies
5765 	 * into a new page. The address of that page is stored
5766 	 * as the second PRP entry.
5767 	 */
5768 	nprp_per_page = nvme->n_pagesize / sizeof (uint64_t);
5769 	ASSERT(nprp_per_page > 0);
5770 
5771 	/*
5772 	 * We currently don't support chained PRPs and set up our DMA
5773 	 * attributes to reflect that. If we still get an I/O request
5774 	 * that needs a chained PRP something is very wrong. Account
5775 	 * for the first cookie here, which we've placed in d_prp[0].
5776 	 */
5777 	nprp = howmany(ncookies - 1, nprp_per_page);
5778 	VERIFY(nprp == 1);
5779 
5780 	/*
5781 	 * Allocate a page of pointers, in which we'll write the
5782 	 * addresses of cookies 1 to `ncookies`.
5783 	 */
5784 	cmd->nc_prp = kmem_cache_alloc(nvme->n_prp_cache, KM_SLEEP);
5785 	bzero(cmd->nc_prp->nd_memp, cmd->nc_prp->nd_len);
5786 	cmd->nc_sqe.sqe_dptr.d_prp[1] = cmd->nc_prp->nd_cookie.dmac_laddress;
5787 
5788 	prp = (uint64_t *)cmd->nc_prp->nd_memp;
5789 	for (idx = 1; idx < ncookies; idx++) {
5790 		if ((cookie = ddi_dma_cookie_get(dma, idx)) == NULL)
5791 			return (DDI_FAILURE);
5792 		*prp++ = cookie->dmac_laddress;
5793 	}
5794 
5795 	(void) ddi_dma_sync(cmd->nc_prp->nd_dmah, 0, cmd->nc_prp->nd_len,
5796 	    DDI_DMA_SYNC_FORDEV);
5797 	return (DDI_SUCCESS);
5798 }
5799 
5800 /*
5801  * The maximum number of requests supported for a deallocate request is
5802  * NVME_DSET_MGMT_MAX_RANGES (256) -- this is from the NVMe 1.1 spec (and
5803  * unchanged through at least 1.4a). The definition of nvme_range_t is also
5804  * from the NVMe 1.1 spec. Together, the result is that all of the ranges for
5805  * a deallocate request will fit into the smallest supported namespace page
5806  * (4k).
5807  */
5808 CTASSERT(sizeof (nvme_range_t) * NVME_DSET_MGMT_MAX_RANGES == 4096);
5809 
5810 static int
nvme_fill_ranges(nvme_cmd_t * cmd,bd_xfer_t * xfer,uint64_t blocksize,int allocflag)5811 nvme_fill_ranges(nvme_cmd_t *cmd, bd_xfer_t *xfer, uint64_t blocksize,
5812     int allocflag)
5813 {
5814 	const dkioc_free_list_t *dfl = xfer->x_dfl;
5815 	const dkioc_free_list_ext_t *exts = dfl->dfl_exts;
5816 	nvme_t *nvme = cmd->nc_nvme;
5817 	nvme_range_t *ranges = NULL;
5818 	uint_t i;
5819 
5820 	/*
5821 	 * The number of ranges in the request is 0s based (that is
5822 	 * word10 == 0 -> 1 range, word10 == 1 -> 2 ranges, ...,
5823 	 * word10 == 255 -> 256 ranges). Therefore the allowed values are
5824 	 * [1..NVME_DSET_MGMT_MAX_RANGES]. If blkdev gives us a bad request,
5825 	 * we either provided bad info in nvme_bd_driveinfo() or there is a bug
5826 	 * in blkdev.
5827 	 */
5828 	VERIFY3U(dfl->dfl_num_exts, >, 0);
5829 	VERIFY3U(dfl->dfl_num_exts, <=, NVME_DSET_MGMT_MAX_RANGES);
5830 	cmd->nc_sqe.sqe_cdw10 = (dfl->dfl_num_exts - 1) & 0xff;
5831 
5832 	cmd->nc_sqe.sqe_cdw11 = NVME_DSET_MGMT_ATTR_DEALLOCATE;
5833 
5834 	cmd->nc_prp = kmem_cache_alloc(nvme->n_prp_cache, allocflag);
5835 	if (cmd->nc_prp == NULL)
5836 		return (DDI_FAILURE);
5837 
5838 	bzero(cmd->nc_prp->nd_memp, cmd->nc_prp->nd_len);
5839 	ranges = (nvme_range_t *)cmd->nc_prp->nd_memp;
5840 
5841 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_prp->nd_cookie.dmac_laddress;
5842 	cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
5843 
5844 	for (i = 0; i < dfl->dfl_num_exts; i++) {
5845 		uint64_t lba, len;
5846 
5847 		lba = (dfl->dfl_offset + exts[i].dfle_start) / blocksize;
5848 		len = exts[i].dfle_length / blocksize;
5849 
5850 		VERIFY3U(len, <=, UINT32_MAX);
5851 
5852 		/* No context attributes for a deallocate request */
5853 		ranges[i].nr_ctxattr = 0;
5854 		ranges[i].nr_len = len;
5855 		ranges[i].nr_lba = lba;
5856 	}
5857 
5858 	(void) ddi_dma_sync(cmd->nc_prp->nd_dmah, 0, cmd->nc_prp->nd_len,
5859 	    DDI_DMA_SYNC_FORDEV);
5860 
5861 	return (DDI_SUCCESS);
5862 }
5863 
5864 static nvme_cmd_t *
nvme_create_nvm_cmd(nvme_namespace_t * ns,uint8_t opc,bd_xfer_t * xfer)5865 nvme_create_nvm_cmd(nvme_namespace_t *ns, uint8_t opc, bd_xfer_t *xfer)
5866 {
5867 	nvme_t *nvme = ns->ns_nvme;
5868 	nvme_cmd_t *cmd;
5869 	int allocflag;
5870 
5871 	/*
5872 	 * Blkdev only sets BD_XFER_POLL when dumping, so don't sleep.
5873 	 */
5874 	allocflag = (xfer->x_flags & BD_XFER_POLL) ? KM_NOSLEEP : KM_SLEEP;
5875 	cmd = nvme_alloc_cmd(nvme, allocflag);
5876 
5877 	if (cmd == NULL)
5878 		return (NULL);
5879 
5880 	cmd->nc_sqe.sqe_opc = opc;
5881 	cmd->nc_callback = nvme_bd_xfer_done;
5882 	cmd->nc_xfer = xfer;
5883 
5884 	switch (opc) {
5885 	case NVME_OPC_NVM_WRITE:
5886 	case NVME_OPC_NVM_READ:
5887 		VERIFY(xfer->x_nblks <= 0x10000);
5888 
5889 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
5890 
5891 		cmd->nc_sqe.sqe_cdw10 = xfer->x_blkno & 0xffffffffu;
5892 		cmd->nc_sqe.sqe_cdw11 = (xfer->x_blkno >> 32);
5893 		cmd->nc_sqe.sqe_cdw12 = (uint16_t)(xfer->x_nblks - 1);
5894 
5895 		if (nvme_fill_prp(cmd, xfer->x_dmah) != DDI_SUCCESS)
5896 			goto fail;
5897 		break;
5898 
5899 	case NVME_OPC_NVM_FLUSH:
5900 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
5901 		break;
5902 
5903 	case NVME_OPC_NVM_DSET_MGMT:
5904 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
5905 
5906 		if (nvme_fill_ranges(cmd, xfer,
5907 		    (uint64_t)ns->ns_block_size, allocflag) != DDI_SUCCESS)
5908 			goto fail;
5909 		break;
5910 
5911 	default:
5912 		goto fail;
5913 	}
5914 
5915 	return (cmd);
5916 
5917 fail:
5918 	nvme_free_cmd(cmd);
5919 	return (NULL);
5920 }
5921 
5922 static void
nvme_bd_xfer_done(void * arg)5923 nvme_bd_xfer_done(void *arg)
5924 {
5925 	nvme_cmd_t *cmd = arg;
5926 	bd_xfer_t *xfer = cmd->nc_xfer;
5927 	int error = 0;
5928 
5929 	error = nvme_check_cmd_status(cmd);
5930 	nvme_free_cmd(cmd);
5931 
5932 	bd_xfer_done(xfer, error);
5933 }
5934 
5935 static void
nvme_bd_driveinfo(void * arg,bd_drive_t * drive)5936 nvme_bd_driveinfo(void *arg, bd_drive_t *drive)
5937 {
5938 	nvme_namespace_t *ns = arg;
5939 	nvme_t *nvme = ns->ns_nvme;
5940 	uint_t ns_count = MAX(1, nvme->n_namespaces_attachable);
5941 
5942 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_BDRO);
5943 
5944 	/*
5945 	 * Set the blkdev qcount to the number of submission queues.
5946 	 * It will then create one waitq/runq pair for each submission
5947 	 * queue and spread I/O requests across the queues.
5948 	 */
5949 	drive->d_qcount = nvme->n_ioq_count;
5950 
5951 	/*
5952 	 * I/O activity to individual namespaces is distributed across
5953 	 * each of the d_qcount blkdev queues (which has been set to
5954 	 * the number of nvme submission queues). d_qsize is the number
5955 	 * of submitted and not completed I/Os within each queue that blkdev
5956 	 * will allow before it starts holding them in the waitq.
5957 	 *
5958 	 * Each namespace will create a child blkdev instance, for each one
5959 	 * we try and set the d_qsize so that each namespace gets an
5960 	 * equal portion of the submission queue.
5961 	 *
5962 	 * If post instantiation of the nvme drive, n_namespaces_attachable
5963 	 * changes and a namespace is attached it could calculate a
5964 	 * different d_qsize. It may even be that the sum of the d_qsizes is
5965 	 * now beyond the submission queue size. Should that be the case
5966 	 * and the I/O rate is such that blkdev attempts to submit more
5967 	 * I/Os than the size of the submission queue, the excess I/Os
5968 	 * will be held behind the semaphore nq_sema.
5969 	 */
5970 	drive->d_qsize = nvme->n_io_squeue_len / ns_count;
5971 
5972 	/*
5973 	 * Don't let the queue size drop below the minimum, though.
5974 	 */
5975 	drive->d_qsize = MAX(drive->d_qsize, NVME_MIN_IO_QUEUE_LEN);
5976 
5977 	/*
5978 	 * d_maxxfer is not set, which means the value is taken from the DMA
5979 	 * attributes specified to bd_alloc_handle.
5980 	 */
5981 
5982 	drive->d_removable = B_FALSE;
5983 	drive->d_hotpluggable = B_FALSE;
5984 
5985 	bcopy(ns->ns_eui64, drive->d_eui64, sizeof (drive->d_eui64));
5986 	drive->d_target = ns->ns_id;
5987 	drive->d_lun = 0;
5988 
5989 	drive->d_model = nvme->n_idctl->id_model;
5990 	drive->d_model_len = sizeof (nvme->n_idctl->id_model);
5991 	drive->d_vendor = nvme->n_vendor;
5992 	drive->d_vendor_len = strlen(nvme->n_vendor);
5993 	drive->d_product = nvme->n_product;
5994 	drive->d_product_len = strlen(nvme->n_product);
5995 	drive->d_serial = nvme->n_idctl->id_serial;
5996 	drive->d_serial_len = sizeof (nvme->n_idctl->id_serial);
5997 	drive->d_revision = nvme->n_idctl->id_fwrev;
5998 	drive->d_revision_len = sizeof (nvme->n_idctl->id_fwrev);
5999 
6000 	/*
6001 	 * If we support the dataset management command, the only restrictions
6002 	 * on a discard request are the maximum number of ranges (segments)
6003 	 * per single request.
6004 	 */
6005 	if (nvme->n_idctl->id_oncs.on_dset_mgmt)
6006 		drive->d_max_free_seg = NVME_DSET_MGMT_MAX_RANGES;
6007 
6008 	nvme_mgmt_unlock(nvme);
6009 }
6010 
6011 static int
nvme_bd_mediainfo(void * arg,bd_media_t * media)6012 nvme_bd_mediainfo(void *arg, bd_media_t *media)
6013 {
6014 	nvme_namespace_t *ns = arg;
6015 	nvme_t *nvme = ns->ns_nvme;
6016 
6017 	if (nvme->n_dead) {
6018 		return (EIO);
6019 	}
6020 
6021 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_BDRO);
6022 
6023 	media->m_nblks = ns->ns_block_count;
6024 	media->m_blksize = ns->ns_block_size;
6025 	media->m_readonly = B_FALSE;
6026 	media->m_solidstate = B_TRUE;
6027 
6028 	media->m_pblksize = ns->ns_best_block_size;
6029 
6030 	nvme_mgmt_unlock(nvme);
6031 
6032 	return (0);
6033 }
6034 
6035 static int
nvme_bd_cmd(nvme_namespace_t * ns,bd_xfer_t * xfer,uint8_t opc)6036 nvme_bd_cmd(nvme_namespace_t *ns, bd_xfer_t *xfer, uint8_t opc)
6037 {
6038 	nvme_t *nvme = ns->ns_nvme;
6039 	nvme_cmd_t *cmd;
6040 	nvme_qpair_t *ioq;
6041 	boolean_t poll;
6042 	int ret;
6043 
6044 	if (nvme->n_dead) {
6045 		return (EIO);
6046 	}
6047 
6048 	cmd = nvme_create_nvm_cmd(ns, opc, xfer);
6049 	if (cmd == NULL)
6050 		return (ENOMEM);
6051 
6052 	cmd->nc_sqid = xfer->x_qnum + 1;
6053 	ASSERT(cmd->nc_sqid <= nvme->n_ioq_count);
6054 	ioq = nvme->n_ioq[cmd->nc_sqid];
6055 
6056 	/*
6057 	 * Get the polling flag before submitting the command. The command may
6058 	 * complete immediately after it was submitted, which means we must
6059 	 * treat both cmd and xfer as if they have been freed already.
6060 	 */
6061 	poll = (xfer->x_flags & BD_XFER_POLL) != 0;
6062 
6063 	ret = nvme_submit_io_cmd(ioq, cmd);
6064 
6065 	if (ret != 0)
6066 		return (ret);
6067 
6068 	if (!poll)
6069 		return (0);
6070 
6071 	do {
6072 		cmd = nvme_retrieve_cmd(nvme, ioq);
6073 		if (cmd != NULL) {
6074 			ASSERT0(cmd->nc_flags & NVME_CMD_F_USELOCK);
6075 			cmd->nc_callback(cmd);
6076 		} else {
6077 			drv_usecwait(10);
6078 		}
6079 	} while (ioq->nq_active_cmds != 0);
6080 
6081 	return (0);
6082 }
6083 
6084 static int
nvme_bd_read(void * arg,bd_xfer_t * xfer)6085 nvme_bd_read(void *arg, bd_xfer_t *xfer)
6086 {
6087 	nvme_namespace_t *ns = arg;
6088 
6089 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_READ));
6090 }
6091 
6092 static int
nvme_bd_write(void * arg,bd_xfer_t * xfer)6093 nvme_bd_write(void *arg, bd_xfer_t *xfer)
6094 {
6095 	nvme_namespace_t *ns = arg;
6096 
6097 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_WRITE));
6098 }
6099 
6100 static int
nvme_bd_sync(void * arg,bd_xfer_t * xfer)6101 nvme_bd_sync(void *arg, bd_xfer_t *xfer)
6102 {
6103 	nvme_namespace_t *ns = arg;
6104 
6105 	if (ns->ns_nvme->n_dead)
6106 		return (EIO);
6107 
6108 	/*
6109 	 * If the volatile write cache is not present or not enabled the FLUSH
6110 	 * command is a no-op, so we can take a shortcut here.
6111 	 */
6112 	if (!ns->ns_nvme->n_write_cache_present) {
6113 		bd_xfer_done(xfer, ENOTSUP);
6114 		return (0);
6115 	}
6116 
6117 	if (!ns->ns_nvme->n_write_cache_enabled) {
6118 		bd_xfer_done(xfer, 0);
6119 		return (0);
6120 	}
6121 
6122 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_FLUSH));
6123 }
6124 
6125 static int
nvme_bd_devid(void * arg,dev_info_t * devinfo,ddi_devid_t * devid)6126 nvme_bd_devid(void *arg, dev_info_t *devinfo, ddi_devid_t *devid)
6127 {
6128 	nvme_namespace_t *ns = arg;
6129 	nvme_t *nvme = ns->ns_nvme;
6130 
6131 	if (nvme->n_dead) {
6132 		return (EIO);
6133 	}
6134 
6135 	if (*(uint64_t *)ns->ns_nguid != 0 ||
6136 	    *(uint64_t *)(ns->ns_nguid + 8) != 0) {
6137 		return (ddi_devid_init(devinfo, DEVID_NVME_NGUID,
6138 		    sizeof (ns->ns_nguid), ns->ns_nguid, devid));
6139 	} else if (*(uint64_t *)ns->ns_eui64 != 0) {
6140 		return (ddi_devid_init(devinfo, DEVID_NVME_EUI64,
6141 		    sizeof (ns->ns_eui64), ns->ns_eui64, devid));
6142 	} else {
6143 		return (ddi_devid_init(devinfo, DEVID_NVME_NSID,
6144 		    strlen(ns->ns_devid), ns->ns_devid, devid));
6145 	}
6146 }
6147 
6148 static int
nvme_bd_free_space(void * arg,bd_xfer_t * xfer)6149 nvme_bd_free_space(void *arg, bd_xfer_t *xfer)
6150 {
6151 	nvme_namespace_t *ns = arg;
6152 
6153 	if (xfer->x_dfl == NULL)
6154 		return (EINVAL);
6155 
6156 	if (!ns->ns_nvme->n_idctl->id_oncs.on_dset_mgmt)
6157 		return (ENOTSUP);
6158 
6159 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_DSET_MGMT));
6160 }
6161 
6162 static int
nvme_open(dev_t * devp,int flag,int otyp,cred_t * cred_p)6163 nvme_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
6164 {
6165 #ifndef __lock_lint
6166 	_NOTE(ARGUNUSED(cred_p));
6167 #endif
6168 	nvme_t *nvme;
6169 	nvme_minor_t *minor = NULL;
6170 	uint32_t nsid;
6171 	minor_t m = getminor(*devp);
6172 	int rv = 0;
6173 
6174 	if (otyp != OTYP_CHR)
6175 		return (EINVAL);
6176 
6177 	if (m >= NVME_OPEN_MINOR_MIN)
6178 		return (ENXIO);
6179 
6180 	nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(m));
6181 	nsid = NVME_MINOR_NSID(m);
6182 
6183 	if (nvme == NULL)
6184 		return (ENXIO);
6185 
6186 	if (nsid > MIN(nvme->n_namespace_count, NVME_MINOR_MAX))
6187 		return (ENXIO);
6188 
6189 	if (nvme->n_dead)
6190 		return (EIO);
6191 
6192 	/*
6193 	 * At this point, we're going to allow an open to proceed on this
6194 	 * device. We need to allocate a new instance for this (presuming one is
6195 	 * available).
6196 	 */
6197 	minor = kmem_zalloc(sizeof (nvme_minor_t), KM_NOSLEEP_LAZY);
6198 	if (minor == NULL) {
6199 		return (ENOMEM);
6200 	}
6201 
6202 	cv_init(&minor->nm_cv, NULL, CV_DRIVER, NULL);
6203 	list_link_init(&minor->nm_ctrl_lock.nli_node);
6204 	minor->nm_ctrl_lock.nli_nvme = nvme;
6205 	minor->nm_ctrl_lock.nli_minor = minor;
6206 	list_link_init(&minor->nm_ns_lock.nli_node);
6207 	minor->nm_ns_lock.nli_nvme = nvme;
6208 	minor->nm_ns_lock.nli_minor = minor;
6209 	minor->nm_minor = id_alloc_nosleep(nvme_open_minors);
6210 	if (minor->nm_minor == -1) {
6211 		nvme_minor_free(minor);
6212 		return (ENOSPC);
6213 	}
6214 
6215 	minor->nm_ctrl = nvme;
6216 	if (nsid != 0) {
6217 		minor->nm_ns = nvme_nsid2ns(nvme, nsid);
6218 	}
6219 
6220 	/*
6221 	 * Before we check for exclusive access and attempt a lock if requested,
6222 	 * ensure that this minor is persisted.
6223 	 */
6224 	mutex_enter(&nvme_open_minors_mutex);
6225 	avl_add(&nvme_open_minors_avl, minor);
6226 	mutex_exit(&nvme_open_minors_mutex);
6227 
6228 	/*
6229 	 * A request for opening this FEXCL, is translated into a non-blocking
6230 	 * write lock of the appropriate entity. This honors the original
6231 	 * semantics here. In the future, we should see if we can remove this
6232 	 * and turn a request for FEXCL at open into ENOTSUP.
6233 	 */
6234 	mutex_enter(&nvme->n_minor_mutex);
6235 	if ((flag & FEXCL) != 0) {
6236 		nvme_ioctl_lock_t lock = {
6237 			.nil_level = NVME_LOCK_L_WRITE,
6238 			.nil_flags = NVME_LOCK_F_DONT_BLOCK
6239 		};
6240 
6241 		if (minor->nm_ns != NULL) {
6242 			lock.nil_ent = NVME_LOCK_E_NS;
6243 			lock.nil_common.nioc_nsid = nsid;
6244 		} else {
6245 			lock.nil_ent = NVME_LOCK_E_CTRL;
6246 		}
6247 		nvme_rwlock(minor, &lock);
6248 		if (lock.nil_common.nioc_drv_err != NVME_IOCTL_E_OK) {
6249 			mutex_exit(&nvme->n_minor_mutex);
6250 
6251 			mutex_enter(&nvme_open_minors_mutex);
6252 			avl_remove(&nvme_open_minors_avl, minor);
6253 			mutex_exit(&nvme_open_minors_mutex);
6254 
6255 			nvme_minor_free(minor);
6256 			return (EBUSY);
6257 		}
6258 	}
6259 	mutex_exit(&nvme->n_minor_mutex);
6260 
6261 	*devp = makedevice(getmajor(*devp), (minor_t)minor->nm_minor);
6262 	return (rv);
6263 
6264 }
6265 
6266 static int
nvme_close(dev_t dev,int flag __unused,int otyp,cred_t * cred_p __unused)6267 nvme_close(dev_t dev, int flag __unused, int otyp, cred_t *cred_p __unused)
6268 {
6269 	nvme_minor_t *minor;
6270 	nvme_t *nvme;
6271 
6272 	if (otyp != OTYP_CHR) {
6273 		return (ENXIO);
6274 	}
6275 
6276 	minor = nvme_minor_find_by_dev(dev);
6277 	if (minor == NULL) {
6278 		return (ENXIO);
6279 	}
6280 
6281 	mutex_enter(&nvme_open_minors_mutex);
6282 	avl_remove(&nvme_open_minors_avl, minor);
6283 	mutex_exit(&nvme_open_minors_mutex);
6284 
6285 	/*
6286 	 * When this device is being closed, we must ensure that any locks held
6287 	 * by this are dealt with.
6288 	 */
6289 	nvme = minor->nm_ctrl;
6290 	mutex_enter(&nvme->n_minor_mutex);
6291 	ASSERT3U(minor->nm_ctrl_lock.nli_state, !=, NVME_LOCK_STATE_BLOCKED);
6292 	ASSERT3U(minor->nm_ns_lock.nli_state, !=, NVME_LOCK_STATE_BLOCKED);
6293 
6294 	if (minor->nm_ctrl_lock.nli_state == NVME_LOCK_STATE_ACQUIRED) {
6295 		VERIFY3P(minor->nm_ctrl_lock.nli_lock, !=, NULL);
6296 		nvme_rwunlock(&minor->nm_ctrl_lock,
6297 		    minor->nm_ctrl_lock.nli_lock);
6298 	}
6299 
6300 	if (minor->nm_ns_lock.nli_state == NVME_LOCK_STATE_ACQUIRED) {
6301 		VERIFY3P(minor->nm_ns_lock.nli_lock, !=, NULL);
6302 		nvme_rwunlock(&minor->nm_ns_lock, minor->nm_ns_lock.nli_lock);
6303 	}
6304 	mutex_exit(&nvme->n_minor_mutex);
6305 
6306 	nvme_minor_free(minor);
6307 
6308 	return (0);
6309 }
6310 
6311 void
nvme_ioctl_success(nvme_ioctl_common_t * ioc)6312 nvme_ioctl_success(nvme_ioctl_common_t *ioc)
6313 {
6314 	ioc->nioc_drv_err = NVME_IOCTL_E_OK;
6315 	ioc->nioc_ctrl_sc = NVME_CQE_SC_GEN_SUCCESS;
6316 	ioc->nioc_ctrl_sct = NVME_CQE_SCT_GENERIC;
6317 }
6318 
6319 boolean_t
nvme_ioctl_error(nvme_ioctl_common_t * ioc,nvme_ioctl_errno_t err,uint32_t sct,uint32_t sc)6320 nvme_ioctl_error(nvme_ioctl_common_t *ioc, nvme_ioctl_errno_t err, uint32_t sct,
6321     uint32_t sc)
6322 {
6323 	ioc->nioc_drv_err = err;
6324 	ioc->nioc_ctrl_sct = sct;
6325 	ioc->nioc_ctrl_sc = sc;
6326 
6327 	return (B_FALSE);
6328 }
6329 
6330 static int
nvme_ioctl_copyout_error(nvme_ioctl_errno_t err,intptr_t uaddr,int mode)6331 nvme_ioctl_copyout_error(nvme_ioctl_errno_t err, intptr_t uaddr, int mode)
6332 {
6333 	nvme_ioctl_common_t ioc;
6334 
6335 	ASSERT3U(err, !=, NVME_IOCTL_E_CTRL_ERROR);
6336 	bzero(&ioc, sizeof (ioc));
6337 	if (ddi_copyout(&ioc, (void *)uaddr, sizeof (nvme_ioctl_common_t),
6338 	    mode & FKIOCTL) != 0) {
6339 		return (EFAULT);
6340 	}
6341 	return (0);
6342 }
6343 
6344 /*
6345  * The companion to the namespace checking. This occurs after any rewriting
6346  * occurs. This is the primary point that we attempt to enforce any operation's
6347  * exclusivity. Note, it is theoretically possible for an operation to be
6348  * ongoing and to have someone with an exclusive lock ask to unlock it for some
6349  * reason. This does not maintain the number of such events that are going on.
6350  * While perhaps this is leaving too much up to the user, by the same token we
6351  * don't try to stop them from issuing two different format NVM commands
6352  * targeting the whole device at the same time either, even though the
6353  * controller would really rather that didn't happen.
6354  */
6355 static boolean_t
nvme_ioctl_excl_check(nvme_minor_t * minor,nvme_ioctl_common_t * ioc,const nvme_ioctl_check_t * check)6356 nvme_ioctl_excl_check(nvme_minor_t *minor, nvme_ioctl_common_t *ioc,
6357     const nvme_ioctl_check_t *check)
6358 {
6359 	nvme_t *const nvme = minor->nm_ctrl;
6360 	nvme_namespace_t *ns;
6361 	boolean_t have_ctrl, have_ns, ctrl_is_excl, ns_is_excl;
6362 
6363 	/*
6364 	 * If the command doesn't require anything, then we're done.
6365 	 */
6366 	if (check->nck_excl == NVME_IOCTL_EXCL_SKIP) {
6367 		return (B_TRUE);
6368 	}
6369 
6370 	if (ioc->nioc_nsid == 0 || ioc->nioc_nsid == NVME_NSID_BCAST) {
6371 		ns = NULL;
6372 	} else {
6373 		ns = nvme_nsid2ns(nvme, ioc->nioc_nsid);
6374 	}
6375 
6376 	mutex_enter(&nvme->n_minor_mutex);
6377 	ctrl_is_excl = nvme->n_lock.nl_writer != NULL;
6378 	have_ctrl = nvme->n_lock.nl_writer == &minor->nm_ctrl_lock;
6379 	if (ns != NULL) {
6380 		/*
6381 		 * We explicitly test the namespace lock's writer versus asking
6382 		 * the minor because the minor's namespace lock may apply to a
6383 		 * different namespace.
6384 		 */
6385 		ns_is_excl = ns->ns_lock.nl_writer != NULL;
6386 		have_ns = ns->ns_lock.nl_writer == &minor->nm_ns_lock;
6387 		ASSERT0(have_ctrl && have_ns);
6388 #ifdef	DEBUG
6389 		if (have_ns) {
6390 			ASSERT3P(minor->nm_ns_lock.nli_ns, ==, ns);
6391 		}
6392 #endif
6393 	} else {
6394 		ns_is_excl = B_FALSE;
6395 		have_ns = B_FALSE;
6396 	}
6397 	ASSERT0(ctrl_is_excl && ns_is_excl);
6398 	mutex_exit(&nvme->n_minor_mutex);
6399 
6400 	if (check->nck_excl == NVME_IOCTL_EXCL_CTRL) {
6401 		if (have_ctrl) {
6402 			return (B_TRUE);
6403 		}
6404 
6405 		return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NEED_CTRL_WRLOCK,
6406 		    0, 0));
6407 	}
6408 
6409 	if (check->nck_excl == NVME_IOCTL_EXCL_WRITE) {
6410 		if (ns == NULL) {
6411 			if (have_ctrl) {
6412 				return (B_TRUE);
6413 			}
6414 			return (nvme_ioctl_error(ioc,
6415 			    NVME_IOCTL_E_NEED_CTRL_WRLOCK, 0, 0));
6416 		} else {
6417 			if (have_ctrl || have_ns) {
6418 				return (B_TRUE);
6419 			}
6420 			return (nvme_ioctl_error(ioc,
6421 			    NVME_IOCTL_E_NEED_NS_WRLOCK, 0, 0));
6422 		}
6423 	}
6424 
6425 	/*
6426 	 * Now we have an operation that does not require exclusive access. We
6427 	 * can proceed as long as no one else has it or if someone does it is
6428 	 * us. Regardless of what we target, a controller lock will stop us.
6429 	 */
6430 	if (ctrl_is_excl && !have_ctrl) {
6431 		return (nvme_ioctl_error(ioc, NVME_IOCTL_E_CTRL_LOCKED, 0, 0));
6432 	}
6433 
6434 	/*
6435 	 * Only check namespace exclusivity if we are targeting one.
6436 	 */
6437 	if (ns != NULL && ns_is_excl && !have_ns) {
6438 		return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NS_LOCKED, 0, 0));
6439 	}
6440 
6441 	return (B_TRUE);
6442 }
6443 
6444 /*
6445  * Perform common checking as to whether or not an ioctl operation may proceed.
6446  * We check in this function various aspects of the namespace attributes that
6447  * it's calling on. Once the namespace attributes and any possible rewriting
6448  * have been performed, then we proceed to check whether or not the requisite
6449  * exclusive access is present in nvme_ioctl_excl_check().
6450  */
6451 static boolean_t
nvme_ioctl_check(nvme_minor_t * minor,nvme_ioctl_common_t * ioc,const nvme_ioctl_check_t * check)6452 nvme_ioctl_check(nvme_minor_t *minor, nvme_ioctl_common_t *ioc,
6453     const nvme_ioctl_check_t *check)
6454 {
6455 	/*
6456 	 * If the minor has a namespace pointer, then it is constrained to that
6457 	 * namespace. If a namespace is allowed, then there are only two valid
6458 	 * values that we can find. The first is matching the minor. The second
6459 	 * is our value zero, which will be transformed to the current
6460 	 * namespace.
6461 	 */
6462 	if (minor->nm_ns != NULL) {
6463 		if (!check->nck_ns_ok || !check->nck_ns_minor_ok) {
6464 			return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NOT_CTRL, 0,
6465 			    0));
6466 		}
6467 
6468 		if (ioc->nioc_nsid == 0) {
6469 			ioc->nioc_nsid = minor->nm_ns->ns_id;
6470 		} else if (ioc->nioc_nsid != minor->nm_ns->ns_id) {
6471 			return (nvme_ioctl_error(ioc,
6472 			    NVME_IOCTL_E_MINOR_WRONG_NS, 0, 0));
6473 		}
6474 
6475 		return (nvme_ioctl_excl_check(minor, ioc, check));
6476 	}
6477 
6478 	/*
6479 	 * If we've been told to skip checking the controller, here's where we
6480 	 * do that. This should really only be for commands which use the
6481 	 * namespace ID for listing purposes and therefore can have
6482 	 * traditionally illegal values here.
6483 	 */
6484 	if (check->nck_skip_ctrl) {
6485 		return (nvme_ioctl_excl_check(minor, ioc, check));
6486 	}
6487 
6488 	/*
6489 	 * At this point, we know that we're on the controller's node. We first
6490 	 * deal with the simple case, is a namespace allowed at all or not. If
6491 	 * it is not allowed, then the only acceptable value is zero.
6492 	 */
6493 	if (!check->nck_ns_ok) {
6494 		if (ioc->nioc_nsid != 0) {
6495 			return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NS_UNUSE, 0,
6496 			    0));
6497 		}
6498 
6499 		return (nvme_ioctl_excl_check(minor, ioc, check));
6500 	}
6501 
6502 	/*
6503 	 * At this point, we know that a controller is allowed to use a
6504 	 * namespace. If we haven't been given zero or the broadcast namespace,
6505 	 * check to see if it's actually a valid namespace ID. If is outside of
6506 	 * range, then it is an error. Next, if we have been requested to
6507 	 * rewrite 0 (the this controller indicator) as the broadcast namespace,
6508 	 * do so.
6509 	 *
6510 	 * While we validate that this namespace is within the valid range, we
6511 	 * do not check if it is active or inactive. That is left to our callers
6512 	 * to determine.
6513 	 */
6514 	if (ioc->nioc_nsid > minor->nm_ctrl->n_namespace_count &&
6515 	    ioc->nioc_nsid != NVME_NSID_BCAST) {
6516 		return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NS_RANGE, 0, 0));
6517 	}
6518 
6519 	if (ioc->nioc_nsid == 0 && check->nck_ctrl_rewrite) {
6520 		ioc->nioc_nsid = NVME_NSID_BCAST;
6521 	}
6522 
6523 	/*
6524 	 * Finally, see if we have ended up with a broadcast namespace ID
6525 	 * whether through specification or rewriting. If that is not allowed,
6526 	 * then that is an error.
6527 	 */
6528 	if (!check->nck_bcast_ok && ioc->nioc_nsid == NVME_NSID_BCAST) {
6529 		return (nvme_ioctl_error(ioc, NVME_IOCTL_E_NO_BCAST_NS, 0, 0));
6530 	}
6531 
6532 	return (nvme_ioctl_excl_check(minor, ioc, check));
6533 }
6534 
6535 static int
nvme_ioctl_ctrl_info(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)6536 nvme_ioctl_ctrl_info(nvme_minor_t *minor, intptr_t arg, int mode,
6537     cred_t *cred_p)
6538 {
6539 	nvme_t *const nvme = minor->nm_ctrl;
6540 	nvme_ioctl_ctrl_info_t *info;
6541 	nvme_reg_cap_t cap = { 0 };
6542 	nvme_ioctl_identify_t id = { .nid_cns = NVME_IDENTIFY_CTRL };
6543 	void *idbuf;
6544 
6545 	if ((mode & FREAD) == 0)
6546 		return (EBADF);
6547 
6548 	info = kmem_alloc(sizeof (nvme_ioctl_ctrl_info_t), KM_NOSLEEP_LAZY);
6549 	if (info == NULL) {
6550 		return (nvme_ioctl_copyout_error(NVME_IOCTL_E_NO_KERN_MEM, arg,
6551 		    mode));
6552 	}
6553 
6554 	if (ddi_copyin((void *)arg, info, sizeof (nvme_ioctl_ctrl_info_t),
6555 	    mode & FKIOCTL) != 0) {
6556 		kmem_free(info, sizeof (nvme_ioctl_ctrl_info_t));
6557 		return (EFAULT);
6558 	}
6559 
6560 	if (!nvme_ioctl_check(minor, &info->nci_common,
6561 	    &nvme_check_ctrl_info)) {
6562 		goto copyout;
6563 	}
6564 
6565 	/*
6566 	 * We explicitly do not use the identify controller copy in the kernel
6567 	 * right now so that way we can get a snapshot of the controller's
6568 	 * current capacity and values. While it's tempting to try to use this
6569 	 * to refresh the kernel's version we don't just to simplify the rest of
6570 	 * the driver right now.
6571 	 */
6572 	if (!nvme_identify(nvme, B_TRUE, &id, &idbuf)) {
6573 		info->nci_common = id.nid_common;
6574 		goto copyout;
6575 	}
6576 	bcopy(idbuf, &info->nci_ctrl_id, sizeof (nvme_identify_ctrl_t));
6577 	kmem_free(idbuf, NVME_IDENTIFY_BUFSIZE);
6578 
6579 	/*
6580 	 * Use the kernel's cached common namespace information for this.
6581 	 */
6582 	bcopy(nvme->n_idcomns, &info->nci_common_ns,
6583 	    sizeof (nvme_identify_nsid_t));
6584 
6585 	info->nci_vers = nvme->n_version;
6586 
6587 	/*
6588 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to
6589 	 * specify the base page size of 4k (1<<12), so add 12 here to
6590 	 * get the real page size value.
6591 	 */
6592 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
6593 	info->nci_caps.cap_mpsmax = 1 << (12 + cap.b.cap_mpsmax);
6594 	info->nci_caps.cap_mpsmin = 1 << (12 + cap.b.cap_mpsmin);
6595 
6596 	info->nci_nintrs = (uint32_t)nvme->n_intr_cnt;
6597 
6598 copyout:
6599 	if (ddi_copyout(info, (void *)arg, sizeof (nvme_ioctl_ctrl_info_t),
6600 	    mode & FKIOCTL) != 0) {
6601 		kmem_free(info, sizeof (nvme_ioctl_ctrl_info_t));
6602 		return (EFAULT);
6603 	}
6604 
6605 	kmem_free(info, sizeof (nvme_ioctl_ctrl_info_t));
6606 	return (0);
6607 }
6608 
6609 static int
nvme_ioctl_ns_info(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)6610 nvme_ioctl_ns_info(nvme_minor_t *minor, intptr_t arg, int mode, cred_t *cred_p)
6611 {
6612 	nvme_t *const nvme = minor->nm_ctrl;
6613 	nvme_ioctl_ns_info_t *ns_info;
6614 	nvme_namespace_t *ns;
6615 	nvme_ioctl_identify_t id = { .nid_cns = NVME_IDENTIFY_NSID };
6616 	void *idbuf;
6617 
6618 	if ((mode & FREAD) == 0)
6619 		return (EBADF);
6620 
6621 	ns_info = kmem_zalloc(sizeof (nvme_ioctl_ns_info_t), KM_NOSLEEP_LAZY);
6622 	if (ns_info == NULL) {
6623 		return (nvme_ioctl_copyout_error(NVME_IOCTL_E_NO_KERN_MEM, arg,
6624 		    mode));
6625 	}
6626 
6627 	if (ddi_copyin((void *)arg, ns_info, sizeof (nvme_ioctl_ns_info_t),
6628 	    mode & FKIOCTL) != 0) {
6629 		kmem_free(ns_info, sizeof (nvme_ioctl_ns_info_t));
6630 		return (EFAULT);
6631 	}
6632 
6633 	if (!nvme_ioctl_check(minor, &ns_info->nni_common,
6634 	    &nvme_check_ns_info)) {
6635 		goto copyout;
6636 	}
6637 
6638 	ASSERT3U(ns_info->nni_common.nioc_nsid, >, 0);
6639 	ns = nvme_nsid2ns(nvme, ns_info->nni_common.nioc_nsid);
6640 
6641 	/*
6642 	 * First fetch a fresh copy of the namespace information. Most callers
6643 	 * are using this because they will want a mostly accurate snapshot of
6644 	 * capacity and utilization.
6645 	 */
6646 	id.nid_common.nioc_nsid = ns_info->nni_common.nioc_nsid;
6647 	if (!nvme_identify(nvme, B_TRUE, &id, &idbuf)) {
6648 		ns_info->nni_common = id.nid_common;
6649 		goto copyout;
6650 	}
6651 	bcopy(idbuf, &ns_info->nni_id, sizeof (nvme_identify_nsid_t));
6652 	kmem_free(idbuf, NVME_IDENTIFY_BUFSIZE);
6653 
6654 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
6655 	ns_info->nni_state = ns->ns_state;
6656 	if (ns->ns_state >= NVME_NS_STATE_ATTACHED) {
6657 		const char *addr;
6658 
6659 		ns_info->nni_state = NVME_NS_STATE_ATTACHED;
6660 		addr = bd_address(ns->ns_bd_hdl);
6661 		if (strlcpy(ns_info->nni_addr, addr,
6662 		    sizeof (ns_info->nni_addr)) >= sizeof (ns_info->nni_addr)) {
6663 			nvme_mgmt_unlock(nvme);
6664 			(void) nvme_ioctl_error(&ns_info->nni_common,
6665 			    NVME_IOCTL_E_BD_ADDR_OVER, 0, 0);
6666 			goto copyout;
6667 		}
6668 	}
6669 	nvme_mgmt_unlock(nvme);
6670 
6671 copyout:
6672 	if (ddi_copyout(ns_info, (void *)arg, sizeof (nvme_ioctl_ns_info_t),
6673 	    mode & FKIOCTL) != 0) {
6674 		kmem_free(ns_info, sizeof (nvme_ioctl_ns_info_t));
6675 		return (EFAULT);
6676 	}
6677 
6678 	kmem_free(ns_info, sizeof (nvme_ioctl_ns_info_t));
6679 	return (0);
6680 }
6681 
6682 static int
nvme_ioctl_identify(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)6683 nvme_ioctl_identify(nvme_minor_t *minor, intptr_t arg, int mode, cred_t *cred_p)
6684 {
6685 	_NOTE(ARGUNUSED(cred_p));
6686 	nvme_t *const nvme = minor->nm_ctrl;
6687 	void *idctl;
6688 	uint_t model;
6689 	nvme_ioctl_identify_t id;
6690 #ifdef	_MULTI_DATAMODEL
6691 	nvme_ioctl_identify32_t id32;
6692 #endif
6693 	boolean_t ns_minor;
6694 
6695 	if ((mode & FREAD) == 0)
6696 		return (EBADF);
6697 
6698 	model = ddi_model_convert_from(mode);
6699 	switch (model) {
6700 #ifdef	_MULTI_DATAMODEL
6701 	case DDI_MODEL_ILP32:
6702 		bzero(&id, sizeof (id));
6703 		if (ddi_copyin((void *)arg, &id32, sizeof (id32),
6704 		    mode & FKIOCTL) != 0) {
6705 			return (EFAULT);
6706 		}
6707 		id.nid_common.nioc_nsid = id32.nid_common.nioc_nsid;
6708 		id.nid_cns = id32.nid_cns;
6709 		id.nid_ctrlid = id32.nid_ctrlid;
6710 		id.nid_data = id32.nid_data;
6711 		break;
6712 #endif	/* _MULTI_DATAMODEL */
6713 	case DDI_MODEL_NONE:
6714 		if (ddi_copyin((void *)arg, &id, sizeof (id),
6715 		    mode & FKIOCTL) != 0) {
6716 			return (EFAULT);
6717 		}
6718 		break;
6719 	default:
6720 		return (ENOTSUP);
6721 	}
6722 
6723 	if (!nvme_ioctl_check(minor, &id.nid_common, &nvme_check_identify)) {
6724 		goto copyout;
6725 	}
6726 
6727 	ns_minor = minor->nm_ns != NULL;
6728 	if (!nvme_validate_identify(nvme, &id, ns_minor)) {
6729 		goto copyout;
6730 	}
6731 
6732 	if (nvme_identify(nvme, B_TRUE, &id, &idctl)) {
6733 		int ret = ddi_copyout(idctl, (void *)id.nid_data,
6734 		    NVME_IDENTIFY_BUFSIZE, mode & FKIOCTL);
6735 		kmem_free(idctl, NVME_IDENTIFY_BUFSIZE);
6736 		if (ret != 0) {
6737 			(void) nvme_ioctl_error(&id.nid_common,
6738 			    NVME_IOCTL_E_BAD_USER_DATA, 0, 0);
6739 			goto copyout;
6740 		}
6741 
6742 		nvme_ioctl_success(&id.nid_common);
6743 	}
6744 
6745 copyout:
6746 	switch (model) {
6747 #ifdef	_MULTI_DATAMODEL
6748 	case DDI_MODEL_ILP32:
6749 		id32.nid_common = id.nid_common;
6750 
6751 		if (ddi_copyout(&id32, (void *)arg, sizeof (id32),
6752 		    mode & FKIOCTL) != 0) {
6753 			return (EFAULT);
6754 		}
6755 		break;
6756 #endif	/* _MULTI_DATAMODEL */
6757 	case DDI_MODEL_NONE:
6758 		if (ddi_copyout(&id, (void *)arg, sizeof (id),
6759 		    mode & FKIOCTL) != 0) {
6760 			return (EFAULT);
6761 		}
6762 		break;
6763 	default:
6764 		return (ENOTSUP);
6765 	}
6766 
6767 	return (0);
6768 }
6769 
6770 /*
6771  * Execute commands on behalf of the various ioctls.
6772  *
6773  * If this returns true then the command completed successfully. Otherwise error
6774  * information is returned in the nvme_ioctl_common_t arguments.
6775  */
6776 static boolean_t
nvme_ioc_cmd(nvme_t * nvme,nvme_ioctl_common_t * ioc,nvme_ioc_cmd_args_t * args)6777 nvme_ioc_cmd(nvme_t *nvme, nvme_ioctl_common_t *ioc, nvme_ioc_cmd_args_t *args)
6778 {
6779 	nvme_cmd_t *cmd;
6780 	boolean_t ret = B_FALSE;
6781 
6782 	cmd = nvme_alloc_admin_cmd(nvme, KM_SLEEP);
6783 	cmd->nc_sqid = 0;
6784 
6785 	/*
6786 	 * This function is used to facilitate requests from
6787 	 * userspace, so don't panic if the command fails. This
6788 	 * is especially true for admin passthru commands, where
6789 	 * the actual command data structure is entirely defined
6790 	 * by userspace.
6791 	 */
6792 	cmd->nc_flags |= NVME_CMD_F_DONTPANIC;
6793 
6794 	cmd->nc_callback = nvme_wakeup_cmd;
6795 	cmd->nc_sqe = *args->ica_sqe;
6796 
6797 	if ((args->ica_dma_flags & DDI_DMA_RDWR) != 0) {
6798 		if (args->ica_data == NULL) {
6799 			ret = nvme_ioctl_error(ioc, NVME_IOCTL_E_NO_DMA_MEM,
6800 			    0, 0);
6801 			goto free_cmd;
6802 		}
6803 
6804 		if (nvme_zalloc_dma(nvme, args->ica_data_len,
6805 		    args->ica_dma_flags, &nvme->n_prp_dma_attr, &cmd->nc_dma) !=
6806 		    DDI_SUCCESS) {
6807 			dev_err(nvme->n_dip, CE_WARN,
6808 			    "!nvme_zalloc_dma failed for nvme_ioc_cmd()");
6809 			ret = nvme_ioctl_error(ioc,
6810 			    NVME_IOCTL_E_NO_DMA_MEM, 0, 0);
6811 			goto free_cmd;
6812 		}
6813 
6814 		if (nvme_fill_prp(cmd, cmd->nc_dma->nd_dmah) != 0) {
6815 			ret = nvme_ioctl_error(ioc,
6816 			    NVME_IOCTL_E_NO_DMA_MEM, 0, 0);
6817 			goto free_cmd;
6818 		}
6819 
6820 		if ((args->ica_dma_flags & DDI_DMA_WRITE) != 0 &&
6821 		    ddi_copyin(args->ica_data, cmd->nc_dma->nd_memp,
6822 		    args->ica_data_len, args->ica_copy_flags) != 0) {
6823 			ret = nvme_ioctl_error(ioc, NVME_IOCTL_E_BAD_USER_DATA,
6824 			    0, 0);
6825 			goto free_cmd;
6826 		}
6827 	}
6828 
6829 	nvme_admin_cmd(cmd, args->ica_timeout);
6830 
6831 	if (!nvme_check_cmd_status_ioctl(cmd, ioc)) {
6832 		ret = B_FALSE;
6833 		goto free_cmd;
6834 	}
6835 
6836 	args->ica_cdw0 = cmd->nc_cqe.cqe_dw0;
6837 
6838 	if ((args->ica_dma_flags & DDI_DMA_READ) != 0 &&
6839 	    ddi_copyout(cmd->nc_dma->nd_memp, args->ica_data,
6840 	    args->ica_data_len, args->ica_copy_flags) != 0) {
6841 		ret = nvme_ioctl_error(ioc, NVME_IOCTL_E_BAD_USER_DATA, 0, 0);
6842 		goto free_cmd;
6843 	}
6844 
6845 	ret = B_TRUE;
6846 	nvme_ioctl_success(ioc);
6847 
6848 free_cmd:
6849 	nvme_free_cmd(cmd);
6850 
6851 	return (ret);
6852 }
6853 
6854 static int
nvme_ioctl_get_logpage(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)6855 nvme_ioctl_get_logpage(nvme_minor_t *minor, intptr_t arg, int mode,
6856     cred_t *cred_p)
6857 {
6858 	nvme_t *const nvme = minor->nm_ctrl;
6859 	void *buf;
6860 	nvme_ioctl_get_logpage_t log;
6861 	uint_t model;
6862 #ifdef	_MULTI_DATAMODEL
6863 	nvme_ioctl_get_logpage32_t log32;
6864 #endif
6865 
6866 	if ((mode & FREAD) == 0) {
6867 		return (EBADF);
6868 	}
6869 
6870 	model = ddi_model_convert_from(mode);
6871 	switch (model) {
6872 #ifdef	_MULTI_DATAMODEL
6873 	case DDI_MODEL_ILP32:
6874 		bzero(&log, sizeof (log));
6875 		if (ddi_copyin((void *)arg, &log32, sizeof (log32),
6876 		    mode & FKIOCTL) != 0) {
6877 			return (EFAULT);
6878 		}
6879 
6880 		log.nigl_common.nioc_nsid = log32.nigl_common.nioc_nsid;
6881 		log.nigl_csi = log32.nigl_csi;
6882 		log.nigl_lid = log32.nigl_lid;
6883 		log.nigl_lsp = log32.nigl_lsp;
6884 		log.nigl_len = log32.nigl_len;
6885 		log.nigl_offset = log32.nigl_offset;
6886 		log.nigl_data = log32.nigl_data;
6887 		break;
6888 #endif	/* _MULTI_DATAMODEL */
6889 	case DDI_MODEL_NONE:
6890 		if (ddi_copyin((void *)arg, &log, sizeof (log),
6891 		    mode & FKIOCTL) != 0) {
6892 			return (EFAULT);
6893 		}
6894 		break;
6895 	default:
6896 		return (ENOTSUP);
6897 	}
6898 
6899 	/*
6900 	 * Eventually we'd like to do a soft lock on the namespaces from
6901 	 * changing out from us during this operation in the future. But we
6902 	 * haven't implemented that yet.
6903 	 */
6904 	if (!nvme_ioctl_check(minor, &log.nigl_common,
6905 	    &nvme_check_get_logpage)) {
6906 		goto copyout;
6907 	}
6908 
6909 	if (!nvme_validate_logpage(nvme, &log)) {
6910 		goto copyout;
6911 	}
6912 
6913 	if (nvme_get_logpage(nvme, B_TRUE, &log, &buf)) {
6914 		int copy;
6915 
6916 		copy = ddi_copyout(buf, (void *)log.nigl_data, log.nigl_len,
6917 		    mode & FKIOCTL);
6918 		kmem_free(buf, log.nigl_len);
6919 		if (copy != 0) {
6920 			(void) nvme_ioctl_error(&log.nigl_common,
6921 			    NVME_IOCTL_E_BAD_USER_DATA, 0, 0);
6922 			goto copyout;
6923 		}
6924 
6925 		nvme_ioctl_success(&log.nigl_common);
6926 	}
6927 
6928 copyout:
6929 	switch (model) {
6930 #ifdef	_MULTI_DATAMODEL
6931 	case DDI_MODEL_ILP32:
6932 		bzero(&log32, sizeof (log32));
6933 
6934 		log32.nigl_common = log.nigl_common;
6935 		log32.nigl_csi = log.nigl_csi;
6936 		log32.nigl_lid = log.nigl_lid;
6937 		log32.nigl_lsp = log.nigl_lsp;
6938 		log32.nigl_len = log.nigl_len;
6939 		log32.nigl_offset = log.nigl_offset;
6940 		log32.nigl_data = log.nigl_data;
6941 		if (ddi_copyout(&log32, (void *)arg, sizeof (log32),
6942 		    mode & FKIOCTL) != 0) {
6943 			return (EFAULT);
6944 		}
6945 		break;
6946 #endif	/* _MULTI_DATAMODEL */
6947 	case DDI_MODEL_NONE:
6948 		if (ddi_copyout(&log, (void *)arg, sizeof (log),
6949 		    mode & FKIOCTL) != 0) {
6950 			return (EFAULT);
6951 		}
6952 		break;
6953 	default:
6954 		return (ENOTSUP);
6955 	}
6956 
6957 	return (0);
6958 }
6959 
6960 static int
nvme_ioctl_get_feature(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)6961 nvme_ioctl_get_feature(nvme_minor_t *minor, intptr_t arg, int mode,
6962     cred_t *cred_p)
6963 {
6964 	nvme_t *const nvme = minor->nm_ctrl;
6965 	nvme_ioctl_get_feature_t feat;
6966 	uint_t model;
6967 #ifdef	_MULTI_DATAMODEL
6968 	nvme_ioctl_get_feature32_t feat32;
6969 #endif
6970 	nvme_get_features_dw10_t gf_dw10 = { 0 };
6971 	nvme_ioc_cmd_args_t args = { NULL };
6972 	nvme_sqe_t sqe = {
6973 	    .sqe_opc	= NVME_OPC_GET_FEATURES
6974 	};
6975 
6976 	if ((mode & FREAD) == 0) {
6977 		return (EBADF);
6978 	}
6979 
6980 	model = ddi_model_convert_from(mode);
6981 	switch (model) {
6982 #ifdef	_MULTI_DATAMODEL
6983 	case DDI_MODEL_ILP32:
6984 		bzero(&feat, sizeof (feat));
6985 		if (ddi_copyin((void *)arg, &feat32, sizeof (feat32),
6986 		    mode & FKIOCTL) != 0) {
6987 			return (EFAULT);
6988 		}
6989 
6990 		feat.nigf_common.nioc_nsid = feat32.nigf_common.nioc_nsid;
6991 		feat.nigf_fid = feat32.nigf_fid;
6992 		feat.nigf_sel = feat32.nigf_sel;
6993 		feat.nigf_cdw11 = feat32.nigf_cdw11;
6994 		feat.nigf_data = feat32.nigf_data;
6995 		feat.nigf_len = feat32.nigf_len;
6996 		break;
6997 #endif	/* _MULTI_DATAMODEL */
6998 	case DDI_MODEL_NONE:
6999 		if (ddi_copyin((void *)arg, &feat, sizeof (feat),
7000 		    mode & FKIOCTL) != 0) {
7001 			return (EFAULT);
7002 		}
7003 		break;
7004 	default:
7005 		return (ENOTSUP);
7006 	}
7007 
7008 	if (!nvme_ioctl_check(minor, &feat.nigf_common,
7009 	    &nvme_check_get_feature)) {
7010 		goto copyout;
7011 	}
7012 
7013 	if (!nvme_validate_get_feature(nvme, &feat)) {
7014 		goto copyout;
7015 	}
7016 
7017 	gf_dw10.b.gt_fid = bitx32(feat.nigf_fid, 7, 0);
7018 	gf_dw10.b.gt_sel = bitx32(feat.nigf_sel, 2, 0);
7019 	sqe.sqe_cdw10 = gf_dw10.r;
7020 	sqe.sqe_cdw11 = feat.nigf_cdw11;
7021 	sqe.sqe_nsid = feat.nigf_common.nioc_nsid;
7022 
7023 	args.ica_sqe = &sqe;
7024 	if (feat.nigf_len != 0) {
7025 		args.ica_data = (void *)feat.nigf_data;
7026 		args.ica_data_len = feat.nigf_len;
7027 		args.ica_dma_flags = DDI_DMA_READ;
7028 	}
7029 	args.ica_copy_flags = mode;
7030 	args.ica_timeout = nvme_admin_cmd_timeout;
7031 
7032 	if (!nvme_ioc_cmd(nvme, &feat.nigf_common, &args)) {
7033 		goto copyout;
7034 	}
7035 
7036 	feat.nigf_cdw0 = args.ica_cdw0;
7037 
7038 copyout:
7039 	switch (model) {
7040 #ifdef	_MULTI_DATAMODEL
7041 	case DDI_MODEL_ILP32:
7042 		bzero(&feat32, sizeof (feat32));
7043 
7044 		feat32.nigf_common = feat.nigf_common;
7045 		feat32.nigf_fid = feat.nigf_fid;
7046 		feat32.nigf_sel = feat.nigf_sel;
7047 		feat32.nigf_cdw11 = feat.nigf_cdw11;
7048 		feat32.nigf_data = feat.nigf_data;
7049 		feat32.nigf_len = feat.nigf_len;
7050 		feat32.nigf_cdw0 = feat.nigf_cdw0;
7051 		if (ddi_copyout(&feat32, (void *)arg, sizeof (feat32),
7052 		    mode & FKIOCTL) != 0) {
7053 			return (EFAULT);
7054 		}
7055 		break;
7056 #endif	/* _MULTI_DATAMODEL */
7057 	case DDI_MODEL_NONE:
7058 		if (ddi_copyout(&feat, (void *)arg, sizeof (feat),
7059 		    mode & FKIOCTL) != 0) {
7060 			return (EFAULT);
7061 		}
7062 		break;
7063 	default:
7064 		return (ENOTSUP);
7065 	}
7066 
7067 	return (0);
7068 }
7069 
7070 static int
nvme_ioctl_format(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7071 nvme_ioctl_format(nvme_minor_t *minor, intptr_t arg, int mode, cred_t *cred_p)
7072 {
7073 	nvme_t *const nvme = minor->nm_ctrl;
7074 	nvme_ioctl_format_t ioc;
7075 
7076 	if ((mode & FWRITE) == 0)
7077 		return (EBADF);
7078 
7079 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7080 		return (EPERM);
7081 
7082 	if (ddi_copyin((void *)(uintptr_t)arg, &ioc,
7083 	    sizeof (nvme_ioctl_format_t), mode & FKIOCTL) != 0)
7084 		return (EFAULT);
7085 
7086 	if (!nvme_ioctl_check(minor, &ioc.nif_common, &nvme_check_format)) {
7087 		goto copyout;
7088 	}
7089 
7090 	if (!nvme_validate_format(nvme, &ioc)) {
7091 		goto copyout;
7092 	}
7093 
7094 	/*
7095 	 * The broadcast namespace can format all namespaces attached to the
7096 	 * controller, meaning active namespaces. However, a targeted format can
7097 	 * impact any allocated namespace, even one not attached. As such, we
7098 	 * need different checks for each situation.
7099 	 */
7100 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7101 	if (ioc.nif_common.nioc_nsid == NVME_NSID_BCAST) {
7102 		if (!nvme_no_blkdev_attached(nvme, ioc.nif_common.nioc_nsid)) {
7103 			nvme_mgmt_unlock(nvme);
7104 			(void) nvme_ioctl_error(&ioc.nif_common,
7105 			    NVME_IOCTL_E_NS_BLKDEV_ATTACH, 0, 0);
7106 			goto copyout;
7107 		}
7108 	} else {
7109 		nvme_namespace_t *ns = nvme_nsid2ns(nvme,
7110 		    ioc.nif_common.nioc_nsid);
7111 
7112 		if (!nvme_ns_state_check(ns, &ioc.nif_common,
7113 		    nvme_format_nvm_states)) {
7114 			nvme_mgmt_unlock(nvme);
7115 			goto copyout;
7116 		}
7117 	}
7118 
7119 	if (nvme_format_nvm(nvme, &ioc)) {
7120 		nvme_ioctl_success(&ioc.nif_common);
7121 		nvme_rescan_ns(nvme, ioc.nif_common.nioc_nsid);
7122 	}
7123 	nvme_mgmt_unlock(nvme);
7124 
7125 copyout:
7126 	if (ddi_copyout(&ioc, (void *)(uintptr_t)arg, sizeof (ioc),
7127 	    mode & FKIOCTL) != 0) {
7128 		return (EFAULT);
7129 	}
7130 
7131 	return (0);
7132 }
7133 
7134 static int
nvme_ioctl_bd_detach(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7135 nvme_ioctl_bd_detach(nvme_minor_t *minor, intptr_t arg, int mode,
7136     cred_t *cred_p)
7137 {
7138 	nvme_t *const nvme = minor->nm_ctrl;
7139 	nvme_ioctl_common_t com;
7140 
7141 	if ((mode & FWRITE) == 0)
7142 		return (EBADF);
7143 
7144 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7145 		return (EPERM);
7146 
7147 	if (ddi_copyin((void *)(uintptr_t)arg, &com, sizeof (com),
7148 	    mode & FKIOCTL) != 0) {
7149 		return (EFAULT);
7150 	}
7151 
7152 	if (!nvme_ioctl_check(minor, &com, &nvme_check_attach_detach)) {
7153 		goto copyout;
7154 	}
7155 
7156 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7157 	if (nvme_bd_detach_ns(nvme, &com)) {
7158 		nvme_ioctl_success(&com);
7159 	}
7160 	nvme_mgmt_unlock(nvme);
7161 
7162 copyout:
7163 	if (ddi_copyout(&com, (void *)(uintptr_t)arg, sizeof (com),
7164 	    mode & FKIOCTL) != 0) {
7165 		return (EFAULT);
7166 	}
7167 
7168 	return (0);
7169 }
7170 
7171 static int
nvme_ioctl_bd_attach(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7172 nvme_ioctl_bd_attach(nvme_minor_t *minor, intptr_t arg, int mode,
7173     cred_t *cred_p)
7174 {
7175 	nvme_t *const nvme = minor->nm_ctrl;
7176 	nvme_ioctl_common_t com;
7177 	nvme_namespace_t *ns;
7178 
7179 	if ((mode & FWRITE) == 0)
7180 		return (EBADF);
7181 
7182 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7183 		return (EPERM);
7184 
7185 	if (ddi_copyin((void *)(uintptr_t)arg, &com, sizeof (com),
7186 	    mode & FKIOCTL) != 0) {
7187 		return (EFAULT);
7188 	}
7189 
7190 	if (!nvme_ioctl_check(minor, &com, &nvme_check_attach_detach)) {
7191 		goto copyout;
7192 	}
7193 
7194 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7195 	ns = nvme_nsid2ns(nvme, com.nioc_nsid);
7196 
7197 	/*
7198 	 * Strictly speaking we shouldn't need to call nvme_init_ns() here as
7199 	 * we should be properly refreshing the internal state when we are
7200 	 * issuing commands that change things. However, we opt to still do so
7201 	 * as a bit of a safety check lest we give the kernel something bad or a
7202 	 * vendor unique command somehow did something behind our backs.
7203 	 */
7204 	if (ns->ns_state < NVME_NS_STATE_ATTACHED) {
7205 		nvme_rescan_ns(nvme, com.nioc_nsid);
7206 	}
7207 
7208 	if (nvme_bd_attach_ns(nvme, &com)) {
7209 		nvme_ioctl_success(&com);
7210 	}
7211 	nvme_mgmt_unlock(nvme);
7212 
7213 copyout:
7214 	if (ddi_copyout(&com, (void *)(uintptr_t)arg, sizeof (com),
7215 	    mode & FKIOCTL) != 0) {
7216 		return (EFAULT);
7217 	}
7218 
7219 	return (0);
7220 }
7221 
7222 /*
7223  * Attach or detach a controller from the specified namespace. While this in
7224  * theory allows for multiple controllers to be specified, currently we only
7225  * support using the controller that we've issued this ioctl on. In the future
7226  * when we have better ways to test dual-attached controllers then this should
7227  * be extended to take the controller list from userland.
7228  */
7229 static boolean_t
nvme_ctrl_attach_detach_ns(nvme_t * nvme,nvme_namespace_t * ns,nvme_ioctl_common_t * ioc,boolean_t attach)7230 nvme_ctrl_attach_detach_ns(nvme_t *nvme, nvme_namespace_t *ns,
7231     nvme_ioctl_common_t *ioc, boolean_t attach)
7232 {
7233 	nvme_ioc_cmd_args_t args = { NULL };
7234 	nvme_sqe_t sqe;
7235 	nvme_ns_mgmt_dw10_t dw10;
7236 	uint16_t ctrlids[2];
7237 
7238 	ASSERT(nvme_mgmt_lock_held(nvme));
7239 
7240 	bzero(&sqe, sizeof (sqe));
7241 	sqe.sqe_nsid = ioc->nioc_nsid;
7242 	sqe.sqe_opc = NVME_OPC_NS_ATTACH;
7243 
7244 	dw10.r = 0;
7245 	dw10.b.nsm_sel = attach ? NVME_NS_ATTACH_CTRL_ATTACH :
7246 	    NVME_NS_ATTACH_CTRL_DETACH;
7247 	sqe.sqe_cdw10 = dw10.r;
7248 
7249 	/*
7250 	 * As we only support sending our current controller's id along, we can
7251 	 * simplify this and don't need both allocating a full
7252 	 * nvme_identify_ctrl_list_t for two items.
7253 	 */
7254 	ctrlids[0] = 1;
7255 	ctrlids[1] = nvme->n_idctl->id_cntlid;
7256 
7257 	args.ica_sqe = &sqe;
7258 	args.ica_data = ctrlids;
7259 	args.ica_data_len = sizeof (ctrlids);
7260 	args.ica_dma_flags = DDI_DMA_WRITE;
7261 	args.ica_copy_flags = FKIOCTL;
7262 	args.ica_timeout = nvme_admin_cmd_timeout;
7263 
7264 	return (nvme_ioc_cmd(nvme, ioc, &args));
7265 }
7266 
7267 static int
nvme_ioctl_ctrl_detach(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7268 nvme_ioctl_ctrl_detach(nvme_minor_t *minor, intptr_t arg, int mode,
7269     cred_t *cred_p)
7270 {
7271 	nvme_t *const nvme = minor->nm_ctrl;
7272 	nvme_ioctl_common_t com;
7273 	nvme_namespace_t *ns;
7274 
7275 	if ((mode & FWRITE) == 0)
7276 		return (EBADF);
7277 
7278 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7279 		return (EPERM);
7280 
7281 	if (ddi_copyin((void *)(uintptr_t)arg, &com, sizeof (com),
7282 	    mode & FKIOCTL) != 0) {
7283 		return (EFAULT);
7284 	}
7285 
7286 	if (!nvme_ioctl_check(minor, &com, &nvme_check_attach_detach)) {
7287 		goto copyout;
7288 	}
7289 
7290 	if (!nvme_validate_ctrl_attach_detach_ns(nvme, &com)) {
7291 		goto copyout;
7292 	}
7293 
7294 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7295 	ns = nvme_nsid2ns(nvme, com.nioc_nsid);
7296 
7297 	if (nvme_ns_state_check(ns, &com, nvme_ctrl_detach_states)) {
7298 		if (nvme_ctrl_attach_detach_ns(nvme, ns, &com, B_FALSE)) {
7299 			nvme_rescan_ns(nvme, com.nioc_nsid);
7300 			nvme_ioctl_success(&com);
7301 		}
7302 	}
7303 	nvme_mgmt_unlock(nvme);
7304 
7305 copyout:
7306 	if (ddi_copyout(&com, (void *)(uintptr_t)arg, sizeof (com),
7307 	    mode & FKIOCTL) != 0) {
7308 		return (EFAULT);
7309 	}
7310 
7311 	return (0);
7312 }
7313 
7314 static int
nvme_ioctl_ns_create(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7315 nvme_ioctl_ns_create(nvme_minor_t *minor, intptr_t arg, int mode,
7316     cred_t *cred_p)
7317 {
7318 	nvme_t *const nvme = minor->nm_ctrl;
7319 	nvme_ioctl_ns_create_t create;
7320 
7321 	if ((mode & FWRITE) == 0)
7322 		return (EBADF);
7323 
7324 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7325 		return (EPERM);
7326 
7327 	if (ddi_copyin((void *)(uintptr_t)arg, &create, sizeof (create),
7328 	    mode & FKIOCTL) != 0) {
7329 		return (EFAULT);
7330 	}
7331 
7332 	if (!nvme_ioctl_check(minor, &create.nnc_common,
7333 	    &nvme_check_ns_create)) {
7334 		goto copyout;
7335 	}
7336 
7337 	if (!nvme_validate_ns_create(nvme, &create)) {
7338 		goto copyout;
7339 	}
7340 
7341 	/*
7342 	 * Now that we've validated this, proceed to build up the actual data
7343 	 * request. We need to fill out the relevant identify namespace data
7344 	 * structure fields.
7345 	 */
7346 	nvme_identify_nsid_t *idns = kmem_zalloc(sizeof (nvme_identify_nsid_t),
7347 	    KM_NOSLEEP_LAZY);
7348 	if (idns == NULL) {
7349 		(void) nvme_ioctl_error(&create.nnc_common,
7350 		    NVME_IOCTL_E_NO_KERN_MEM, 0, 0);
7351 		goto copyout;
7352 	}
7353 
7354 	idns->id_nsize = create.nnc_nsze;
7355 	idns->id_ncap = create.nnc_ncap;
7356 	idns->id_flbas.lba_format = create.nnc_flbas;
7357 	idns->id_nmic.nm_shared = bitx32(create.nnc_nmic, 0, 0);
7358 
7359 	nvme_ioc_cmd_args_t args = { NULL };
7360 	nvme_sqe_t sqe;
7361 	nvme_ns_mgmt_dw10_t dw10;
7362 	nvme_ns_mgmt_dw11_t dw11;
7363 
7364 	bzero(&sqe, sizeof (sqe));
7365 	sqe.sqe_nsid = create.nnc_common.nioc_nsid;
7366 	sqe.sqe_opc = NVME_OPC_NS_MGMT;
7367 
7368 	dw10.r = 0;
7369 	dw10.b.nsm_sel = NVME_NS_MGMT_NS_CREATE;
7370 	sqe.sqe_cdw10 = dw10.r;
7371 
7372 	dw11.r = 0;
7373 	dw11.b.nsm_csi = create.nnc_csi;
7374 	sqe.sqe_cdw11 = dw11.r;
7375 
7376 	args.ica_sqe = &sqe;
7377 	args.ica_data = idns;
7378 	args.ica_data_len = sizeof (nvme_identify_nsid_t);
7379 	args.ica_dma_flags = DDI_DMA_WRITE;
7380 	args.ica_copy_flags = FKIOCTL;
7381 	args.ica_timeout = nvme_format_cmd_timeout;
7382 
7383 	/*
7384 	 * This command manipulates our understanding of a namespace's state.
7385 	 * While we don't need to check anything before we proceed, we still
7386 	 * logically require the lock.
7387 	 */
7388 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7389 	if (nvme_ioc_cmd(nvme, &create.nnc_common, &args)) {
7390 		create.nnc_nsid = args.ica_cdw0;
7391 		nvme_rescan_ns(nvme, create.nnc_nsid);
7392 		nvme_ioctl_success(&create.nnc_common);
7393 	}
7394 	nvme_mgmt_unlock(nvme);
7395 	kmem_free(idns, sizeof (nvme_identify_nsid_t));
7396 
7397 copyout:
7398 	if (ddi_copyout(&create, (void *)(uintptr_t)arg, sizeof (create),
7399 	    mode & FKIOCTL) != 0) {
7400 		return (EFAULT);
7401 	}
7402 
7403 	return (0);
7404 
7405 }
7406 
7407 static int
nvme_ioctl_ns_delete(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7408 nvme_ioctl_ns_delete(nvme_minor_t *minor, intptr_t arg, int mode,
7409     cred_t *cred_p)
7410 {
7411 	nvme_t *const nvme = minor->nm_ctrl;
7412 	nvme_ioctl_common_t com;
7413 
7414 	if ((mode & FWRITE) == 0)
7415 		return (EBADF);
7416 
7417 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7418 		return (EPERM);
7419 
7420 	if (ddi_copyin((void *)(uintptr_t)arg, &com, sizeof (com),
7421 	    mode & FKIOCTL) != 0) {
7422 		return (EFAULT);
7423 	}
7424 
7425 	if (!nvme_ioctl_check(minor, &com, &nvme_check_ns_delete)) {
7426 		goto copyout;
7427 	}
7428 
7429 	if (!nvme_validate_ns_delete(nvme, &com)) {
7430 		goto copyout;
7431 	}
7432 
7433 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7434 	if (com.nioc_nsid == NVME_NSID_BCAST) {
7435 		if (!nvme_no_blkdev_attached(nvme, com.nioc_nsid)) {
7436 			nvme_mgmt_unlock(nvme);
7437 			(void) nvme_ioctl_error(&com,
7438 			    NVME_IOCTL_E_NS_BLKDEV_ATTACH, 0, 0);
7439 			goto copyout;
7440 		}
7441 	} else {
7442 		nvme_namespace_t *ns = nvme_nsid2ns(nvme, com.nioc_nsid);
7443 
7444 		if (!nvme_ns_state_check(ns, &com, nvme_ns_delete_states)) {
7445 			nvme_mgmt_unlock(nvme);
7446 			goto copyout;
7447 		}
7448 	}
7449 
7450 	nvme_ioc_cmd_args_t args = { NULL };
7451 	nvme_sqe_t sqe;
7452 	nvme_ns_mgmt_dw10_t dw10;
7453 
7454 	bzero(&sqe, sizeof (sqe));
7455 	sqe.sqe_nsid = com.nioc_nsid;
7456 	sqe.sqe_opc = NVME_OPC_NS_MGMT;
7457 
7458 	dw10.r = 0;
7459 	dw10.b.nsm_sel = NVME_NS_MGMT_NS_DELETE;
7460 	sqe.sqe_cdw10 = dw10.r;
7461 
7462 	args.ica_sqe = &sqe;
7463 	args.ica_data = NULL;
7464 	args.ica_data_len = 0;
7465 	args.ica_dma_flags = 0;
7466 	args.ica_copy_flags = 0;
7467 	args.ica_timeout = nvme_format_cmd_timeout;
7468 
7469 	if (nvme_ioc_cmd(nvme, &com, &args)) {
7470 		nvme_rescan_ns(nvme, com.nioc_nsid);
7471 		nvme_ioctl_success(&com);
7472 	}
7473 	nvme_mgmt_unlock(nvme);
7474 
7475 copyout:
7476 	if (ddi_copyout(&com, (void *)(uintptr_t)arg, sizeof (com),
7477 	    mode & FKIOCTL) != 0) {
7478 		return (EFAULT);
7479 	}
7480 
7481 	return (0);
7482 }
7483 
7484 static int
nvme_ioctl_ctrl_attach(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7485 nvme_ioctl_ctrl_attach(nvme_minor_t *minor, intptr_t arg, int mode,
7486     cred_t *cred_p)
7487 {
7488 	nvme_t *const nvme = minor->nm_ctrl;
7489 	nvme_ioctl_common_t com;
7490 	nvme_namespace_t *ns;
7491 
7492 	if ((mode & FWRITE) == 0)
7493 		return (EBADF);
7494 
7495 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7496 		return (EPERM);
7497 
7498 	if (ddi_copyin((void *)(uintptr_t)arg, &com, sizeof (com),
7499 	    mode & FKIOCTL) != 0) {
7500 		return (EFAULT);
7501 	}
7502 
7503 	if (!nvme_ioctl_check(minor, &com, &nvme_check_attach_detach)) {
7504 		goto copyout;
7505 	}
7506 
7507 	if (!nvme_validate_ctrl_attach_detach_ns(nvme, &com)) {
7508 		goto copyout;
7509 	}
7510 
7511 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7512 	ns = nvme_nsid2ns(nvme, com.nioc_nsid);
7513 
7514 	if (nvme_ns_state_check(ns, &com, nvme_ctrl_attach_states)) {
7515 		if (nvme_ctrl_attach_detach_ns(nvme, ns, &com, B_TRUE)) {
7516 			nvme_rescan_ns(nvme, com.nioc_nsid);
7517 			nvme_ioctl_success(&com);
7518 		}
7519 	}
7520 	nvme_mgmt_unlock(nvme);
7521 
7522 copyout:
7523 	if (ddi_copyout(&com, (void *)(uintptr_t)arg, sizeof (com),
7524 	    mode & FKIOCTL) != 0) {
7525 		return (EFAULT);
7526 	}
7527 
7528 	return (0);
7529 }
7530 
7531 static void
nvme_ufm_update(nvme_t * nvme)7532 nvme_ufm_update(nvme_t *nvme)
7533 {
7534 	mutex_enter(&nvme->n_fwslot_mutex);
7535 	ddi_ufm_update(nvme->n_ufmh);
7536 	if (nvme->n_fwslot != NULL) {
7537 		kmem_free(nvme->n_fwslot, sizeof (nvme_fwslot_log_t));
7538 		nvme->n_fwslot = NULL;
7539 	}
7540 	mutex_exit(&nvme->n_fwslot_mutex);
7541 }
7542 
7543 /*
7544  * Download new firmware to the device's internal staging area. We do not call
7545  * nvme_ufm_update() here because after a firmware download, there has been no
7546  * change to any of the actual persistent firmware data. That requires a
7547  * subsequent ioctl (NVME_IOC_FIRMWARE_COMMIT) to commit the firmware to a slot
7548  * or to activate a slot.
7549  */
7550 static int
nvme_ioctl_firmware_download(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7551 nvme_ioctl_firmware_download(nvme_minor_t *minor, intptr_t arg, int mode,
7552     cred_t *cred_p)
7553 {
7554 	nvme_t *const nvme = minor->nm_ctrl;
7555 	nvme_ioctl_fw_load_t fw;
7556 	uint64_t len, maxcopy;
7557 	offset_t offset;
7558 	uint32_t gran;
7559 	nvme_valid_ctrl_data_t data;
7560 	uintptr_t buf;
7561 	nvme_sqe_t sqe = {
7562 	    .sqe_opc	= NVME_OPC_FW_IMAGE_LOAD
7563 	};
7564 
7565 	if ((mode & FWRITE) == 0)
7566 		return (EBADF);
7567 
7568 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7569 		return (EPERM);
7570 
7571 	if (ddi_copyin((void *)(uintptr_t)arg, &fw, sizeof (fw),
7572 	    mode & FKIOCTL) != 0) {
7573 		return (EFAULT);
7574 	}
7575 
7576 	if (!nvme_ioctl_check(minor, &fw.fwl_common, &nvme_check_firmware)) {
7577 		goto copyout;
7578 	}
7579 
7580 	if (!nvme_validate_fw_load(nvme, &fw)) {
7581 		goto copyout;
7582 	}
7583 
7584 	len = fw.fwl_len;
7585 	offset = fw.fwl_off;
7586 	buf = fw.fwl_buf;
7587 
7588 	/*
7589 	 * We need to determine the minimum and maximum amount of data that we
7590 	 * will send to the device in a given go. Starting in NMVe 1.3 this must
7591 	 * be a multiple of the firmware update granularity (FWUG), but must not
7592 	 * exceed the maximum data transfer that we've set. Many devices don't
7593 	 * report something here, which means we'll end up getting our default
7594 	 * value. Our policy is a little simple, but it's basically if the
7595 	 * maximum data transfer is evenly divided by the granularity, then use
7596 	 * it. Otherwise we use the granularity itself. The granularity is
7597 	 * always in page sized units, so trying to find another optimum point
7598 	 * isn't worth it. If we encounter a contradiction, then we will have to
7599 	 * error out.
7600 	 */
7601 	data.vcd_vers = &nvme->n_version;
7602 	data.vcd_id = nvme->n_idctl;
7603 	gran = nvme_fw_load_granularity(&data);
7604 
7605 	if ((nvme->n_max_data_transfer_size % gran) == 0) {
7606 		maxcopy = nvme->n_max_data_transfer_size;
7607 	} else if (gran <= nvme->n_max_data_transfer_size) {
7608 		maxcopy = gran;
7609 	} else {
7610 		(void) nvme_ioctl_error(&fw.fwl_common,
7611 		    NVME_IOCTL_E_FW_LOAD_IMPOS_GRAN, 0, 0);
7612 		goto copyout;
7613 	}
7614 
7615 	while (len > 0) {
7616 		nvme_ioc_cmd_args_t args = { NULL };
7617 		uint64_t copylen = MIN(maxcopy, len);
7618 
7619 		sqe.sqe_cdw10 = (uint32_t)(copylen >> NVME_DWORD_SHIFT) - 1;
7620 		sqe.sqe_cdw11 = (uint32_t)(offset >> NVME_DWORD_SHIFT);
7621 
7622 		args.ica_sqe = &sqe;
7623 		args.ica_data = (void *)buf;
7624 		args.ica_data_len = copylen;
7625 		args.ica_dma_flags = DDI_DMA_WRITE;
7626 		args.ica_copy_flags = mode;
7627 		args.ica_timeout = nvme_admin_cmd_timeout;
7628 
7629 		if (!nvme_ioc_cmd(nvme, &fw.fwl_common, &args)) {
7630 			break;
7631 		}
7632 
7633 		buf += copylen;
7634 		offset += copylen;
7635 		len -= copylen;
7636 	}
7637 
7638 copyout:
7639 	if (ddi_copyout(&fw, (void *)(uintptr_t)arg, sizeof (fw),
7640 	    mode & FKIOCTL) != 0) {
7641 		return (EFAULT);
7642 	}
7643 
7644 	return (0);
7645 }
7646 
7647 static int
nvme_ioctl_firmware_commit(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7648 nvme_ioctl_firmware_commit(nvme_minor_t *minor, intptr_t arg, int mode,
7649     cred_t *cred_p)
7650 {
7651 	nvme_t *const nvme = minor->nm_ctrl;
7652 	nvme_ioctl_fw_commit_t fw;
7653 	nvme_firmware_commit_dw10_t fc_dw10 = { 0 };
7654 	nvme_ioc_cmd_args_t args = { NULL };
7655 	nvme_sqe_t sqe = {
7656 	    .sqe_opc	= NVME_OPC_FW_ACTIVATE
7657 	};
7658 
7659 	if ((mode & FWRITE) == 0)
7660 		return (EBADF);
7661 
7662 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7663 		return (EPERM);
7664 
7665 	if (ddi_copyin((void *)(uintptr_t)arg, &fw, sizeof (fw),
7666 	    mode & FKIOCTL) != 0) {
7667 		return (EFAULT);
7668 	}
7669 
7670 	if (!nvme_ioctl_check(minor, &fw.fwc_common, &nvme_check_firmware)) {
7671 		goto copyout;
7672 	}
7673 
7674 	if (!nvme_validate_fw_commit(nvme, &fw)) {
7675 		goto copyout;
7676 	}
7677 
7678 	fc_dw10.b.fc_slot = fw.fwc_slot;
7679 	fc_dw10.b.fc_action = fw.fwc_action;
7680 	sqe.sqe_cdw10 = fc_dw10.r;
7681 
7682 	args.ica_sqe = &sqe;
7683 	args.ica_timeout = nvme_commit_save_cmd_timeout;
7684 
7685 	/*
7686 	 * There are no conditional actions to take based on this succeeding or
7687 	 * failing. A failure is recorded in the ioctl structure returned to the
7688 	 * user.
7689 	 */
7690 	(void) nvme_ioc_cmd(nvme, &fw.fwc_common, &args);
7691 
7692 	/*
7693 	 * Let the DDI UFM subsystem know that the firmware information for
7694 	 * this device has changed. We perform this unconditionally as an
7695 	 * invalidation doesn't particularly hurt us.
7696 	 */
7697 	nvme_ufm_update(nvme);
7698 
7699 copyout:
7700 	if (ddi_copyout(&fw, (void *)(uintptr_t)arg, sizeof (fw),
7701 	    mode & FKIOCTL) != 0) {
7702 		return (EFAULT);
7703 	}
7704 
7705 	return (0);
7706 }
7707 
7708 /*
7709  * Helper to copy in a passthru command from userspace, handling
7710  * different data models.
7711  */
7712 static int
nvme_passthru_copyin_cmd(const void * buf,nvme_ioctl_passthru_t * cmd,int mode)7713 nvme_passthru_copyin_cmd(const void *buf, nvme_ioctl_passthru_t *cmd, int mode)
7714 {
7715 	switch (ddi_model_convert_from(mode & FMODELS)) {
7716 #ifdef _MULTI_DATAMODEL
7717 	case DDI_MODEL_ILP32: {
7718 		nvme_ioctl_passthru32_t cmd32;
7719 
7720 		if (ddi_copyin(buf, (void*)&cmd32, sizeof (cmd32), mode) != 0)
7721 			return (EFAULT);
7722 
7723 		bzero(cmd, sizeof (nvme_ioctl_passthru_t));
7724 
7725 		cmd->npc_common.nioc_nsid = cmd32.npc_common.nioc_nsid;
7726 		cmd->npc_opcode = cmd32.npc_opcode;
7727 		cmd->npc_timeout = cmd32.npc_timeout;
7728 		cmd->npc_flags = cmd32.npc_flags;
7729 		cmd->npc_impact = cmd32.npc_impact;
7730 		cmd->npc_cdw12 = cmd32.npc_cdw12;
7731 		cmd->npc_cdw13 = cmd32.npc_cdw13;
7732 		cmd->npc_cdw14 = cmd32.npc_cdw14;
7733 		cmd->npc_cdw15 = cmd32.npc_cdw15;
7734 		cmd->npc_buflen = cmd32.npc_buflen;
7735 		cmd->npc_buf = cmd32.npc_buf;
7736 		break;
7737 	}
7738 #endif	/* _MULTI_DATAMODEL */
7739 	case DDI_MODEL_NONE:
7740 		if (ddi_copyin(buf, (void *)cmd, sizeof (nvme_ioctl_passthru_t),
7741 		    mode) != 0) {
7742 			return (EFAULT);
7743 		}
7744 		break;
7745 	default:
7746 		return (ENOTSUP);
7747 	}
7748 
7749 	return (0);
7750 }
7751 
7752 /*
7753  * Helper to copy out a passthru command result to userspace, handling
7754  * different data models.
7755  */
7756 static int
nvme_passthru_copyout_cmd(const nvme_ioctl_passthru_t * cmd,void * buf,int mode)7757 nvme_passthru_copyout_cmd(const nvme_ioctl_passthru_t *cmd, void *buf, int mode)
7758 {
7759 	switch (ddi_model_convert_from(mode & FMODELS)) {
7760 #ifdef _MULTI_DATAMODEL
7761 	case DDI_MODEL_ILP32: {
7762 		nvme_ioctl_passthru32_t cmd32;
7763 
7764 		bzero(&cmd32, sizeof (nvme_ioctl_passthru32_t));
7765 
7766 		cmd32.npc_common = cmd->npc_common;
7767 		cmd32.npc_opcode = cmd->npc_opcode;
7768 		cmd32.npc_timeout = cmd->npc_timeout;
7769 		cmd32.npc_flags = cmd->npc_flags;
7770 		cmd32.npc_impact = cmd->npc_impact;
7771 		cmd32.npc_cdw0 = cmd->npc_cdw0;
7772 		cmd32.npc_cdw12 = cmd->npc_cdw12;
7773 		cmd32.npc_cdw13 = cmd->npc_cdw13;
7774 		cmd32.npc_cdw14 = cmd->npc_cdw14;
7775 		cmd32.npc_cdw15 = cmd->npc_cdw15;
7776 		cmd32.npc_buflen = (size32_t)cmd->npc_buflen;
7777 		cmd32.npc_buf = (uintptr32_t)cmd->npc_buf;
7778 		if (ddi_copyout(&cmd32, buf, sizeof (cmd32), mode) != 0)
7779 			return (EFAULT);
7780 		break;
7781 	}
7782 #endif	/* _MULTI_DATAMODEL */
7783 	case DDI_MODEL_NONE:
7784 		if (ddi_copyout(cmd, buf, sizeof (nvme_ioctl_passthru_t),
7785 		    mode) != 0) {
7786 			return (EFAULT);
7787 		}
7788 		break;
7789 	default:
7790 		return (ENOTSUP);
7791 	}
7792 	return (0);
7793 }
7794 
7795 /*
7796  * Run an arbitrary vendor-specific admin command on the device.
7797  */
7798 static int
nvme_ioctl_passthru(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7799 nvme_ioctl_passthru(nvme_minor_t *minor, intptr_t arg, int mode, cred_t *cred_p)
7800 {
7801 	nvme_t *const nvme = minor->nm_ctrl;
7802 	int rv;
7803 	nvme_ioctl_passthru_t pass;
7804 	nvme_sqe_t sqe;
7805 	nvme_ioc_cmd_args_t args = { NULL };
7806 
7807 	/*
7808 	 * Basic checks: permissions, data model, argument size.
7809 	 */
7810 	if ((mode & FWRITE) == 0)
7811 		return (EBADF);
7812 
7813 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7814 		return (EPERM);
7815 
7816 	if ((rv = nvme_passthru_copyin_cmd((void *)(uintptr_t)arg, &pass,
7817 	    mode)) != 0) {
7818 		return (rv);
7819 	}
7820 
7821 	if (!nvme_ioctl_check(minor, &pass.npc_common, &nvme_check_passthru)) {
7822 		goto copyout;
7823 	}
7824 
7825 	if (!nvme_validate_vuc(nvme, &pass)) {
7826 		goto copyout;
7827 	}
7828 
7829 	nvme_mgmt_lock(nvme, NVME_MGMT_LOCK_NVME);
7830 	if ((pass.npc_impact & NVME_IMPACT_NS) != 0) {
7831 		/*
7832 		 * We've been told this has ns impact. Right now force that to
7833 		 * be every ns until we have more use cases and reason to trust
7834 		 * the nsid field.
7835 		 */
7836 		if (!nvme_no_blkdev_attached(nvme, NVME_NSID_BCAST)) {
7837 			nvme_mgmt_unlock(nvme);
7838 			(void) nvme_ioctl_error(&pass.npc_common,
7839 			    NVME_IOCTL_E_NS_BLKDEV_ATTACH, 0, 0);
7840 			goto copyout;
7841 		}
7842 	}
7843 
7844 	bzero(&sqe, sizeof (sqe));
7845 
7846 	sqe.sqe_opc = pass.npc_opcode;
7847 	sqe.sqe_nsid = pass.npc_common.nioc_nsid;
7848 	sqe.sqe_cdw10 = (uint32_t)(pass.npc_buflen >> NVME_DWORD_SHIFT);
7849 	sqe.sqe_cdw12 = pass.npc_cdw12;
7850 	sqe.sqe_cdw13 = pass.npc_cdw13;
7851 	sqe.sqe_cdw14 = pass.npc_cdw14;
7852 	sqe.sqe_cdw15 = pass.npc_cdw15;
7853 
7854 	args.ica_sqe = &sqe;
7855 	args.ica_data = (void *)pass.npc_buf;
7856 	args.ica_data_len = pass.npc_buflen;
7857 	args.ica_copy_flags = mode;
7858 	args.ica_timeout = pass.npc_timeout;
7859 
7860 	if ((pass.npc_flags & NVME_PASSTHRU_READ) != 0)
7861 		args.ica_dma_flags |= DDI_DMA_READ;
7862 	else if ((pass.npc_flags & NVME_PASSTHRU_WRITE) != 0)
7863 		args.ica_dma_flags |= DDI_DMA_WRITE;
7864 
7865 	if (nvme_ioc_cmd(nvme, &pass.npc_common, &args)) {
7866 		pass.npc_cdw0 = args.ica_cdw0;
7867 		if ((pass.npc_impact & NVME_IMPACT_NS) != 0) {
7868 			nvme_rescan_ns(nvme, NVME_NSID_BCAST);
7869 		}
7870 	}
7871 	nvme_mgmt_unlock(nvme);
7872 
7873 copyout:
7874 	rv = nvme_passthru_copyout_cmd(&pass, (void *)(uintptr_t)arg,
7875 	    mode);
7876 
7877 	return (rv);
7878 }
7879 
7880 static int
nvme_ioctl_lock(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)7881 nvme_ioctl_lock(nvme_minor_t *minor, intptr_t arg, int mode,
7882     cred_t *cred_p)
7883 {
7884 	nvme_ioctl_lock_t lock;
7885 	const nvme_lock_flags_t all_flags = NVME_LOCK_F_DONT_BLOCK;
7886 	nvme_t *nvme = minor->nm_ctrl;
7887 
7888 	if ((mode & FWRITE) == 0)
7889 		return (EBADF);
7890 
7891 	if (secpolicy_sys_config(cred_p, B_FALSE) != 0)
7892 		return (EPERM);
7893 
7894 	if (ddi_copyin((void *)(uintptr_t)arg, &lock, sizeof (lock),
7895 	    mode & FKIOCTL) != 0) {
7896 		return (EFAULT);
7897 	}
7898 
7899 	if (lock.nil_ent != NVME_LOCK_E_CTRL &&
7900 	    lock.nil_ent != NVME_LOCK_E_NS) {
7901 		(void) nvme_ioctl_error(&lock.nil_common,
7902 		    NVME_IOCTL_E_BAD_LOCK_ENTITY, 0, 0);
7903 		goto copyout;
7904 	}
7905 
7906 	if (lock.nil_level != NVME_LOCK_L_READ &&
7907 	    lock.nil_level != NVME_LOCK_L_WRITE) {
7908 		(void) nvme_ioctl_error(&lock.nil_common,
7909 		    NVME_IOCTL_E_BAD_LOCK_LEVEL, 0, 0);
7910 		goto copyout;
7911 	}
7912 
7913 	if ((lock.nil_flags & ~all_flags) != 0) {
7914 		(void) nvme_ioctl_error(&lock.nil_common,
7915 		    NVME_IOCTL_E_BAD_LOCK_FLAGS, 0, 0);
7916 		goto copyout;
7917 	}
7918 
7919 	if (!nvme_ioctl_check(minor, &lock.nil_common, &nvme_check_locking)) {
7920 		goto copyout;
7921 	}
7922 
7923 	/*
7924 	 * If we're on a namespace, confirm that we're not asking for the
7925 	 * controller.
7926 	 */
7927 	if (lock.nil_common.nioc_nsid != 0 &&
7928 	    lock.nil_ent == NVME_LOCK_E_CTRL) {
7929 		(void) nvme_ioctl_error(&lock.nil_common,
7930 		    NVME_IOCTL_E_NS_CANNOT_LOCK_CTRL, 0, 0);
7931 		goto copyout;
7932 	}
7933 
7934 	/*
7935 	 * We've reached the point where we can no longer actually check things
7936 	 * without serializing state. First, we need to check to make sure that
7937 	 * none of our invariants are being broken for locking:
7938 	 *
7939 	 * 1) The caller isn't already blocking for a lock operation to
7940 	 * complete.
7941 	 *
7942 	 * 2) The caller is attempting to grab a lock that they already have.
7943 	 * While there are other rule violations that this might create, we opt
7944 	 * to check this ahead of it so we can have slightly better error
7945 	 * messages for our callers.
7946 	 *
7947 	 * 3) The caller is trying to grab a controller lock, while holding a
7948 	 * namespace lock.
7949 	 *
7950 	 * 4) The caller has a controller write lock and is trying to get a
7951 	 * namespace lock. For now, we disallow this case. Holding a controller
7952 	 * read lock is allowed, but the write lock allows you to operate on all
7953 	 * namespaces anyways. In addition, this simplifies the locking logic;
7954 	 * however, this constraint may be loosened in the future.
7955 	 *
7956 	 * 5) The caller is trying to acquire a second namespace lock when they
7957 	 * already have one.
7958 	 */
7959 	mutex_enter(&nvme->n_minor_mutex);
7960 	if (minor->nm_ctrl_lock.nli_state == NVME_LOCK_STATE_BLOCKED ||
7961 	    minor->nm_ns_lock.nli_state == NVME_LOCK_STATE_BLOCKED) {
7962 		(void) nvme_ioctl_error(&lock.nil_common,
7963 		    NVME_IOCTL_E_LOCK_PENDING, 0, 0);
7964 		mutex_exit(&nvme->n_minor_mutex);
7965 		goto copyout;
7966 	}
7967 
7968 	if ((lock.nil_ent == NVME_LOCK_E_CTRL &&
7969 	    minor->nm_ctrl_lock.nli_state == NVME_LOCK_STATE_ACQUIRED) ||
7970 	    (lock.nil_ent == NVME_LOCK_E_NS &&
7971 	    minor->nm_ns_lock.nli_state == NVME_LOCK_STATE_ACQUIRED &&
7972 	    minor->nm_ns_lock.nli_ns->ns_id == lock.nil_common.nioc_nsid)) {
7973 		(void) nvme_ioctl_error(&lock.nil_common,
7974 		    NVME_IOCTL_E_LOCK_ALREADY_HELD, 0, 0);
7975 		mutex_exit(&nvme->n_minor_mutex);
7976 		goto copyout;
7977 	}
7978 
7979 	if (lock.nil_ent == NVME_LOCK_E_CTRL &&
7980 	    minor->nm_ns_lock.nli_state != NVME_LOCK_STATE_UNLOCKED) {
7981 		(void) nvme_ioctl_error(&lock.nil_common,
7982 		    NVME_IOCTL_E_LOCK_NO_CTRL_WITH_NS, 0, 0);
7983 		mutex_exit(&nvme->n_minor_mutex);
7984 		goto copyout;
7985 	}
7986 
7987 	if (lock.nil_ent == NVME_LOCK_E_NS &&
7988 	    (minor->nm_ctrl_lock.nli_state == NVME_LOCK_STATE_ACQUIRED &&
7989 	    minor->nm_ctrl_lock.nli_curlevel == NVME_LOCK_L_WRITE)) {
7990 		(void) nvme_ioctl_error(&lock.nil_common,
7991 		    NVME_IOCTL_LOCK_NO_NS_WITH_CTRL_WRLOCK, 0, 0);
7992 		mutex_exit(&nvme->n_minor_mutex);
7993 		goto copyout;
7994 	}
7995 
7996 	if (lock.nil_ent == NVME_LOCK_E_NS &&
7997 	    minor->nm_ns_lock.nli_state != NVME_LOCK_STATE_UNLOCKED) {
7998 		(void) nvme_ioctl_error(&lock.nil_common,
7999 		    NVME_IOCTL_E_LOCK_NO_2ND_NS, 0, 0);
8000 		mutex_exit(&nvme->n_minor_mutex);
8001 		goto copyout;
8002 	}
8003 
8004 #ifdef	DEBUG
8005 	/*
8006 	 * This is a big block of sanity checks to make sure that we haven't
8007 	 * allowed anything bad to happen.
8008 	 */
8009 	if (lock.nil_ent == NVME_LOCK_E_NS) {
8010 		ASSERT3P(minor->nm_ns_lock.nli_lock, ==, NULL);
8011 		ASSERT3U(minor->nm_ns_lock.nli_state, ==,
8012 		    NVME_LOCK_STATE_UNLOCKED);
8013 		ASSERT3U(minor->nm_ns_lock.nli_curlevel, ==, 0);
8014 		ASSERT3P(minor->nm_ns_lock.nli_ns, ==, NULL);
8015 
8016 		if (minor->nm_ns != NULL) {
8017 			ASSERT3U(minor->nm_ns->ns_id, ==,
8018 			    lock.nil_common.nioc_nsid);
8019 		}
8020 
8021 		ASSERT0(list_link_active(&minor->nm_ns_lock.nli_node));
8022 	} else {
8023 		ASSERT3P(minor->nm_ctrl_lock.nli_lock, ==, NULL);
8024 		ASSERT3U(minor->nm_ctrl_lock.nli_state, ==,
8025 		    NVME_LOCK_STATE_UNLOCKED);
8026 		ASSERT3U(minor->nm_ctrl_lock.nli_curlevel, ==, 0);
8027 		ASSERT3P(minor->nm_ns_lock.nli_ns, ==, NULL);
8028 		ASSERT0(list_link_active(&minor->nm_ctrl_lock.nli_node));
8029 
8030 		ASSERT3P(minor->nm_ns_lock.nli_lock, ==, NULL);
8031 		ASSERT3U(minor->nm_ns_lock.nli_state, ==,
8032 		    NVME_LOCK_STATE_UNLOCKED);
8033 		ASSERT3U(minor->nm_ns_lock.nli_curlevel, ==, 0);
8034 		ASSERT3P(minor->nm_ns_lock.nli_ns, ==, NULL);
8035 		ASSERT0(list_link_active(&minor->nm_ns_lock.nli_node));
8036 	}
8037 #endif	/* DEBUG */
8038 
8039 	/*
8040 	 * At this point we should actually attempt a locking operation.
8041 	 */
8042 	nvme_rwlock(minor, &lock);
8043 	mutex_exit(&nvme->n_minor_mutex);
8044 
8045 copyout:
8046 	if (ddi_copyout(&lock, (void *)(uintptr_t)arg, sizeof (lock),
8047 	    mode & FKIOCTL) != 0) {
8048 		return (EFAULT);
8049 	}
8050 
8051 	return (0);
8052 }
8053 
8054 static int
nvme_ioctl_unlock(nvme_minor_t * minor,intptr_t arg,int mode,cred_t * cred_p)8055 nvme_ioctl_unlock(nvme_minor_t *minor, intptr_t arg, int mode,
8056     cred_t *cred_p)
8057 {
8058 	nvme_ioctl_unlock_t unlock;
8059 	nvme_t *const nvme = minor->nm_ctrl;
8060 	boolean_t is_ctrl;
8061 	nvme_lock_t *lock;
8062 	nvme_minor_lock_info_t *info;
8063 
8064 	/*
8065 	 * Note, we explicitly don't check for privileges for unlock. The idea
8066 	 * being that if you have the lock, that's what matters. If you don't
8067 	 * have the lock, it doesn't matter what privileges that you have at
8068 	 * all.
8069 	 */
8070 	if ((mode & FWRITE) == 0)
8071 		return (EBADF);
8072 
8073 	if (ddi_copyin((void *)(uintptr_t)arg, &unlock, sizeof (unlock),
8074 	    mode & FKIOCTL) != 0) {
8075 		return (EFAULT);
8076 	}
8077 
8078 	if (unlock.niu_ent != NVME_LOCK_E_CTRL &&
8079 	    unlock.niu_ent != NVME_LOCK_E_NS) {
8080 		(void) nvme_ioctl_error(&unlock.niu_common,
8081 		    NVME_IOCTL_E_BAD_LOCK_ENTITY, 0, 0);
8082 		goto copyout;
8083 	}
8084 
8085 	if (!nvme_ioctl_check(minor, &unlock.niu_common, &nvme_check_locking)) {
8086 		goto copyout;
8087 	}
8088 
8089 	/*
8090 	 * If we're on a namespace, confirm that we're not asking for the
8091 	 * controller.
8092 	 */
8093 	if (unlock.niu_common.nioc_nsid != 0 &&
8094 	    unlock.niu_ent == NVME_LOCK_E_CTRL) {
8095 		(void) nvme_ioctl_error(&unlock.niu_common,
8096 		    NVME_IOCTL_E_NS_CANNOT_UNLOCK_CTRL, 0, 0);
8097 		goto copyout;
8098 	}
8099 
8100 	mutex_enter(&nvme->n_minor_mutex);
8101 	if (unlock.niu_ent == NVME_LOCK_E_CTRL) {
8102 		if (minor->nm_ctrl_lock.nli_state != NVME_LOCK_STATE_ACQUIRED) {
8103 			mutex_exit(&nvme->n_minor_mutex);
8104 			(void) nvme_ioctl_error(&unlock.niu_common,
8105 			    NVME_IOCTL_E_LOCK_NOT_HELD, 0, 0);
8106 			goto copyout;
8107 		}
8108 	} else {
8109 		if (minor->nm_ns_lock.nli_ns == NULL) {
8110 			mutex_exit(&nvme->n_minor_mutex);
8111 			(void) nvme_ioctl_error(&unlock.niu_common,
8112 			    NVME_IOCTL_E_LOCK_NOT_HELD, 0, 0);
8113 			goto copyout;
8114 		}
8115 
8116 		/*
8117 		 * Check that our unlock request corresponds to the namespace ID
8118 		 * that is currently locked. This could happen if we're using
8119 		 * the controller node and it specified a valid, but not locked,
8120 		 * namespace ID.
8121 		 */
8122 		if (minor->nm_ns_lock.nli_ns->ns_id !=
8123 		    unlock.niu_common.nioc_nsid) {
8124 			mutex_exit(&nvme->n_minor_mutex);
8125 			ASSERT3P(minor->nm_ns, ==, NULL);
8126 			(void) nvme_ioctl_error(&unlock.niu_common,
8127 			    NVME_IOCTL_E_LOCK_WRONG_NS, 0, 0);
8128 			goto copyout;
8129 		}
8130 
8131 		if (minor->nm_ns_lock.nli_state != NVME_LOCK_STATE_ACQUIRED) {
8132 			mutex_exit(&nvme->n_minor_mutex);
8133 			(void) nvme_ioctl_error(&unlock.niu_common,
8134 			    NVME_IOCTL_E_LOCK_NOT_HELD, 0, 0);
8135 			goto copyout;
8136 		}
8137 	}
8138 
8139 	/*
8140 	 * Finally, perform the unlock.
8141 	 */
8142 	is_ctrl = unlock.niu_ent == NVME_LOCK_E_CTRL;
8143 	if (is_ctrl) {
8144 		lock = &nvme->n_lock;
8145 		info = &minor->nm_ctrl_lock;
8146 	} else {
8147 		nvme_namespace_t *ns;
8148 		const uint32_t nsid = unlock.niu_common.nioc_nsid;
8149 
8150 		ns = nvme_nsid2ns(nvme, nsid);
8151 		lock = &ns->ns_lock;
8152 		info = &minor->nm_ns_lock;
8153 		VERIFY3P(ns, ==, info->nli_ns);
8154 	}
8155 	nvme_rwunlock(info, lock);
8156 	mutex_exit(&nvme->n_minor_mutex);
8157 	nvme_ioctl_success(&unlock.niu_common);
8158 
8159 copyout:
8160 	if (ddi_copyout(&unlock, (void *)(uintptr_t)arg, sizeof (unlock),
8161 	    mode & FKIOCTL) != 0) {
8162 		return (EFAULT);
8163 	}
8164 
8165 	return (0);
8166 }
8167 
8168 static int
nvme_ioctl(dev_t dev,int cmd,intptr_t arg,int mode,cred_t * cred_p,int * rval_p)8169 nvme_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *cred_p,
8170     int *rval_p)
8171 {
8172 #ifndef __lock_lint
8173 	_NOTE(ARGUNUSED(rval_p));
8174 #endif
8175 	int ret;
8176 	nvme_minor_t *minor;
8177 	nvme_t *nvme;
8178 
8179 	minor = nvme_minor_find_by_dev(dev);
8180 	if (minor == NULL) {
8181 		return (ENXIO);
8182 	}
8183 
8184 	nvme = minor->nm_ctrl;
8185 	if (nvme == NULL)
8186 		return (ENXIO);
8187 
8188 	if (IS_DEVCTL(cmd))
8189 		return (ndi_devctl_ioctl(nvme->n_dip, cmd, arg, mode, 0));
8190 
8191 	if (nvme->n_dead && (cmd != NVME_IOC_BD_DETACH && cmd !=
8192 	    NVME_IOC_UNLOCK)) {
8193 		if (IS_NVME_IOC(cmd) == 0) {
8194 			return (EIO);
8195 		}
8196 
8197 		return (nvme_ioctl_copyout_error(nvme->n_dead_status, arg,
8198 		    mode));
8199 	}
8200 
8201 	/*
8202 	 * ioctls that are no longer using the original ioctl structure.
8203 	 */
8204 	switch (cmd) {
8205 	case NVME_IOC_CTRL_INFO:
8206 		ret = nvme_ioctl_ctrl_info(minor, arg, mode, cred_p);
8207 		break;
8208 	case NVME_IOC_IDENTIFY:
8209 		ret = nvme_ioctl_identify(minor, arg, mode, cred_p);
8210 		break;
8211 	case NVME_IOC_GET_LOGPAGE:
8212 		ret = nvme_ioctl_get_logpage(minor, arg, mode, cred_p);
8213 		break;
8214 	case NVME_IOC_GET_FEATURE:
8215 		ret = nvme_ioctl_get_feature(minor, arg, mode, cred_p);
8216 		break;
8217 	case NVME_IOC_BD_DETACH:
8218 		ret = nvme_ioctl_bd_detach(minor, arg, mode, cred_p);
8219 		break;
8220 	case NVME_IOC_BD_ATTACH:
8221 		ret = nvme_ioctl_bd_attach(minor, arg, mode, cred_p);
8222 		break;
8223 	case NVME_IOC_FORMAT:
8224 		ret = nvme_ioctl_format(minor, arg, mode, cred_p);
8225 		break;
8226 	case NVME_IOC_FIRMWARE_DOWNLOAD:
8227 		ret = nvme_ioctl_firmware_download(minor, arg, mode, cred_p);
8228 		break;
8229 	case NVME_IOC_FIRMWARE_COMMIT:
8230 		ret = nvme_ioctl_firmware_commit(minor, arg, mode, cred_p);
8231 		break;
8232 	case NVME_IOC_NS_INFO:
8233 		ret = nvme_ioctl_ns_info(minor, arg, mode, cred_p);
8234 		break;
8235 	case NVME_IOC_PASSTHRU:
8236 		ret = nvme_ioctl_passthru(minor, arg, mode, cred_p);
8237 		break;
8238 	case NVME_IOC_LOCK:
8239 		ret = nvme_ioctl_lock(minor, arg, mode, cred_p);
8240 		break;
8241 	case NVME_IOC_UNLOCK:
8242 		ret = nvme_ioctl_unlock(minor, arg, mode, cred_p);
8243 		break;
8244 	case NVME_IOC_CTRL_DETACH:
8245 		ret = nvme_ioctl_ctrl_detach(minor, arg, mode, cred_p);
8246 		break;
8247 	case NVME_IOC_CTRL_ATTACH:
8248 		ret = nvme_ioctl_ctrl_attach(minor, arg, mode, cred_p);
8249 		break;
8250 	case NVME_IOC_NS_CREATE:
8251 		ret = nvme_ioctl_ns_create(minor, arg, mode, cred_p);
8252 		break;
8253 	case NVME_IOC_NS_DELETE:
8254 		ret = nvme_ioctl_ns_delete(minor, arg, mode, cred_p);
8255 		break;
8256 	default:
8257 		ret = ENOTTY;
8258 		break;
8259 	}
8260 
8261 	ASSERT(!nvme_mgmt_lock_held(nvme));
8262 	return (ret);
8263 }
8264 
8265 /*
8266  * DDI UFM Callbacks
8267  */
8268 static int
nvme_ufm_fill_image(ddi_ufm_handle_t * ufmh,void * arg,uint_t imgno,ddi_ufm_image_t * img)8269 nvme_ufm_fill_image(ddi_ufm_handle_t *ufmh, void *arg, uint_t imgno,
8270     ddi_ufm_image_t *img)
8271 {
8272 	nvme_t *nvme = arg;
8273 
8274 	if (imgno != 0)
8275 		return (EINVAL);
8276 
8277 	ddi_ufm_image_set_desc(img, "Firmware");
8278 	ddi_ufm_image_set_nslots(img, nvme->n_idctl->id_frmw.fw_nslot);
8279 
8280 	return (0);
8281 }
8282 
8283 /*
8284  * Fill out firmware slot information for the requested slot.  The firmware
8285  * slot information is gathered by requesting the Firmware Slot Information log
8286  * page.  The format of the page is described in section 5.10.1.3.
8287  *
8288  * We lazily cache the log page on the first call and then invalidate the cache
8289  * data after a successful firmware download or firmware commit command.
8290  * The cached data is protected by a mutex as the state can change
8291  * asynchronous to this callback.
8292  */
8293 static int
nvme_ufm_fill_slot(ddi_ufm_handle_t * ufmh,void * arg,uint_t imgno,uint_t slotno,ddi_ufm_slot_t * slot)8294 nvme_ufm_fill_slot(ddi_ufm_handle_t *ufmh, void *arg, uint_t imgno,
8295     uint_t slotno, ddi_ufm_slot_t *slot)
8296 {
8297 	nvme_t *nvme = arg;
8298 	void *log = NULL;
8299 	size_t bufsize;
8300 	ddi_ufm_attr_t attr = 0;
8301 	char fw_ver[NVME_FWVER_SZ + 1];
8302 
8303 	if (imgno > 0 || slotno > (nvme->n_idctl->id_frmw.fw_nslot - 1))
8304 		return (EINVAL);
8305 
8306 	mutex_enter(&nvme->n_fwslot_mutex);
8307 	if (nvme->n_fwslot == NULL) {
8308 		if (!nvme_get_logpage_int(nvme, B_TRUE, &log, &bufsize,
8309 		    NVME_LOGPAGE_FWSLOT) ||
8310 		    bufsize != sizeof (nvme_fwslot_log_t)) {
8311 			if (log != NULL)
8312 				kmem_free(log, bufsize);
8313 			mutex_exit(&nvme->n_fwslot_mutex);
8314 			return (EIO);
8315 		}
8316 		nvme->n_fwslot = (nvme_fwslot_log_t *)log;
8317 	}
8318 
8319 	/*
8320 	 * NVMe numbers firmware slots starting at 1
8321 	 */
8322 	if (slotno == (nvme->n_fwslot->fw_afi - 1))
8323 		attr |= DDI_UFM_ATTR_ACTIVE;
8324 
8325 	if (slotno != 0 || nvme->n_idctl->id_frmw.fw_readonly == 0)
8326 		attr |= DDI_UFM_ATTR_WRITEABLE;
8327 
8328 	if (nvme->n_fwslot->fw_frs[slotno][0] == '\0') {
8329 		attr |= DDI_UFM_ATTR_EMPTY;
8330 	} else {
8331 		(void) strncpy(fw_ver, nvme->n_fwslot->fw_frs[slotno],
8332 		    NVME_FWVER_SZ);
8333 		fw_ver[NVME_FWVER_SZ] = '\0';
8334 		ddi_ufm_slot_set_version(slot, fw_ver);
8335 	}
8336 	mutex_exit(&nvme->n_fwslot_mutex);
8337 
8338 	ddi_ufm_slot_set_attrs(slot, attr);
8339 
8340 	return (0);
8341 }
8342 
8343 static int
nvme_ufm_getcaps(ddi_ufm_handle_t * ufmh,void * arg,ddi_ufm_cap_t * caps)8344 nvme_ufm_getcaps(ddi_ufm_handle_t *ufmh, void *arg, ddi_ufm_cap_t *caps)
8345 {
8346 	*caps = DDI_UFM_CAP_REPORT;
8347 	return (0);
8348 }
8349 
8350 boolean_t
nvme_ctrl_atleast(nvme_t * nvme,const nvme_version_t * min)8351 nvme_ctrl_atleast(nvme_t *nvme, const nvme_version_t *min)
8352 {
8353 	return (nvme_vers_atleast(&nvme->n_version, min) ? B_TRUE : B_FALSE);
8354 }
8355