xref: /freebsd/sbin/nvmecontrol/firmware.c (revision 1d386b48a555f61cb7325543adbbb5c3f3407a66)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013 EMC Corp.
5  * All rights reserved.
6  *
7  * Copyright (C) 2012-2013 Intel Corporation
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/ioccom.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 
38 #include <ctype.h>
39 #include <err.h>
40 #include <fcntl.h>
41 #include <inttypes.h>
42 #include <stdbool.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <sysexits.h>
48 #include <unistd.h>
49 
50 #include "nvmecontrol.h"
51 
52 /* Tables for command line parsing */
53 
54 static cmd_fn_t firmware;
55 
56 #define NONE 0xffffffffu
57 static struct options {
58 	bool		activate;
59 	uint32_t	slot;
60 	const char	*fw_img;
61 	const char	*dev;
62 } opt = {
63 	.activate = false,
64 	.slot = NONE,
65 	.fw_img = NULL,
66 	.dev = NULL,
67 };
68 
69 static const struct opts firmware_opts[] = {
70 #define OPT(l, s, t, opt, addr, desc) { l, s, t, &opt.addr, desc }
71 	OPT("activate", 'a', arg_none, opt, activate,
72 	    "Attempt to activate firmware"),
73 	OPT("slot", 's', arg_uint32, opt, slot,
74 	    "Slot to activate and/or download firmware to"),
75 	OPT("firmware", 'f', arg_path, opt, fw_img,
76 	    "Firmware image to download"),
77 	{ NULL, 0, arg_none, NULL, NULL }
78 };
79 #undef OPT
80 
81 static const struct args firmware_args[] = {
82 	{ arg_string, &opt.dev, "controller-id|namespace-id" },
83 	{ arg_none, NULL, NULL },
84 };
85 
86 static struct cmd firmware_cmd = {
87 	.name = "firmware",
88 	.fn = firmware,
89 	.descr = "Download firmware image to controller",
90 	.ctx_size = sizeof(opt),
91 	.opts = firmware_opts,
92 	.args = firmware_args,
93 };
94 
95 CMD_COMMAND(firmware_cmd);
96 
97 /* End of tables for command line parsing */
98 
99 static int
100 slot_has_valid_firmware(int fd, int slot)
101 {
102 	struct nvme_firmware_page	fw;
103 	int				has_fw = false;
104 
105 	read_logpage(fd, NVME_LOG_FIRMWARE_SLOT,
106 	    NVME_GLOBAL_NAMESPACE_TAG, 0, 0, 0, &fw, sizeof(fw));
107 
108 	if (fw.revision[slot-1] != 0LLU)
109 		has_fw = true;
110 
111 	return (has_fw);
112 }
113 
114 static void
115 read_image_file(const char *path, void **buf, int32_t *size)
116 {
117 	struct stat	sb;
118 	int32_t		filesize;
119 	int		fd;
120 
121 	*size = 0;
122 	*buf = NULL;
123 
124 	if ((fd = open(path, O_RDONLY)) < 0)
125 		err(EX_NOINPUT, "unable to open '%s'", path);
126 	if (fstat(fd, &sb) < 0)
127 		err(EX_NOINPUT, "unable to stat '%s'", path);
128 
129 	/*
130 	 * The NVMe spec does not explicitly state a maximum firmware image
131 	 *  size, although one can be inferred from the dword size limitation
132 	 *  for the size and offset fields in the Firmware Image Download
133 	 *  command.
134 	 *
135 	 * Technically, the max is UINT32_MAX * sizeof(uint32_t), since the
136 	 *  size and offsets are specified in terms of dwords (not bytes), but
137 	 *  realistically INT32_MAX is sufficient here and simplifies matters
138 	 *  a bit.
139 	 */
140 	if (sb.st_size > INT32_MAX)
141 		errx(EX_USAGE, "size of file '%s' is too large (%jd bytes)",
142 		    path, (intmax_t)sb.st_size);
143 	filesize = (int32_t)sb.st_size;
144 	if ((*buf = malloc(filesize)) == NULL)
145 		errx(EX_OSERR, "unable to malloc %d bytes", filesize);
146 	if ((*size = read(fd, *buf, filesize)) < 0)
147 		err(EX_IOERR, "error reading '%s'", path);
148 	/* XXX assuming no short reads */
149 	if (*size != filesize)
150 		errx(EX_IOERR,
151 		    "error reading '%s' (read %d bytes, requested %d bytes)",
152 		    path, *size, filesize);
153 	close(fd);
154 }
155 
156 static void
157 update_firmware(int fd, uint8_t *payload, int32_t payload_size, uint8_t fwug)
158 {
159 	struct nvme_pt_command	pt;
160 	uint64_t		max_xfer_size;
161 	int32_t			off;
162 	uint32_t		resid, size;
163 	void			*chunk;
164 
165 	off = 0;
166 	resid = payload_size;
167 
168 	if (ioctl(fd, NVME_GET_MAX_XFER_SIZE, &max_xfer_size) < 0)
169 		err(EX_IOERR, "query max transfer size failed");
170 	if (fwug != 0 && fwug != 0xFF)
171 		max_xfer_size = MIN(max_xfer_size, (uint64_t)fwug << 12);
172 
173 	if ((chunk = aligned_alloc(PAGE_SIZE, max_xfer_size)) == NULL)
174 		errx(EX_OSERR, "unable to malloc %zd bytes", (size_t)max_xfer_size);
175 
176 	while (resid > 0) {
177 		size = (resid >= max_xfer_size) ?  max_xfer_size : resid;
178 		memcpy(chunk, payload + off, size);
179 
180 		memset(&pt, 0, sizeof(pt));
181 		pt.cmd.opc = NVME_OPC_FIRMWARE_IMAGE_DOWNLOAD;
182 		pt.cmd.cdw10 = htole32((size / sizeof(uint32_t)) - 1);
183 		pt.cmd.cdw11 = htole32(off / sizeof(uint32_t));
184 		pt.buf = chunk;
185 		pt.len = size;
186 		pt.is_read = 0;
187 
188 		if (ioctl(fd, NVME_PASSTHROUGH_CMD, &pt) < 0)
189 			err(EX_IOERR, "firmware download request failed");
190 
191 		if (nvme_completion_is_error(&pt.cpl))
192 			errx(EX_IOERR, "firmware download request returned error");
193 
194 		resid -= size;
195 		off += size;
196 	}
197 	free(chunk);
198 }
199 
200 static int
201 activate_firmware(int fd, int slot, int activate_action)
202 {
203 	struct nvme_pt_command	pt;
204 	uint16_t sct, sc;
205 
206 	memset(&pt, 0, sizeof(pt));
207 	pt.cmd.opc = NVME_OPC_FIRMWARE_ACTIVATE;
208 	pt.cmd.cdw10 = htole32((activate_action << 3) | slot);
209 	pt.is_read = 0;
210 
211 	if (ioctl(fd, NVME_PASSTHROUGH_CMD, &pt) < 0)
212 		err(EX_IOERR, "firmware activate request failed");
213 
214 	sct = NVME_STATUS_GET_SCT(pt.cpl.status);
215 	sc = NVME_STATUS_GET_SC(pt.cpl.status);
216 
217 	if (sct == NVME_SCT_COMMAND_SPECIFIC &&
218 	    sc == NVME_SC_FIRMWARE_REQUIRES_RESET)
219 		return 1;
220 
221 	if (nvme_completion_is_error(&pt.cpl))
222 		errx(EX_IOERR, "firmware activate request returned error");
223 
224 	return 0;
225 }
226 
227 static void
228 firmware(const struct cmd *f, int argc, char *argv[])
229 {
230 	int				fd = -1;
231 	int				activate_action, reboot_required;
232 	char				prompt[64];
233 	void				*buf = NULL;
234 	char				*path;
235 	int32_t				size = 0, nsid;
236 	uint16_t			oacs_fw;
237 	uint8_t				fw_slot1_ro, fw_num_slots;
238 	struct nvme_controller_data	cdata;
239 
240 	if (arg_parse(argc, argv, f))
241 		return;
242 
243 	if (opt.slot == 0) {
244 		fprintf(stderr,
245 		    "0 is not a valid slot number. "
246 		    "Slot numbers start at 1.\n");
247 		arg_help(argc, argv, f);
248 	} else if (opt.slot > 7 && opt.slot != NONE) {
249 		fprintf(stderr,
250 		    "Slot number %s specified which is "
251 		    "greater than max allowed slot number of "
252 		    "7.\n", optarg);
253 		arg_help(argc, argv, f);
254 	}
255 
256 	if (!opt.activate && opt.fw_img == NULL) {
257 		fprintf(stderr,
258 		    "Neither a replace ([-f path_to_firmware]) nor "
259 		    "activate ([-a]) firmware image action\n"
260 		    "was specified.\n");
261 		arg_help(argc, argv, f);
262 	}
263 
264 	if (opt.activate && opt.fw_img == NULL && opt.slot == 0) {
265 		fprintf(stderr,
266 		    "Slot number to activate not specified.\n");
267 		arg_help(argc, argv, f);
268 	}
269 
270 	open_dev(opt.dev, &fd, 1, 1);
271 	get_nsid(fd, &path, &nsid);
272 	if (nsid != 0) {
273 		close(fd);
274 		open_dev(path, &fd, 1, 1);
275 	}
276 	free(path);
277 
278 	if (read_controller_data(fd, &cdata))
279 		errx(EX_IOERR, "Identify request failed");
280 
281 	oacs_fw = (cdata.oacs >> NVME_CTRLR_DATA_OACS_FIRMWARE_SHIFT) &
282 		NVME_CTRLR_DATA_OACS_FIRMWARE_MASK;
283 
284 	if (oacs_fw == 0)
285 		errx(EX_UNAVAILABLE,
286 		    "controller does not support firmware activate/download");
287 
288 	fw_slot1_ro = (cdata.frmw >> NVME_CTRLR_DATA_FRMW_SLOT1_RO_SHIFT) &
289 		NVME_CTRLR_DATA_FRMW_SLOT1_RO_MASK;
290 
291 	if (opt.fw_img && opt.slot == 1 && fw_slot1_ro)
292 		errx(EX_UNAVAILABLE, "slot %d is marked as read only", opt.slot);
293 
294 	fw_num_slots = (cdata.frmw >> NVME_CTRLR_DATA_FRMW_NUM_SLOTS_SHIFT) &
295 		NVME_CTRLR_DATA_FRMW_NUM_SLOTS_MASK;
296 
297 	if (opt.slot > fw_num_slots)
298 		errx(EX_UNAVAILABLE,
299 		    "slot %d specified but controller only supports %d slots",
300 		    opt.slot, fw_num_slots);
301 
302 	if (opt.activate && opt.fw_img == NULL &&
303 	    !slot_has_valid_firmware(fd, opt.slot))
304 		errx(EX_UNAVAILABLE,
305 		    "slot %d does not contain valid firmware,\n"
306 		    "try 'nvmecontrol logpage -p 3 %s' to get a list "
307 		    "of available images\n",
308 		    opt.slot, opt.dev);
309 
310 	if (opt.fw_img)
311 		read_image_file(opt.fw_img, &buf, &size);
312 
313 	if (opt.fw_img != NULL&& opt.activate)
314 		printf("You are about to download and activate "
315 		       "firmware image (%s) to controller %s.\n"
316 		       "This may damage your controller and/or "
317 		       "overwrite an existing firmware image.\n",
318 		       opt.fw_img, opt.dev);
319 	else if (opt.activate)
320 		printf("You are about to activate a new firmware "
321 		       "image on controller %s.\n"
322 		       "This may damage your controller.\n",
323 		       opt.dev);
324 	else if (opt.fw_img != NULL)
325 		printf("You are about to download firmware image "
326 		       "(%s) to controller %s.\n"
327 		       "This may damage your controller and/or "
328 		       "overwrite an existing firmware image.\n",
329 		       opt.fw_img, opt.dev);
330 
331 	printf("Are you sure you want to continue? (yes/no) ");
332 	while (1) {
333 		fgets(prompt, sizeof(prompt), stdin);
334 		if (strncasecmp(prompt, "yes", 3) == 0)
335 			break;
336 		if (strncasecmp(prompt, "no", 2) == 0)
337 			exit(EX_DATAERR);
338 		printf("Please answer \"yes\" or \"no\". ");
339 	}
340 
341 	if (opt.fw_img != NULL) {
342 		update_firmware(fd, buf, size, cdata.fwug);
343 		if (opt.activate)
344 			activate_action = NVME_AA_REPLACE_ACTIVATE;
345 		else
346 			activate_action = NVME_AA_REPLACE_NO_ACTIVATE;
347 	} else {
348 		activate_action = NVME_AA_ACTIVATE;
349 	}
350 
351 	reboot_required = activate_firmware(fd, opt.slot, activate_action);
352 
353 	if (opt.activate) {
354 		if (reboot_required) {
355 			printf("New firmware image activated but requires "
356 			       "conventional reset (i.e. reboot) to "
357 			       "complete activation.\n");
358 		} else {
359 			printf("New firmware image activated and will take "
360 			       "effect after next controller reset.\n"
361 			       "Controller reset can be initiated via "
362 			       "'nvmecontrol reset %s'\n",
363 			       opt.dev);
364 		}
365 	}
366 
367 	close(fd);
368 	exit(0);
369 }
370