Debian Codegraph @

src/nvme/util.c

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3 * This file is part of libnvme.
4 * Copyright (c) 2020 Western Digital Corporation or its affiliates.
5 *
6 * Authors: Keith Busch <[email protected]>
7 * Chaitanya Kulkarni <[email protected]>
8 */
9
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <stdbool.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <malloc.h>
16
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <sys/param.h>
20 #include <sys/types.h>
21 #include <arpa/inet.h>
22 #include <netdb.h>
23 #include <unistd.h>
24
25 #include <ccan/ccan/minmax/minmax.h>
26 #include <ccan/endian/endian.h>
27
28 #include "cleanup.h"
29 #include "private.h"
30 #include "util.h"
31 #include "log.h"
32
33 /* The bionic libc implementation doesn't define LINE_MAX */
34 #ifndef LINE_MAX
35 #define LINE_MAX 2048
36 #endif
37
38 /* Source Code Control System, query version of binary with 'what' */
39 const char sccsid[] = "@(#)libnvme " GIT_VERSION;
40
41 static inline __u8 nvme_generic_status_to_errno(__u16 status)
42 {
43 switch (status) {
44 case NVME_SC_INVALID_OPCODE:
45 case NVME_SC_INVALID_FIELD:
46 case NVME_SC_INVALID_NS:
47 case NVME_SC_SGL_INVALID_LAST:
48 case NVME_SC_SGL_INVALID_COUNT:
49 case NVME_SC_SGL_INVALID_DATA:
50 case NVME_SC_SGL_INVALID_METADATA:
51 case NVME_SC_SGL_INVALID_TYPE:
52 case NVME_SC_SGL_INVALID_OFFSET:
53 case NVME_SC_PRP_INVALID_OFFSET:
54 case NVME_SC_CMB_INVALID_USE:
55 case NVME_SC_KAT_INVALID:
56 case NVME_SC_INVALID_KEY_TAG:
57 case NVME_SC_INCORRECT_KEY:
58 case NVME_SC_INVALID_VALUE_SIZE:
59 case NVME_SC_INVALID_KEY_SIZE:
60 return EINVAL;
61 case NVME_SC_CMDID_CONFLICT:
62 return EADDRINUSE;
63 case NVME_SC_DATA_XFER_ERROR:
64 case NVME_SC_INTERNAL:
65 case NVME_SC_SANITIZE_FAILED:
66 return EIO;
67 case NVME_SC_POWER_LOSS:
68 case NVME_SC_ABORT_REQ:
69 case NVME_SC_ABORT_QUEUE:
70 case NVME_SC_FUSED_FAIL:
71 case NVME_SC_FUSED_MISSING:
72 return EWOULDBLOCK;
73 case NVME_SC_CMD_SEQ_ERROR:
74 return EILSEQ;
75 case NVME_SC_SANITIZE_IN_PROGRESS:
76 case NVME_SC_FORMAT_IN_PROGRESS:
77 return EINPROGRESS;
78 case NVME_SC_NS_WRITE_PROTECTED:
79 case NVME_SC_NS_NOT_READY:
80 case NVME_SC_RESERVATION_CONFLICT:
81 case NVME_SC_OP_DENIED:
82 case NVME_SC_ADMIN_CMD_MEDIA_NOT_READY:
83 return EACCES;
84 case NVME_SC_LBA_RANGE:
85 return EREMOTEIO;
86 case NVME_SC_CAP_EXCEEDED:
87 case NVME_SC_AWU_EXCEEDED:
88 return ENOSPC;
89 }
90 return EIO;
91 }
92
93 static inline __u8 nvme_cmd_specific_status_to_errno(__u16 status)
94 {
95 switch (status) {
96 case NVME_SC_CQ_INVALID:
97 case NVME_SC_QID_INVALID:
98 case NVME_SC_QUEUE_SIZE:
99 case NVME_SC_FIRMWARE_SLOT:
100 case NVME_SC_FIRMWARE_IMAGE:
101 case NVME_SC_INVALID_VECTOR:
102 case NVME_SC_INVALID_LOG_PAGE:
103 case NVME_SC_INVALID_FORMAT:
104 case NVME_SC_INVALID_QUEUE:
105 case NVME_SC_NS_INSUFFICIENT_CAP:
106 case NVME_SC_NS_ID_UNAVAILABLE:
107 case NVME_SC_CTRL_LIST_INVALID:
108 case NVME_SC_BAD_ATTRIBUTES:
109 case NVME_SC_INVALID_PI:
110 case NVME_SC_INVALID_CTRL_ID:
111 case NVME_SC_INVALID_SEC_CTRL_STATE:
112 case NVME_SC_INVALID_CTRL_RESOURCES:
113 case NVME_SC_INVALID_RESOURCE_ID:
114 case NVME_SC_ANA_GROUP_ID_INVALID:
115 case NVME_SC_INSUFFICIENT_CAP:
116 case NVME_SC_INVALID_IOCS:
117 case NVME_SC_ID_UNAVAILABLE:
118 return EINVAL;
119 case NVME_SC_ABORT_LIMIT:
120 case NVME_SC_ASYNC_LIMIT:
121 case NVME_SC_NS_ATTACHMENT_LIMIT_EXCEEDED:
122 return EDQUOT;
123 case NVME_SC_FW_NEEDS_CONV_RESET:
124 case NVME_SC_FW_NEEDS_SUBSYS_RESET:
125 case NVME_SC_FW_NEEDS_MAX_TIME:
126 case NVME_SC_FW_NEEDS_RESET:
127 return ERESTART;
128 case NVME_SC_FEATURE_NOT_SAVEABLE:
129 case NVME_SC_FEATURE_NOT_CHANGEABLE:
130 case NVME_SC_FEATURE_NOT_PER_NS:
131 case NVME_SC_FW_ACTIVATE_PROHIBITED:
132 case NVME_SC_NS_IS_PRIVATE:
133 case NVME_SC_BP_WRITE_PROHIBITED:
134 case NVME_SC_READ_ONLY:
135 case NVME_SC_PMR_SAN_PROHIBITED:
136 return EPERM;
137 case NVME_SC_OVERLAPPING_RANGE:
138 case NVME_SC_NS_NOT_ATTACHED:
139 return ENOSPC;
140 case NVME_SC_NS_ALREADY_ATTACHED:
141 return EALREADY;
142 case NVME_SC_THIN_PROV_NOT_SUPP:
143 case NVME_SC_PROHIBIT_CMD_EXEC_NOT_SUPPORTED:
144 return EOPNOTSUPP;
145 case NVME_SC_ABORT_MISSING:
146 return EWOULDBLOCK;
147 case NVME_SC_SELF_TEST_IN_PROGRESS:
148 return EINPROGRESS;
149 }
150
151 return EIO;
152 }
153
154 static inline __u8 nvme_fabrics_status_to_errno(__u16 status)
155 {
156 switch (status) {
157 case NVME_SC_CONNECT_FORMAT:
158 case NVME_SC_CONNECT_INVALID_PARAM:
159 case NVME_SC_DISCONNECT_INVALID_QTYPE:
160 return EINVAL;
161 case NVME_SC_CONNECT_CTRL_BUSY:
162 return EBUSY;
163 case NVME_SC_CONNECT_RESTART_DISC:
164 return ERESTART;
165 case NVME_SC_CONNECT_INVALID_HOST:
166 return ECONNREFUSED;
167 case NVME_SC_DISCOVERY_RESTART:
168 return EAGAIN;
169 case NVME_SC_AUTH_REQUIRED:
170 return EPERM;
171 }
172
173 return EIO;
174 }
175
176 __u8 nvme_status_to_errno(int status, bool fabrics)
177 {
178 __u16 sc;
179
180 if (!status)
181 return 0;
182 if (status < 0)
183 return errno;
184
185 sc = nvme_status_code(status);
186 switch (nvme_status_code_type(status)) {
187 case NVME_SCT_GENERIC:
188 return nvme_generic_status_to_errno(sc);
189 case NVME_SCT_CMD_SPECIFIC:
190 if (fabrics)
191 return nvme_fabrics_status_to_errno(sc);
192 return nvme_cmd_specific_status_to_errno(sc);
193 default:
194 return EIO;
195 }
196 }
197
198 static const char * const generic_status[] = {
199 [NVME_SC_SUCCESS] = "Successful Completion: The command completed without error",
200 [NVME_SC_INVALID_OPCODE] = "Invalid Command Opcode: A reserved coded value or an unsupported value in the command opcode field",
201 [NVME_SC_INVALID_FIELD] = "Invalid Field in Command: A reserved coded value or an unsupported value in a defined field",
202 [NVME_SC_CMDID_CONFLICT] = "Command ID Conflict: The command identifier is already in use",
203 [NVME_SC_DATA_XFER_ERROR] = "Data Transfer Error: Transferring the data or metadata associated with a command experienced an error",
204 [NVME_SC_POWER_LOSS] = "Commands Aborted due to Power Loss Notification: Indicates that the command was aborted due to a power loss notification",
205 [NVME_SC_INTERNAL] = "Internal Error: The command was not completed successfully due to an internal error",
206 [NVME_SC_ABORT_REQ] = "Command Abort Requested: The command was aborted due to an Abort command",
207 [NVME_SC_ABORT_QUEUE] = "Command Aborted due to SQ Deletion: The command was aborted due to a Delete I/O Submission Queue",
208 [NVME_SC_FUSED_FAIL] = "Command Aborted due to Failed Fused Command: The command was aborted due to the other command in a fused operation failing",
209 [NVME_SC_FUSED_MISSING] = "Command Aborted due to Missing Fused Command: The fused command was aborted due to the adjacent submission queue entry not containing a fused command",
210 [NVME_SC_INVALID_NS] = "Invalid Namespace or Format: The namespace or the format of that namespace is invalid",
211 [NVME_SC_CMD_SEQ_ERROR] = "Command Sequence Error: The command was aborted due to a protocol violation in a multi- command sequence",
212 [NVME_SC_SGL_INVALID_LAST] = "Invalid SGL Segment Descriptor: The command includes an invalid SGL Last Segment or SGL Segment descriptor",
213 [NVME_SC_SGL_INVALID_COUNT] = "Invalid Number of SGL Descriptors: There is an SGL Last Segment descriptor or an SGL Segment descriptor in a location other than the last descriptor of a segment based on the length indicated",
214 [NVME_SC_SGL_INVALID_DATA] = "Data SGL Length Invalid: The length of a Data SGL is too short or too long and the controller does not support SGL transfers longer than the amount of data to be transferred",
215 [NVME_SC_SGL_INVALID_METADATA] = "Metadata SGL Length Invalid: The length of a Metadata SGL is too short or too long and the controller does not support SGL transfers longer than the amount of data to be transferred",
216 [NVME_SC_SGL_INVALID_TYPE] = "SGL Descriptor Type Invalid: The type of an SGL Descriptor is a type that is not supported by the controller",
217 [NVME_SC_CMB_INVALID_USE] = "Invalid Use of Controller Memory Buffer: The attempted use of the Controller Memory Buffer is not supported by the controller",
218 [NVME_SC_PRP_INVALID_OFFSET] = "PRP Offset Invalid: The Offset field for a PRP entry is invalid",
219 [NVME_SC_AWU_EXCEEDED] = "Atomic Write Unit Exceeded: The length specified exceeds the atomic write unit size",
220 [NVME_SC_OP_DENIED] = "Operation Denied: The command was denied due to lack of access rights",
221 [NVME_SC_SGL_INVALID_OFFSET] = "SGL Offset Invalid: The offset specified in a descriptor is invalid",
222 [NVME_SC_HOSTID_FORMAT] = "Host Identifier Inconsistent Format: The NVM subsystem detected the simultaneous use of 64- bit and 128-bit Host Identifier values on different controllers",
223 [NVME_SC_KAT_EXPIRED] = "Keep Alive Timer Expired: The Keep Alive Timer expired",
224 [NVME_SC_KAT_INVALID] = "Keep Alive Timeout Invalid: The Keep Alive Timeout value specified is invalid",
225 [NVME_SC_CMD_ABORTED_PREMEPT] = "Command Aborted due to Preempt and Abort: The command was aborted due to a Reservation Acquire command",
226 [NVME_SC_SANITIZE_FAILED] = "Sanitize Failed: The most recent sanitize operation failed and no recovery action has been successfully completed",
227 [NVME_SC_SANITIZE_IN_PROGRESS] = "Sanitize In Progress: The requested function is prohibited while a sanitize operation is in progress",
228 [NVME_SC_SGL_INVALID_GRANULARITY] = "SGL Data Block Granularity Invalid: The Address alignment or Length granularity for an SGL Data Block descriptor is invalid",
229 [NVME_SC_CMD_IN_CMBQ_NOT_SUPP] = "Command Not Supported for Queue in CMB: The controller does not support Submission Queue in the Controller Memory Buffer or Completion Queue in the Controller Memory Buffer",
230 [NVME_SC_NS_WRITE_PROTECTED] = "Namespace is Write Protected: The command is prohibited while the namespace is write protected",
231 [NVME_SC_CMD_INTERRUPTED] = "Command Interrupted: Command processing was interrupted and the controller is unable to successfully complete the command",
232 [NVME_SC_TRAN_TPORT_ERROR] = "Transient Transport Error: A transient transport error was detected",
233 [NVME_SC_PROHIBITED_BY_CMD_AND_FEAT] = "Command Prohibited by Command and Feature Lockdown: The command was aborted due to command execution being prohibited by the Command and Feature Lockdown",
234 [NVME_SC_ADMIN_CMD_MEDIA_NOT_READY] = "Admin Command Media Not Ready: The Admin command requires access to media and the media is not ready",
235 [NVME_SC_INVALID_KEY_TAG] = "The command was aborted due to an invalid KEYTAG field value",
236 [NVME_SC_HOST_DISPERSED_NS_NOT_ENABLED] = "The command is prohibited while the Host Disperesed Namespace Support (HDISNS) field is not set to 1h in the Host Behavior Support feature",
237 [NVME_SC_HOST_ID_NOT_INITIALIZED] = "Host Identifier Not Initialized",
238 [NVME_SC_INCORRECT_KEY] = "The command was aborted due to the key associated with the KEYTAG field being incorrect",
239 [NVME_SC_LBA_RANGE] = "LBA Out of Range: The command references an LBA that exceeds the size of the namespace",
240 [NVME_SC_CAP_EXCEEDED] = "Capacity Exceeded: Execution of the command has caused the capacity of the namespace to be exceeded",
241 [NVME_SC_NS_NOT_READY] = "Namespace Not Ready: The namespace is not ready to be accessed",
242 [NVME_SC_RESERVATION_CONFLICT] = "Reservation Conflict: The command was aborted due to a conflict with a reservation held on the accessed namespace",
243 [NVME_SC_FORMAT_IN_PROGRESS] = "Format In Progress: A Format NVM command is in progress on the namespace",
244 [NVME_SC_INVALID_VALUE_SIZE] = "The value size is not valid",
245 [NVME_SC_INVALID_KEY_SIZE] = "The KV key size is not valid",
246 [NVME_SC_KV_KEY_NOT_EXISTS] = "The Store If Key Exists (SIKE) bit is set to '1' in the Store Option field and the KV key does not exists",
247 [NVME_SC_UNRECOVERED_ERROR] = "There was an unrecovered error when reading from the medium",
248 [NVME_SC_KEY_EXISTS] = "The Store If No Key Exists (SINKE) bit is set to '1' in the Store Option field and the KV key exists",
249 };
250
251 static const char * const cmd_spec_status[] = {
252 [NVME_SC_CQ_INVALID] = "Completion Queue Invalid: The Completion Queue identifier specified in the command does not exist",
253 [NVME_SC_QID_INVALID] = "Invalid Queue Identifier: The creation of the I/O Completion Queue failed due to an invalid queue identifier specified as part of the command",
254 [NVME_SC_QUEUE_SIZE] = "Invalid Queue Size: The host attempted to create an I/O Completion Queue with an invalid number of entries",
255 [NVME_SC_ABORT_LIMIT] = "Abort Command Limit Exceeded: The number of concurrently outstanding Abort commands has exceeded the limit indicated in the Identify Controller data structure",
256 [NVME_SC_ABORT_MISSING] = "Abort Command Is Missing: The abort command is missing",
257 [NVME_SC_ASYNC_LIMIT] = "Asynchronous Event Request Limit Exceeded: The number of concurrently outstanding Asynchronous Event Request commands has been exceeded",
258 [NVME_SC_FIRMWARE_SLOT] = "Invalid Firmware Slot: The firmware slot indicated is invalid or read only",
259 [NVME_SC_FIRMWARE_IMAGE] = "Invalid Firmware Image: The firmware image specified for activation is invalid and not loaded by the controller",
260 [NVME_SC_INVALID_VECTOR] = "Invalid Interrupt Vector: The creation of the I/O Completion Queue failed due to an invalid interrupt vector specified as part of the command",
261 [NVME_SC_INVALID_LOG_PAGE] = "Invalid Log Page: The log page indicated is invalid",
262 [NVME_SC_INVALID_FORMAT] = "Invalid Format: The LBA Format specified is not supported",
263 [NVME_SC_FW_NEEDS_CONV_RESET] = "Firmware Activation Requires Conventional Reset: The firmware commit was successful, however, activation of the firmware image requires a conventional reset",
264 [NVME_SC_INVALID_QUEUE] = "Invalid Queue Deletion: Invalid I/O Completion Queue specified to delete",
265 [NVME_SC_FEATURE_NOT_SAVEABLE] = "Feature Identifier Not Saveable: The Feature Identifier specified does not support a saveable value",
266 [NVME_SC_FEATURE_NOT_CHANGEABLE] = "Feature Not Changeable: The Feature Identifier is not able to be changed",
267 [NVME_SC_FEATURE_NOT_PER_NS] = "Feature Not Namespace Specific: The Feature Identifier specified is not namespace specific",
268 [NVME_SC_FW_NEEDS_SUBSYS_RESET] = "Firmware Activation Requires NVM Subsystem Reset: The firmware commit was successful, however, activation of the firmware image requires an NVM Subsystem",
269 [NVME_SC_FW_NEEDS_RESET] = "Firmware Activation Requires Controller Level Reset: The firmware commit was successful; however, the image specified does not support being activated without a reset",
270 [NVME_SC_FW_NEEDS_MAX_TIME] = "Firmware Activation Requires Maximum Time Violation: The image specified if activated immediately would exceed the Maximum Time for Firmware Activation (MTFA) value reported in Identify Controller",
271 [NVME_SC_FW_ACTIVATE_PROHIBITED] = "Firmware Activation Prohibited: The image specified is being prohibited from activation by the controller for vendor specific reasons",
272 [NVME_SC_OVERLAPPING_RANGE] = "Overlapping Range: The downloaded firmware image has overlapping ranges",
273 [NVME_SC_NS_INSUFFICIENT_CAP] = "Namespace Insufficient Capacity: Creating the namespace requires more free space than is currently available",
274 [NVME_SC_NS_ID_UNAVAILABLE] = "Namespace Identifier Unavailable: The number of namespaces supported has been exceeded",
275 [NVME_SC_NS_ALREADY_ATTACHED] = "Namespace Already Attached: The controller is already attached to the namespace specified",
276 [NVME_SC_NS_IS_PRIVATE] = "Namespace Is Private: The namespace is private and is already attached to one controller",
277 [NVME_SC_NS_NOT_ATTACHED] = "Namespace Not Attached: The request to detach the controller could not be completed because the controller is not attached to the namespace",
278 [NVME_SC_THIN_PROV_NOT_SUPP] = "Thin Provisioning Not Supported: Thin provisioning is not supported by the controller",
279 [NVME_SC_CTRL_LIST_INVALID] = "Controller List Invalid: The controller list provided contains invalid controller ids",
280 [NVME_SC_SELF_TEST_IN_PROGRESS] = "Device Self-test In Progress: The controller or NVM subsystem already has a device self-test operation in process",
281 [NVME_SC_BP_WRITE_PROHIBITED] = "Boot Partition Write Prohibited: The command tried to modify a locked Boot Partition",
282 [NVME_SC_INVALID_CTRL_ID] = "Invalid Controller Identifier: An invalid controller id was specified",
283 [NVME_SC_INVALID_SEC_CTRL_STATE] = "Invalid Secondary Controller State: The requested secondary controller action is invalid based on the secondary and primary controllers current states",
284 [NVME_SC_INVALID_CTRL_RESOURCES] = "Invalid Number of Controller Resources: The specified number of Flexible Resources is invalid",
285 [NVME_SC_INVALID_RESOURCE_ID] = "Invalid Resource Identifier: At least one of the specified resource identifiers was invalid",
286 [NVME_SC_PMR_SAN_PROHIBITED] = "Sanitize Prohibited While Persistent Memory Region is Enabled",
287 [NVME_SC_ANA_GROUP_ID_INVALID] = "ANA Group Identifier Invalid: The specified ANA Group Identifier (ANAGRPID) is not supported in the submitted command",
288 [NVME_SC_ANA_ATTACH_FAILED] = "ANA Attach Failed: The controller is not attached to the namespace as a result of an ANA condition",
289 [NVME_SC_INSUFFICIENT_CAP] = "Insufficient Capacity: Requested operation requires more free space than is currently available",
290 [NVME_SC_NS_ATTACHMENT_LIMIT_EXCEEDED] = "Namespace Attachment Limit Exceeded: Attaching the ns to a controller causes max number of ns attachments allowed to be exceeded",
291 [NVME_SC_PROHIBIT_CMD_EXEC_NOT_SUPPORTED] = "Prohibition of Command Execution Not Supported",
292 [NVME_SC_IOCS_NOT_SUPPORTED] = "The I/O command set is not supported",
293 [NVME_SC_IOCS_NOT_ENABLED] = "The I/O command set is not enabled",
294 [NVME_SC_IOCS_COMBINATION_REJECTED] = "The I/O command set combination is rejected",
295 [NVME_SC_INVALID_IOCS] = "The I/O command set is invalid",
296 [NVME_SC_ID_UNAVAILABLE] = "Identifier Unavailable: The number of Endurance Groups or NVM Sets supported has been exceeded",
297 [NVME_SC_INVALID_DISCOVERY_INFO] = "Discovery Info Entry not applicable to selected entity",
298 [NVME_SC_ZONING_DATA_STRUCT_LOCKED] = "The requested Zoning data structure is locked on the CDC",
299 [NVME_SC_ZONING_DATA_STRUCT_NOTFND] = "The requested Zoning data structure does not exist on the CDC",
300 [NVME_SC_INSUFFICIENT_DISC_RES] = "Discovery Info entries exceed Discovery Controller's capacity",
301 [NVME_SC_REQSTD_FUNCTION_DISABLED] = "Fabric Zoning is not enabled on the CDC",
302 [NVME_SC_ZONEGRP_ORIGINATOR_INVLD] = "The NQN contained in the ZoneGroup Originator field does not match the Host NQN used by the DDC to connect to the CDC",
303 [NVME_SC_INVALID_CONTROLER_DATA_QUEUE] = "Invalid Controller Data Queue",
304 [NVME_SC_NOT_ENOUGH_RESOURCES] = "Not Enough Resources",
305 [NVME_SC_CONTROLLER_SUSPENDED] = "Controller Suspended: Operation failed because the controller is currently in a suspended state",
306 [NVME_SC_CONTROLLER_NOT_SUSPENDED] = "Controller Not Suspended: Operation failed because the controller is not in a suspended state",
307 [NVME_SC_CONTROLLER_DATA_QUEUE_FULL] = "Controller Data Queue Full",
308 };
309
310 static const char * const nvm_status[] = {
311 [NVME_SC_BAD_ATTRIBUTES] = "Conflicting Attributes: The attributes specified in the command are conflicting",
312 [NVME_SC_INVALID_PI] = "Invalid Protection Information: The command's Protection Information Field settings are invalid for the namespace's Protection Information format",
313 [NVME_SC_READ_ONLY] = "Attempted Write to Read Only Range: The LBA range specified contains read-only blocks",
314 [NVME_SC_CMD_SIZE_LIMIT_EXCEEDED] = "Command Size Limit Exceeded",
315 [NVME_SC_INCOMPATIBLE_NS] = "Incompatible Namespace or Format",
316 [NVME_SC_FAST_COPY_NOT_POSSIBLE] = "Fast Copy Not Possible",
317 [NVME_SC_OVERLAPPING_IO_RANGE] = "Overlapping I/O Range",
318 [NVME_SC_INSUFFICIENT_RESOURCES] = "Insufficient Resources",
319 [NVME_SC_ZNS_INVALID_OP_REQUEST] = "Invalid Zone Operation Request: The operation requested is invalid",
320 [NVME_SC_ZNS_ZRWA_RESOURCES_UNAVAILABLE] = "ZRWA Resources Unavailable: No ZRWAs are available",
321 [NVME_SC_ZNS_BOUNDARY_ERROR] = "Zoned Boundary Error: Invalid Zone Boundary crossing",
322 [NVME_SC_ZNS_FULL] = "Zone Is Full: The accessed zone is in ZSF:Full state",
323 [NVME_SC_ZNS_READ_ONLY] = "Zone Is Read Only: The accessed zone is in ZSRO:Read Only state",
324 [NVME_SC_ZNS_OFFLINE] = "Zone Is Offline: The access zone is in ZSO:Offline state",
325 [NVME_SC_ZNS_INVALID_WRITE] = "Zone Invalid Write: The write to zone was not at the write pointer offset",
326 [NVME_SC_ZNS_TOO_MANY_ACTIVE] = "Too Many Active Zones: The controller does not allow additional active zones",
327 [NVME_SC_ZNS_TOO_MANY_OPENS] = "Too Many Open Zones: The controller does not allow additional open zones",
328 [NVME_SC_ZNS_INVAL_TRANSITION] = "Invalid Zone State Transition: The request is not a valid zone state transition",
329 };
330
331 static const char * const nvmf_status[] = {
332 [NVME_SC_CONNECT_FORMAT] = "Incompatible Format: The NVM subsystem does not support the record format specified by the host",
333 [NVME_SC_CONNECT_CTRL_BUSY] = "Controller Busy: The controller is already associated with a host",
334 [NVME_SC_CONNECT_INVALID_PARAM] = "Connect Invalid Parameters: One or more of the command parameters",
335 [NVME_SC_CONNECT_RESTART_DISC] = "Connect Restart Discovery: The NVM subsystem requested is not available",
336 [NVME_SC_CONNECT_INVALID_HOST] = "Connect Invalid Host: The host is not allowed to establish an association to either any controller in the NVM subsystem or the specified controller",
337 [NVME_SC_DISCONNECT_INVALID_QTYPE] = "Invalid Queue Type: The command was sent on the wrong queue type",
338 [NVME_SC_DISCOVERY_RESTART] = "Discover Restart: The snapshot of the records is now invalid or out of date",
339 [NVME_SC_AUTH_REQUIRED] = "Authentication Required: NVMe in-band authentication is required and the queue has not yet been authenticated",
340 };
341
342 static const char * const media_status[] = {
343 [NVME_SC_WRITE_FAULT] = "Write Fault: The write data could not be committed to the media",
344 [NVME_SC_READ_ERROR] = "Unrecovered Read Error: The read data could not be recovered from the media",
345 [NVME_SC_GUARD_CHECK] = "End-to-end Guard Check Error: The command was aborted due to an end-to-end guard check failure",
346 [NVME_SC_APPTAG_CHECK] = "End-to-end Application Tag Check Error: The command was aborted due to an end-to-end application tag check failure",
347 [NVME_SC_REFTAG_CHECK] = "End-to-end Reference Tag Check Error: The command was aborted due to an end-to-end reference tag check failure",
348 [NVME_SC_COMPARE_FAILED] = "Compare Failure: The command failed due to a miscompare during a Compare command",
349 [NVME_SC_ACCESS_DENIED] = "Access Denied: Access to the namespace and/or LBA range is denied due to lack of access rights",
350 [NVME_SC_UNWRITTEN_BLOCK] = "Deallocated or Unwritten Logical Block: The command failed due to an attempt to read from or verify an LBA range containing a deallocated or unwritten logical block",
351 [NVME_SC_STORAGE_TAG_CHECK] = "End-to-End Storage Tag Check Error: The command was aborted due to an end-to-end storage tag check failure",
352 };
353
354 static const char * const path_status[] = {
355 [NVME_SC_ANA_INTERNAL_PATH_ERROR] = "Internal Path Error: An internal error specific to the controller processing the command prevented completion",
356 [NVME_SC_ANA_PERSISTENT_LOSS] = "Asymmetric Access Persistent Loss: The controller is in a persistent loss state with the requested namespace",
357 [NVME_SC_ANA_INACCESSIBLE] = "Asymmetric Access Inaccessible: The controller is in an inaccessible state with the requested namespace",
358 [NVME_SC_ANA_TRANSITION] = "Asymmetric Access Transition: The controller is currently transitioning states with the requested namespace",
359 [NVME_SC_CTRL_PATH_ERROR] = "Controller Pathing Error: A pathing error was detected by the controller",
360 [NVME_SC_HOST_PATH_ERROR] = "Host Pathing Error: A pathing error was detected by the host",
361 [NVME_SC_CMD_ABORTED_BY_HOST] = "Command Aborted By Host: The command was aborted as a result of host action",
362 };
363
364 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
365 #define ARGSTR(s, i) arg_str(s, ARRAY_SIZE(s), i)
366
367 static const char *arg_str(const char * const *strings,
368 size_t array_size, size_t idx)
369 {
370 if (idx < array_size && strings[idx])
371 return strings[idx];
372 return "unrecognized";
373 }
374
375 const char *nvme_status_to_string(int status, bool fabrics)
376 {
377 const char *s = "Unknown status";
378 __u16 sc, sct;
379
380 if (status < 0)
381 return strerror(errno);
382
383 sc = nvme_status_code(status);
384 sct = nvme_status_code_type(status);
385
386 switch (sct) {
387 case NVME_SCT_GENERIC:
388 s = ARGSTR(generic_status, sc);
389 break;
390 case NVME_SCT_CMD_SPECIFIC:
391 if (sc < ARRAY_SIZE(cmd_spec_status))
392 s = ARGSTR(cmd_spec_status, sc);
393 else if (fabrics)
394 s = ARGSTR(nvmf_status, sc);
395 else
396 s = ARGSTR(nvm_status, sc);
397 break;
398 case NVME_SCT_MEDIA:
399 s = ARGSTR(media_status, sc);
400 break;
401 case NVME_SCT_PATH:
402 s = ARGSTR(path_status, sc);
403 break;
404 case NVME_SCT_VS:
405 s = "Vendor Specific Status";
406 break;
407 default:
408 break;
409 }
410
411 return s;
412 }
413
414 static inline void nvme_init_copy_range_elbt(__u8 *elbt, __u64 eilbrt)
415 {
416 int i;
417
418 for (i = 0; i < 8; i++)
419 elbt[9 - i] = (eilbrt >> (8 * i)) & 0xff;
420 elbt[1] = 0;
421 elbt[0] = 0;
422 }
423
424 void nvme_init_copy_range(struct nvme_copy_range *copy, __u16 *nlbs,
425 __u64 *slbas, __u32 *eilbrts, __u32 *elbatms,
426 __u32 *elbats, __u16 nr)
427 {
428 int i;
429
430 for (i = 0; i < nr; i++) {
431 copy[i].nlb = cpu_to_le16(nlbs[i]);
432 copy[i].slba = cpu_to_le64(slbas[i]);
433 copy[i].eilbrt = cpu_to_le32(eilbrts[i]);
434 copy[i].elbatm = cpu_to_le16(elbatms[i]);
435 copy[i].elbat = cpu_to_le16(elbats[i]);
436 }
437 }
438
439 void nvme_init_copy_range_f1(struct nvme_copy_range_f1 *copy, __u16 *nlbs,
440 __u64 *slbas, __u64 *eilbrts, __u32 *elbatms,
441 __u32 *elbats, __u16 nr)
442 {
443 int i;
444
445 for (i = 0; i < nr; i++) {
446 copy[i].nlb = cpu_to_le16(nlbs[i]);
447 copy[i].slba = cpu_to_le64(slbas[i]);
448 copy[i].elbatm = cpu_to_le16(elbatms[i]);
449 copy[i].elbat = cpu_to_le16(elbats[i]);
450 nvme_init_copy_range_elbt(copy[i].elbt, eilbrts[i]);
451 }
452 }
453
454 void nvme_init_copy_range_f2(struct nvme_copy_range_f2 *copy, __u32 *snsids,
455 __u16 *nlbs, __u64 *slbas, __u16 *sopts,
456 __u32 *eilbrts, __u32 *elbatms, __u32 *elbats,
457 __u16 nr)
458 {
459 int i;
460
461 for (i = 0; i < nr; i++) {
462 copy[i].snsid = cpu_to_le32(snsids[i]);
463 copy[i].nlb = cpu_to_le16(nlbs[i]);
464 copy[i].slba = cpu_to_le64(slbas[i]);
465 copy[i].sopt = cpu_to_le16(sopts[i]);
466 copy[i].eilbrt = cpu_to_le32(eilbrts[i]);
467 copy[i].elbatm = cpu_to_le16(elbatms[i]);
468 copy[i].elbat = cpu_to_le16(elbats[i]);
469 }
470 }
471
472 void nvme_init_copy_range_f3(struct nvme_copy_range_f3 *copy, __u32 *snsids,
473 __u16 *nlbs, __u64 *slbas, __u16 *sopts,
474 __u64 *eilbrts, __u32 *elbatms, __u32 *elbats,
475 __u16 nr)
476 {
477 int i;
478
479 for (i = 0; i < nr; i++) {
480 copy[i].snsid = cpu_to_le32(snsids[i]);
481 copy[i].nlb = cpu_to_le16(nlbs[i]);
482 copy[i].slba = cpu_to_le64(slbas[i]);
483 copy[i].sopt = cpu_to_le16(sopts[i]);
484 copy[i].elbatm = cpu_to_le16(elbatms[i]);
485 copy[i].elbat = cpu_to_le16(elbats[i]);
486 nvme_init_copy_range_elbt(copy[i].elbt, eilbrts[i]);
487 }
488 }
489
490 void nvme_init_dsm_range(struct nvme_dsm_range *dsm, __u32 *ctx_attrs,
491 __u32 *llbas, __u64 *slbas, __u16 nr_ranges)
492 {
493 int i;
494
495 for (i = 0; i < nr_ranges; i++) {
496 dsm[i].cattr = cpu_to_le32(ctx_attrs[i]);
497 dsm[i].nlb = cpu_to_le32(llbas[i]);
498 dsm[i].slba = cpu_to_le64(slbas[i]);
499 }
500 }
501
502 void nvme_init_ctrl_list(struct nvme_ctrl_list *cntlist, __u16 num_ctrls,
503 __u16 *ctrlist)
504 {
505 int i;
506
507 cntlist->num = cpu_to_le16(num_ctrls);
508 for (i = 0; i < num_ctrls; i++)
509 cntlist->identifier[i] = cpu_to_le16(ctrlist[i]);
510 }
511
512 int nvme_get_feature_length(int fid, __u32 cdw11, __u32 *len)
513 {
514 switch (fid) {
515 case NVME_FEAT_FID_LBA_RANGE:
516 *len = sizeof(struct nvme_lba_range_type);
517 break;
518 case NVME_FEAT_FID_AUTO_PST:
519 *len = sizeof(struct nvme_feat_auto_pst);
520 break;
521 case NVME_FEAT_FID_PLM_CONFIG:
522 *len = sizeof(struct nvme_plm_config);
523 break;
524 case NVME_FEAT_FID_TIMESTAMP:
525 *len = sizeof(struct nvme_timestamp);
526 break;
527 case NVME_FEAT_FID_HOST_BEHAVIOR:
528 *len = sizeof(struct nvme_feat_host_behavior);
529 break;
530 case NVME_FEAT_FID_HOST_ID:
531 *len = (cdw11 & 0x1) ? 16 : 8;
532 break;
533 case NVME_FEAT_FID_HOST_MEM_BUF:
534 *len = sizeof(struct nvme_host_mem_buf_attrs);
535 break;
536 case NVME_FEAT_FID_ARBITRATION:
537 case NVME_FEAT_FID_POWER_MGMT:
538 case NVME_FEAT_FID_TEMP_THRESH:
539 case NVME_FEAT_FID_ERR_RECOVERY:
540 case NVME_FEAT_FID_VOLATILE_WC:
541 case NVME_FEAT_FID_NUM_QUEUES:
542 case NVME_FEAT_FID_IRQ_COALESCE:
543 case NVME_FEAT_FID_IRQ_CONFIG:
544 case NVME_FEAT_FID_WRITE_ATOMIC:
545 case NVME_FEAT_FID_ASYNC_EVENT:
546 case NVME_FEAT_FID_KATO:
547 case NVME_FEAT_FID_HCTM:
548 case NVME_FEAT_FID_NOPSC:
549 case NVME_FEAT_FID_RRL:
550 case NVME_FEAT_FID_PLM_WINDOW:
551 case NVME_FEAT_FID_LBA_STS_INTERVAL:
552 case NVME_FEAT_FID_SANITIZE:
553 case NVME_FEAT_FID_ENDURANCE_EVT_CFG:
554 case NVME_FEAT_FID_SW_PROGRESS:
555 case NVME_FEAT_FID_RESV_MASK:
556 case NVME_FEAT_FID_RESV_PERSIST:
557 case NVME_FEAT_FID_WRITE_PROTECT:
558 *len = 0;
559 break;
560 case NVME_FEAT_FID_ENH_CTRL_METADATA:
561 case NVME_FEAT_FID_CTRL_METADATA:
562 case NVME_FEAT_FID_NS_METADATA:
563 *len = sizeof(struct nvme_host_metadata);
564 break;
565 case NVME_FEAT_FID_PERF_CHARACTERISTICS:
566 *len = sizeof(struct nvme_perf_characteristics);
567 break;
568 case NVME_FEAT_FID_FDP_EVENTS:
569 *len = NVME_FEAT_FDPE_NOET_MASK * sizeof(struct nvme_fdp_supported_event_desc);
570 break;
571 default:
572 errno = EINVAL;
573 return -1;
574 }
575 return 0;
576 }
577
578 int nvme_get_feature_length2(int fid, __u32 cdw11, enum nvme_data_tfr dir,
579 __u32 *len)
580 {
581 switch (fid) {
582 case NVME_FEAT_FID_HOST_MEM_BUF:
583 if (dir == NVME_DATA_TFR_HOST_TO_CTRL) {
584 *len = 0;
585 break;
586 }
587 fallthrough;
588 default:
589 return nvme_get_feature_length(fid, cdw11, len);
590 }
591 return 0;
592 }
593
594 int nvme_get_directive_receive_length(enum nvme_directive_dtype dtype,
595 enum nvme_directive_receive_doper doper, __u32 *len)
596 {
597 switch (dtype) {
598 case NVME_DIRECTIVE_DTYPE_IDENTIFY:
599 switch (doper) {
600 case NVME_DIRECTIVE_RECEIVE_IDENTIFY_DOPER_PARAM:
601 *len = sizeof(struct nvme_id_directives);
602 return 0;
603 default:
604 errno = EINVAL;
605 return -1;
606 }
607 case NVME_DIRECTIVE_DTYPE_STREAMS:
608 switch (doper) {
609 case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_PARAM:
610 *len = sizeof(struct nvme_streams_directive_params);
611 return 0;
612 case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_STATUS:
613 *len = (128 * 1024) * sizeof(__le16);
614 return 0;
615 case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_RESOURCE:
616 *len = 0;
617 return 0;
618 default:
619 errno = EINVAL;
620 return -1;
621 }
622 default:
623 errno = EINVAL;
624 return -1;
625 }
626 }
627
628 static const char * const libnvme_status[] = {
629 [ENVME_CONNECT_RESOLVE] = "failed to resolve host",
630 [ENVME_CONNECT_ADDRFAM] = "unrecognized address family",
631 [ENVME_CONNECT_TRADDR] = "failed to get transport address",
632 [ENVME_CONNECT_TARG] = "no transport specified",
633 [ENVME_CONNECT_AARG] = "no transport address specified",
634 [ENVME_CONNECT_OPEN] = "failed to open nvme-fabrics device",
635 [ENVME_CONNECT_WRITE] = "failed to write to nvme-fabrics device",
636 [ENVME_CONNECT_READ] = "failed to read from nvme-fabrics device",
637 [ENVME_CONNECT_PARSE] = "failed to parse ctrl info",
638 [ENVME_CONNECT_INVAL_TR] = "invalid transport type",
639 [ENVME_CONNECT_LOOKUP_SUBSYS_NAME] = "failed to lookup subsystem name",
640 [ENVME_CONNECT_LOOKUP_SUBSYS] = "failed to lookup subsystem",
641 [ENVME_CONNECT_ALREADY] = "already connected",
642 [ENVME_CONNECT_INVAL] = "invalid arguments/configuration",
643 [ENVME_CONNECT_ADDRINUSE] = "hostnqn already in use",
644 [ENVME_CONNECT_NODEV] = "invalid interface",
645 [ENVME_CONNECT_OPNOTSUPP] = "not supported",
646 [ENVME_CONNECT_CONNREFUSED] = "connection refused",
647 [ENVME_CONNECT_ADDRNOTAVAIL] = "cannot assign requested address",
648 [ENVME_CONNECT_IGNORED] = "connection ignored",
649 [ENVME_CONNECT_NOKEY] = "pre-shared TLS key is missing"
650 };
651
652 const char *nvme_errno_to_string(int status)
653 {
654 const char *s = ARGSTR(libnvme_status, status);
655
656 return s;
657 }
658
659 #ifdef HAVE_NETDB
660 char *hostname2traddr(struct nvme_root *r, const char *traddr)
661 {
662 struct addrinfo *host_info, hints = {.ai_family = AF_UNSPEC};
663 char addrstr[NVMF_TRADDR_SIZE];
664 const char *p;
665 char *ret_traddr = NULL;
666 int ret;
667
668 ret = getaddrinfo(traddr, NULL, &hints, &host_info);
669 if (ret) {
670 nvme_msg(r, LOG_ERR, "failed to resolve host %s info\n",
671 traddr);
672 return NULL;
673 }
674
675 switch (host_info->ai_family) {
676 case AF_INET:
677 p = inet_ntop(host_info->ai_family,
678 &(((struct sockaddr_in *)host_info->ai_addr)->sin_addr),
679 addrstr, NVMF_TRADDR_SIZE);
680 break;
681 case AF_INET6:
682 p = inet_ntop(host_info->ai_family,
683 &(((struct sockaddr_in6 *)host_info->ai_addr)->sin6_addr),
684 addrstr, NVMF_TRADDR_SIZE);
685 break;
686 default:
687 nvme_msg(r, LOG_ERR, "unrecognized address family (%d) %s\n",
688 host_info->ai_family, traddr);
689 goto free_addrinfo;
690 }
691
692 if (!p) {
693 nvme_msg(r, LOG_ERR, "failed to get traddr for %s\n",
694 traddr);
695 goto free_addrinfo;
696 }
697 ret_traddr = strdup(addrstr);
698
699 free_addrinfo:
700 freeaddrinfo(host_info);
701 return ret_traddr;
702 }
703 #else /* HAVE_NETDB */
704 char *hostname2traddr(struct nvme_root *r, const char *traddr)
705 {
706 nvme_msg(NULL, LOG_ERR, "No support for hostname IP address resolution; " \
707 "recompile with libnss support.\n");
708
709 errno = -ENOTSUP;
710 return NULL;
711 }
712 #endif /* HAVE_NETDB */
713
714 char *startswith(const char *s, const char *prefix)
715 {
716 size_t l;
717
718 l = strlen(prefix);
719 if (!strncmp(s, prefix, l))
720 return (char *)s + l;
721
722 return NULL;
723 }
724
725 char *kv_strip(char *kv)
726 {
727 char *s;
728
729 kv[strcspn(kv, "\n\r")] = '\0';
730
731 /* Remove leading newline and spaces */
732 kv += strspn(kv, " \t\n\r");
733
734 /* Skip comments and empty lines */
735 if (*kv == '#' || *kv == '\0') {
736 *kv = '\0';
737 return kv;
738 }
739
740 /* Remove trailing newline chars */
741 kv[strcspn(kv, "\n\r")] = '\0';
742
743 /* Delete trailing comments (including spaces/tabs that precede the #)*/
744 s = &kv[strcspn(kv, "#")];
745 *s-- = '\0';
746 while ((s >= kv) && ((*s == ' ') || (*s == '\t'))) {
747 *s-- = '\0';
748 }
749
750 return kv;
751 }
752
753 char *kv_keymatch(const char *kv, const char *key)
754 {
755 char *value;
756
757 value = startswith(kv, key);
758 if (value) {
759 /* Make sure key is a whole word. I.e. it should be
760 * followed by spaces, tabs, or a equal sign. Skip
761 * leading spaces, tabs, and equal sign (=) */
762 switch (*value) {
763 case ' ':
764 case '\t':
765 case '=':
766 value += strspn(value, " \t=");
767 return value;
768 default: ;
769 }
770 }
771
772 return NULL;
773 }
774
775 /**
776 * read_file - read contents of file into @buffer.
777 * @fname: File name
778 * @buffer: Where to save file's contents
779 * @bufsz: Size of @buffer. On success, @bufsz gets decremented by the
780 * number of characters that were writtent to @buffer.
781 *
782 * Return: The number of characters read. If the file cannot be opened or
783 * nothing is read from the file, then this function returns 0.
784 */
785 static size_t read_file(const char * fname, char *buffer, size_t *bufsz)
786 {
787 char *p;
788 _cleanup_file_ FILE *file = NULL;
789 size_t len;
790
791 file = fopen(fname, "re");
792 if (!file)
793 return 0;
794
795 p = fgets(buffer, *bufsz, file);
796
797 if (!p)
798 return 0;
799
800 /* Strip unwanted trailing chars */
801 len = strcspn(buffer, " \t\n\r");
802 *bufsz -= len;
803
804 return len;
805 }
806
807 static size_t copy_value(char *buf, size_t buflen, const char *value)
808 {
809 size_t val_len;
810
811 memset(buf, 0, buflen);
812
813 /* Remove leading " */
814 if (value[0] == '"')
815 value++;
816
817 /* Remove trailing " */
818 val_len = strcspn(value, "\"");
819
820 memcpy(buf, value, MIN(val_len, buflen-1));
821
822 return val_len;
823 }
824
825 size_t get_entity_name(char *buffer, size_t bufsz)
826 {
827 size_t len = !gethostname(buffer, bufsz) ? strlen(buffer) : 0;
828
829 /* Fill the rest of buffer with zeros */
830 memset(&buffer[len], '\0', bufsz-len);
831
832 return len;
833 }
834
835 size_t get_entity_version(char *buffer, size_t bufsz)
836 {
837 _cleanup_file_ FILE *file = NULL;
838 size_t num_bytes = 0;
839
840 /* /proc/sys/kernel/ostype typically contains the string "Linux" */
841 num_bytes += read_file("/proc/sys/kernel/ostype",
842 &buffer[num_bytes], &bufsz);
843
844 /* /proc/sys/kernel/osrelease contains the Linux
845 * version (e.g. 5.8.0-63-generic)
846 */
847 buffer[num_bytes++] = ' '; /* Append a space */
848 num_bytes += read_file("/proc/sys/kernel/osrelease",
849 &buffer[num_bytes], &bufsz);
850
851 /* /etc/os-release contains Key-Value pairs. We only care about the key
852 * PRETTY_NAME, which contains the Distro's version. For example:
853 * "SUSE Linux Enterprise Server 15 SP4", "Ubuntu 20.04.3 LTS", or
854 * "Fedora Linux 35 (Server Edition)"
855 */
856 file = fopen("/etc/os-release", "re");
857 if (file) {
858 char name[64] = {0};
859 size_t name_len = 0;
860 char ver_id[64] = {0};
861 size_t ver_id_len = 0;
862 char line[LINE_MAX];
863 char *p;
864 char *s;
865
866 /* Read key-value pairs one line at a time */
867 while ((!name_len || !ver_id_len) &&
868 (p = fgets(line, sizeof(line), file)) != NULL) {
869 /* Clean up string by removing leading/trailing blanks
870 * and new line characters. Also eliminate trailing
871 * comments, if any.
872 */
873 p = kv_strip(p);
874
875 /* Empty string? */
876 if (*p == '\0')
877 continue;
878
879 s = kv_keymatch(p, "NAME");
880 if (s)
881 name_len = copy_value(name, sizeof(name), s);
882
883 s = kv_keymatch(p, "VERSION_ID");
884 if (s)
885 ver_id_len = copy_value(ver_id, sizeof(ver_id), s);
886 }
887
888 if (name_len) {
889 /* Append a space */
890 buffer[num_bytes++] = ' ';
891 name_len = MIN(name_len, bufsz);
892 memcpy(&buffer[num_bytes], name, name_len);
893 bufsz -= name_len;
894 num_bytes += name_len;
895 }
896
897 if (ver_id_len) {
898 /* Append a space */
899 buffer[num_bytes++] = ' ';
900 ver_id_len = MIN(ver_id_len, bufsz);
901 memcpy(&buffer[num_bytes], ver_id, ver_id_len);
902 bufsz -= ver_id_len;
903 num_bytes += ver_id_len;
904 }
905 }
906
907 /* Fill the rest of buffer with zeros */
908 memset(&buffer[num_bytes], '\0', bufsz);
909
910 return num_bytes;
911 }
912
913 struct nvmf_ext_attr *nvmf_exat_ptr_next(struct nvmf_ext_attr *p)
914 {
915 return (struct nvmf_ext_attr *)
916 ((uintptr_t)p + (ptrdiff_t)nvmf_exat_size(le16_to_cpu(p->exatlen)));
917 }
918
919 const char *nvme_get_version(enum nvme_version type)
920 {
921 switch(type) {
922 case NVME_VERSION_PROJECT:
923 return PROJECT_VERSION;
924 case NVME_VERSION_GIT:
925 return GIT_VERSION;
926 default:
927 return "n/a";
928 }
929 }
930
931 int nvme_uuid_to_string(unsigned char uuid[NVME_UUID_LEN], char *str)
932 {
933 int n;
934 n = snprintf(str, NVME_UUID_LEN_STRING,
935 "%02x%02x%02x%02x-%02x%02x-%02x%02x-"
936 "%02x%02x-%02x%02x%02x%02x%02x%02x",
937 uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
938 uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
939 uuid[12], uuid[13], uuid[14], uuid[15]);
940 return n != NVME_UUID_LEN_STRING - 1 ? -EINVAL : 0;
941 }
942
943 int nvme_uuid_from_string(const char *str, unsigned char uuid[NVME_UUID_LEN])
944 {
945 int n;
946
947 n = sscanf(str,
948 "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx-"
949 "%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
950 &uuid[0], &uuid[1], &uuid[2], &uuid[3], &uuid[4], &uuid[5],
951 &uuid[6], &uuid[7], &uuid[8], &uuid[9], &uuid[10], &uuid[11],
952 &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
953 return n != NVME_UUID_LEN ? -EINVAL : 0;
954
955 }
956
957 int nvme_uuid_random(unsigned char uuid[NVME_UUID_LEN])
958 {
959 _cleanup_fd_ int f = -1;
960 ssize_t n;
961
962 f = open("/dev/urandom", O_RDONLY);
963 if (f < 0)
964 return -errno;
965 n = read(f, uuid, NVME_UUID_LEN);
966 if (n < 0)
967 return -errno;
968 else if (n != NVME_UUID_LEN)
969 return -EIO;
970
971 /*
972 * See https://www.rfc-editor.org/rfc/rfc4122#section-4.4
973 * Algorithms for Creating a UUID from Truly Random
974 * or Pseudo-Random Numbers
975 */
976 uuid[6] = (uuid[6] & 0x0f) | 0x40;
977 uuid[8] = (uuid[8] & 0x3f) | 0x80;
978
979 return 0;
980 }
981
982 int nvme_uuid_find(struct nvme_id_uuid_list *uuid_list, const unsigned char uuid[NVME_UUID_LEN])
983 {
984 const unsigned char uuid_end[NVME_UUID_LEN] = {0};
985
986 if ((!uuid_list) || (!uuid)) {
987 errno = EINVAL;
988 return -1;
989 }
990
991 for (int i = 0; i < NVME_ID_UUID_LIST_MAX; i++) {
992 if (memcmp(uuid, &uuid_list->entry[i].uuid, NVME_UUID_LEN) == 0)
993 return i + 1;
994 if (memcmp(uuid_end, &uuid_list->entry[i].uuid, NVME_UUID_LEN) == 0)
995 break;
996 }
997 errno = ENOENT;
998 return -1;
999 }
1000
1001 #ifdef HAVE_NETDB
1002 static bool _nvme_ipaddrs_eq(struct sockaddr *addr1, struct sockaddr *addr2)
1003 {
1004 struct sockaddr_in *sockaddr_v4;
1005 struct sockaddr_in6 *sockaddr_v6;
1006
1007 if (addr1->sa_family == AF_INET && addr2->sa_family == AF_INET) {
1008 struct sockaddr_in *sockaddr1 = (struct sockaddr_in *)addr1;
1009 struct sockaddr_in *sockaddr2 = (struct sockaddr_in *)addr2;
1010 return sockaddr1->sin_addr.s_addr == sockaddr2->sin_addr.s_addr;
1011 }
1012
1013 if (addr1->sa_family == AF_INET6 && addr2->sa_family == AF_INET6) {
1014 struct sockaddr_in6 *sockaddr1 = (struct sockaddr_in6 *)addr1;
1015 struct sockaddr_in6 *sockaddr2 = (struct sockaddr_in6 *)addr2;
1016 return !memcmp(&sockaddr1->sin6_addr, &sockaddr2->sin6_addr, sizeof(struct in6_addr));
1017 }
1018
1019 switch (addr1->sa_family) {
1020 case AF_INET:
1021 sockaddr_v6 = (struct sockaddr_in6 *)addr2;
1022 if (IN6_IS_ADDR_V4MAPPED(&sockaddr_v6->sin6_addr)) {
1023 sockaddr_v4 = (struct sockaddr_in *)addr1;
1024 return sockaddr_v4->sin_addr.s_addr == sockaddr_v6->sin6_addr.s6_addr32[3];
1025 }
1026 break;
1027
1028 case AF_INET6:
1029 sockaddr_v6 = (struct sockaddr_in6 *)addr1;
1030 if (IN6_IS_ADDR_V4MAPPED(&sockaddr_v6->sin6_addr)) {
1031 sockaddr_v4 = (struct sockaddr_in *)addr2;
1032 return sockaddr_v4->sin_addr.s_addr == sockaddr_v6->sin6_addr.s6_addr32[3];
1033 }
1034 break;
1035
1036 default: ;
1037 }
1038
1039 return false;
1040 }
1041
1042 bool nvme_ipaddrs_eq(const char *addr1, const char *addr2)
1043 {
1044 bool result = false;
1045 struct addrinfo *info1 = NULL, hint1 = { .ai_flags=AI_NUMERICHOST, .ai_family=AF_UNSPEC };
1046 struct addrinfo *info2 = NULL, hint2 = { .ai_flags=AI_NUMERICHOST, .ai_family=AF_UNSPEC };
1047
1048 if (addr1 == addr2)
1049 return true;
1050
1051 if (!addr1 || !addr2)
1052 return false;
1053
1054 if (getaddrinfo(addr1, 0, &hint1, &info1) || !info1)
1055 goto ipaddrs_eq_fail;
1056
1057 if (getaddrinfo(addr2, 0, &hint2, &info2) || !info2)
1058 goto ipaddrs_eq_fail;
1059
1060 result = _nvme_ipaddrs_eq(info1->ai_addr, info2->ai_addr);
1061
1062 ipaddrs_eq_fail:
1063 if (info1)
1064 freeaddrinfo(info1);
1065 if (info2)
1066 freeaddrinfo(info2);
1067 return result;
1068 }
1069 #else /* HAVE_NETDB */
1070 bool nvme_ipaddrs_eq(const char *addr1, const char *addr2)
1071 {
1072 nvme_msg(NULL, LOG_ERR, "no support for hostname ip address resolution; " \
1073 "recompile with libnss support.\n");
1074
1075 return false;
1076 }
1077 #endif /* HAVE_NETDB */
1078
1079 #ifdef HAVE_NETDB
1080 const char *nvme_iface_matching_addr(const struct ifaddrs *iface_list, const char *addr)
1081 {
1082 const struct ifaddrs *iface_it;
1083 struct addrinfo *info = NULL, hint = { .ai_flags = AI_NUMERICHOST, .ai_family = AF_UNSPEC };
1084 const char *iface_name = NULL;
1085
1086 if (!iface_list || !addr || getaddrinfo(addr, 0, &hint, &info) || !info)
1087 return NULL;
1088
1089 /* Walk through the linked list */
1090 for (iface_it = iface_list; iface_it != NULL; iface_it = iface_it->ifa_next) {
1091 struct sockaddr *ifaddr = iface_it->ifa_addr;
1092
1093 if (ifaddr && (ifaddr->sa_family == AF_INET || ifaddr->sa_family == AF_INET6) &&
1094 _nvme_ipaddrs_eq(info->ai_addr, ifaddr)) {
1095 iface_name = iface_it->ifa_name;
1096 break;
1097 }
1098 }
1099
1100 freeaddrinfo(info);
1101
1102 return iface_name;
1103 }
1104
1105 bool nvme_iface_primary_addr_matches(const struct ifaddrs *iface_list, const char *iface, const char *addr)
1106 {
1107 const struct ifaddrs *iface_it;
1108 struct addrinfo *info = NULL, hint = { .ai_flags = AI_NUMERICHOST, .ai_family = AF_UNSPEC };
1109 bool match_found = false;
1110
1111 if (!iface_list || !addr || getaddrinfo(addr, 0, &hint, &info) || !info)
1112 return false;
1113
1114 /* Walk through the linked list */
1115 for (iface_it = iface_list; iface_it != NULL; iface_it = iface_it->ifa_next) {
1116 if (strcmp(iface, iface_it->ifa_name))
1117 continue; /* Not the interface we're looking for*/
1118
1119 /* The interface list is ordered in a way that the primary
1120 * address is listed first. As soon as the parsed address
1121 * matches the family of the address we're looking for, we
1122 * have found the primary address for that family.
1123 */
1124 if (iface_it->ifa_addr && (iface_it->ifa_addr->sa_family == info->ai_addr->sa_family)) {
1125 match_found = _nvme_ipaddrs_eq(info->ai_addr, iface_it->ifa_addr);
1126 break;
1127 }
1128 }
1129
1130 freeaddrinfo(info);
1131
1132 return match_found;
1133 }
1134
1135 #else /* HAVE_NETDB */
1136
1137 const char *nvme_iface_matching_addr(const struct ifaddrs *iface_list, const char *addr)
1138 {
1139 nvme_msg(NULL, LOG_ERR, "no support for interface lookup; "
1140 "recompile with libnss support.\n");
1141
1142 return NULL;
1143 }
1144
1145 bool nvme_iface_primary_addr_matches(const struct ifaddrs *iface_list, const char *iface, const char *addr)
1146 {
1147 nvme_msg(NULL, LOG_ERR, "no support for interface lookup; "
1148 "recompile with libnss support.\n");
1149
1150 return false;
1151 }
1152
1153 #endif /* HAVE_NETDB */
1154
1155 void *__nvme_alloc(size_t len)
1156 {
1157 size_t _len = round_up(len, 0x1000);
1158 void *p;
1159
1160 if (posix_memalign((void *)&p, getpagesize(), _len))
1161 return NULL;
1162
1163 memset(p, 0, _len);
1164 return p;
1165 }
1166
1167 void *__nvme_realloc(void *p, size_t len)
1168 {
1169 size_t old_len = malloc_usable_size(p);
1170
1171 void *result = __nvme_alloc(len);
1172
1173 if (p && result) {
1174 memcpy(result, p, min(old_len, len));
1175 free(p);
1176 }
1177
1178 return result;
1179 }