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