xref: /freebsd-14.2/sbin/camcontrol/fwdownload.c (revision ce6c84ab)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 Sandvine Incorporated. All rights reserved.
5  * Copyright (c) 2002-2011 Andre Albsmeier <[email protected]>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This software is derived from Andre Albsmeier's fwprog.c which contained
32  * the following note:
33  *
34  * Many thanks goes to Marc Frajola <[email protected]> from
35  * TeraSolutions for the initial idea and his programme for upgrading
36  * the firmware of I*M DDYS drives.
37  */
38 
39 /*
40  * BEWARE:
41  *
42  * The fact that you see your favorite vendor listed below does not
43  * imply that your equipment won't break when you use this software
44  * with it. It only means that the firmware of at least one device type
45  * of each vendor listed has been programmed successfully using this code.
46  *
47  * The -s option simulates a download but does nothing apart from that.
48  * It can be used to check what chunk sizes would have been used with the
49  * specified device.
50  */
51 
52 #include <sys/cdefs.h>
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 
56 #include <err.h>
57 #include <fcntl.h>
58 #include <stdbool.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #include <cam/cam.h>
65 #include <cam/scsi/scsi_all.h>
66 #include <cam/scsi/scsi_pass.h>
67 #include <cam/scsi/scsi_message.h>
68 #include <camlib.h>
69 
70 #include "progress.h"
71 
72 #include "camcontrol.h"
73 
74 #define	WB_TIMEOUT 50000	/* 50 seconds */
75 
76 typedef enum {
77 	VENDOR_HGST,
78 	VENDOR_HITACHI,
79 	VENDOR_HP,
80 	VENDOR_IBM,
81 	VENDOR_PLEXTOR,
82 	VENDOR_QUALSTAR,
83 	VENDOR_QUANTUM,
84 	VENDOR_SAMSUNG,
85 	VENDOR_SEAGATE,
86 	VENDOR_SMART,
87 	VENDOR_TOSHIBA,
88 	VENDOR_ATA,
89 	VENDOR_UNKNOWN
90 } fw_vendor_t;
91 
92 /*
93  * FW_TUR_READY:     The drive must return good status for a test unit ready.
94  *
95  * FW_TUR_NOT_READY: The drive must return not ready status for a test unit
96  *		     ready.  You may want this in a removable media drive.
97  *
98  * FW_TUR_NA:	     It doesn't matter whether the drive is ready or not.
99  * 		     This may be the case for a removable media drive.
100  */
101 typedef enum {
102 	FW_TUR_NONE,
103 	FW_TUR_READY,
104 	FW_TUR_NOT_READY,
105 	FW_TUR_NA
106 } fw_tur_status;
107 
108 /*
109  * FW_TIMEOUT_DEFAULT:		Attempt to probe for a WRITE BUFFER timeout
110  *				value from the drive.  If we get an answer,
111  *				use the Recommended timeout.  Otherwise,
112  * 				use the default value from the table.
113  *
114  * FW_TIMEOUT_DEV_REPORTED:	The timeout value was probed directly from
115  *				the device.
116  *
117  * FW_TIMEOUT_NO_PROBE:		Do not ask the device for a WRITE BUFFER
118  * 				timeout value.  Use the device-specific
119  *				value.
120  *
121  * FW_TIMEOUT_USER_SPEC:	The user specified a timeout on the command
122  *				line with the -t option.  This overrides any
123  *				probe or default timeout.
124  */
125 typedef enum {
126 	FW_TIMEOUT_DEFAULT,
127 	FW_TIMEOUT_DEV_REPORTED,
128 	FW_TIMEOUT_NO_PROBE,
129 	FW_TIMEOUT_USER_SPEC
130 } fw_timeout_type;
131 
132 /*
133  * type: 		Enumeration for the particular vendor.
134  *
135  * pattern:		Pattern to match for the Vendor ID from the SCSI
136  *			Inquiry data.
137  *
138  * dev_type:		SCSI device type to match, or T_ANY to match any
139  *			device from the given vendor.  Note that if there
140  *			is a specific device type listed for a particular
141  *			vendor, it must be listed before a T_ANY entry.
142  *
143  * max_pkt_size:	Maximum packet size when talking to a device.  Note
144  *			that although large data sizes may be supported by
145  *			the target device, they may not be supported by the
146  *			OS or the controller.
147  *
148  * cdb_byte2:		This specifies byte 2 (byte 1 when counting from 0)
149  *			of the CDB.  This is generally the WRITE BUFFER mode.
150  *
151  * cdb_byte2_last:	This specifies byte 2 for the last chunk of the
152  *			download.
153  *
154  * inc_cdb_buffer_id:	Increment the buffer ID by 1 for each chunk sent
155  *			down to the drive.
156  *
157  * inc_cdb_offset:	Increment the offset field in the CDB with the byte
158  *			offset into the firmware file.
159  *
160  * tur_status:		Pay attention to whether the device is ready before
161  *			upgrading the firmware, or not.  See above for the
162  *			values.
163  */
164 struct fw_vendor {
165 	fw_vendor_t type;
166 	const char *pattern;
167 	int dev_type;
168 	int max_pkt_size;
169 	uint8_t cdb_byte2;
170 	uint8_t cdb_byte2_last;
171 	int inc_cdb_buffer_id;
172 	int inc_cdb_offset;
173 	fw_tur_status tur_status;
174 	int timeout_ms;
175 	fw_timeout_type timeout_type;
176 };
177 
178 /*
179  * Vendor notes:
180  *
181  * HGST:     The packets need to be sent in multiples of 4K.
182  *
183  * IBM:      For LTO and TS drives, the buffer ID is ignored in mode 7 (and
184  * 	     some other modes).  It treats the request as a firmware download.
185  *           The offset (and therefore the length of each chunk sent) needs
186  *           to be a multiple of the offset boundary specified for firmware
187  *           (buffer ID 4) in the read buffer command.  At least for LTO-6,
188  *           that seems to be 0, but using a 32K chunk size should satisfy
189  *           most any alignment requirement.
190  *
191  * SmrtStor: Mode 5 is also supported, but since the firmware is 400KB or
192  *           so, we can't fit it in a single request in most cases.
193  */
194 static struct fw_vendor vendors_list[] = {
195 	{VENDOR_HGST,	 	"HGST",		T_DIRECT,
196 	0x1000, 0x07, 0x07, 1, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
197 	{VENDOR_HITACHI, 	"HITACHI",	T_ANY,
198 	0x8000, 0x05, 0x05, 1, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
199 	{VENDOR_HP,	 	"HP",		T_ANY,
200 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
201 	{VENDOR_IBM,		"IBM",		T_SEQUENTIAL,
202 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_NA, 300 * 1000, FW_TIMEOUT_DEFAULT},
203 	{VENDOR_IBM,		"IBM",		T_ANY,
204 	0x8000, 0x05, 0x05, 1, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
205 	{VENDOR_PLEXTOR,	"PLEXTOR",	T_ANY,
206 	0x2000, 0x04, 0x05, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
207 	{VENDOR_QUALSTAR,	"QUALSTAR",	T_ANY,
208 	0x2030, 0x05, 0x05, 0, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
209 	{VENDOR_QUANTUM,	"QUANTUM",	T_ANY,
210 	0x2000, 0x04, 0x05, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
211 	{VENDOR_SAMSUNG,	"SAMSUNG",	T_ANY,
212 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
213 	{VENDOR_SEAGATE,	"SEAGATE",	T_ANY,
214 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
215 	{VENDOR_SMART,		"SmrtStor",	T_DIRECT,
216 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
217 	{VENDOR_TOSHIBA,	"TOSHIBA",	T_DIRECT,
218 	0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
219 	{VENDOR_HGST,	 	"WD",		T_DIRECT,
220 	0x1000, 0x07, 0x07, 1, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
221 	{VENDOR_HGST,	 	"WDC",		T_DIRECT,
222 	0x1000, 0x07, 0x07, 1, 0, FW_TUR_READY, WB_TIMEOUT, FW_TIMEOUT_DEFAULT},
223 
224 	/*
225 	 * We match any ATA device.  This is really just a placeholder,
226 	 * since we won't actually send a WRITE BUFFER with any of the
227 	 * listed parameters.  If a SATA device is behind a SAS controller,
228 	 * the SCSI to ATA translation code (at least for LSI) doesn't
229 	 * generally translate a SCSI WRITE BUFFER into an ATA DOWNLOAD
230 	 * MICROCODE command.  So, we use the SCSI ATA PASS_THROUGH command
231 	 * to send the ATA DOWNLOAD MICROCODE command instead.
232 	 */
233 	{VENDOR_ATA,		"ATA",		T_ANY,
234 	 0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT,
235 	 FW_TIMEOUT_NO_PROBE},
236 	{VENDOR_UNKNOWN,	NULL,		T_ANY,
237 	0x0000, 0x00, 0x00, 0, 0, FW_TUR_NONE, WB_TIMEOUT, FW_TIMEOUT_DEFAULT}
238 };
239 
240 struct fw_timeout_desc {
241 	fw_timeout_type timeout_type;
242 	const char *timeout_desc;
243 };
244 
245 static const struct fw_timeout_desc fw_timeout_desc_table[] = {
246 	{ FW_TIMEOUT_DEFAULT, "the default" },
247 	{ FW_TIMEOUT_DEV_REPORTED, "recommended by this particular device" },
248 	{ FW_TIMEOUT_NO_PROBE, "the default" },
249 	{ FW_TIMEOUT_USER_SPEC, "what was specified on the command line" }
250 };
251 
252 #ifndef ATA_DOWNLOAD_MICROCODE
253 #define ATA_DOWNLOAD_MICROCODE	0x92
254 #endif
255 
256 #define USE_OFFSETS_FEATURE	0x3
257 
258 #ifndef LOW_SECTOR_SIZE
259 #define LOW_SECTOR_SIZE		512
260 #endif
261 
262 #define ATA_MAKE_LBA(o, p)	\
263 	((((((o) / LOW_SECTOR_SIZE) >> 8) & 0xff) << 16) | \
264 	  ((((o) / LOW_SECTOR_SIZE) & 0xff) << 8) | \
265 	  ((((p) / LOW_SECTOR_SIZE) >> 8) & 0xff))
266 
267 #define ATA_MAKE_SECTORS(p)	(((p) / 512) & 0xff)
268 
269 #ifndef UNKNOWN_MAX_PKT_SIZE
270 #define UNKNOWN_MAX_PKT_SIZE	0x8000
271 #endif
272 
273 static struct fw_vendor *fw_get_vendor(struct cam_device *cam_dev,
274 				       struct ata_params *ident_buf);
275 static int fw_get_timeout(struct cam_device *cam_dev, struct fw_vendor *vp,
276 			  int task_attr, int retry_count, int timeout);
277 static int fw_validate_ibm(struct cam_device *dev, int retry_count,
278 			   int timeout, int fd, char *buf,
279 			    const char *fw_img_path, int quiet);
280 static char *fw_read_img(struct cam_device *dev, int retry_count,
281 			 int timeout, int quiet, const char *fw_img_path,
282 			 struct fw_vendor *vp, int *num_bytes);
283 static int fw_check_device_ready(struct cam_device *dev,
284 				 camcontrol_devtype devtype,
285 				 struct fw_vendor *vp, int printerrors,
286 				 int timeout);
287 static int fw_download_img(struct cam_device *cam_dev,
288 			   struct fw_vendor *vp, char *buf, int img_size,
289 			   int sim_mode, int printerrors, int quiet,
290 			   int retry_count, int timeout, const char */*name*/,
291 			   camcontrol_devtype devtype);
292 
293 /*
294  * Find entry in vendors list that belongs to
295  * the vendor of given cam device.
296  */
297 static struct fw_vendor *
fw_get_vendor(struct cam_device * cam_dev,struct ata_params * ident_buf)298 fw_get_vendor(struct cam_device *cam_dev, struct ata_params *ident_buf)
299 {
300 	char vendor[42];
301 	struct fw_vendor *vp;
302 
303 	if (cam_dev == NULL)
304 		return (NULL);
305 
306 	if (ident_buf != NULL) {
307 		cam_strvis((u_char *)vendor, ident_buf->model,
308 		    sizeof(ident_buf->model), sizeof(vendor));
309 		for (vp = vendors_list; vp->pattern != NULL; vp++) {
310 			if (vp->type == VENDOR_ATA)
311 				return (vp);
312 		}
313 	} else {
314 		cam_strvis((u_char *)vendor, (u_char *)cam_dev->inq_data.vendor,
315 		    sizeof(cam_dev->inq_data.vendor), sizeof(vendor));
316 	}
317 	for (vp = vendors_list; vp->pattern != NULL; vp++) {
318 		if (!cam_strmatch((const u_char *)vendor,
319 		    (const u_char *)vp->pattern, strlen(vendor))) {
320 			if ((vp->dev_type == T_ANY)
321 			 || (vp->dev_type == SID_TYPE(&cam_dev->inq_data)))
322 				break;
323 		}
324 	}
325 	return (vp);
326 }
327 
328 static int
fw_get_timeout(struct cam_device * cam_dev,struct fw_vendor * vp,int task_attr,int retry_count,int timeout)329 fw_get_timeout(struct cam_device *cam_dev, struct fw_vendor *vp,
330 	       int task_attr, int retry_count, int timeout)
331 {
332 	struct scsi_report_supported_opcodes_one *one;
333 	struct scsi_report_supported_opcodes_timeout *td;
334 	uint8_t *buf = NULL;
335 	uint32_t fill_len = 0, cdb_len = 0, rec_timeout = 0;
336 	int retval = 0;
337 
338 	/*
339 	 * If the user has specified a timeout on the command line, we let
340 	 * him override any default or probed value.
341 	 */
342 	if (timeout != 0) {
343 		vp->timeout_type = FW_TIMEOUT_USER_SPEC;
344 		vp->timeout_ms = timeout;
345 		goto bailout;
346 	}
347 
348 	/*
349 	 * Check to see whether we should probe for a timeout for this
350 	 * device.
351 	 */
352 	if (vp->timeout_type == FW_TIMEOUT_NO_PROBE)
353 		goto bailout;
354 
355 	retval = scsigetopcodes(/*device*/ cam_dev,
356 				/*opcode_set*/ 1,
357 				/*opcode*/ WRITE_BUFFER,
358 				/*show_sa_errors*/ 1,
359 				/*sa_set*/ 0,
360 				/*service_action*/ 0,
361 				/*timeout_desc*/ 1,
362 				/*task_attr*/ task_attr,
363 				/*retry_count*/ retry_count,
364 				/*timeout*/ 10000,
365 				/*verbose*/ 0,
366 				/*fill_len*/ &fill_len,
367 				/*data_ptr*/ &buf);
368 	/*
369 	 * It isn't an error if we can't get a timeout descriptor.  We just
370 	 * continue on with the default timeout.
371 	 */
372 	if (retval != 0) {
373 		retval = 0;
374 		goto bailout;
375 	}
376 
377 	/*
378 	 * Even if the drive didn't return a SCSI error, if we don't have
379 	 * enough data to contain the one opcode descriptor, the CDB
380 	 * structure and a timeout descriptor, we don't have the timeout
381 	 * value we're looking for.  So we'll just fall back to the
382 	 * default value.
383 	 */
384 	if (fill_len < (sizeof(*one) + sizeof(struct scsi_write_buffer) +
385 	    sizeof(*td)))
386 		goto bailout;
387 
388 	one = (struct scsi_report_supported_opcodes_one *)buf;
389 
390 	/*
391 	 * If the drive claims to not support the WRITE BUFFER command...
392 	 * fall back to the default timeout value and let things fail on
393 	 * the actual firmware download.
394 	 */
395 	if ((one->support & RSO_ONE_SUP_MASK) == RSO_ONE_SUP_NOT_SUP)
396 		goto bailout;
397 
398 	cdb_len = scsi_2btoul(one->cdb_length);
399 	td = (struct scsi_report_supported_opcodes_timeout *)
400 	    &buf[sizeof(*one) + cdb_len];
401 
402 	rec_timeout = scsi_4btoul(td->recommended_time);
403 	/*
404 	 * If the recommended timeout is 0, then the device has probably
405 	 * returned a bogus value.
406 	 */
407 	if (rec_timeout == 0)
408 		goto bailout;
409 
410 	/* CAM timeouts are in ms */
411 	rec_timeout *= 1000;
412 
413 	vp->timeout_ms = rec_timeout;
414 	vp->timeout_type = FW_TIMEOUT_DEV_REPORTED;
415 
416 bailout:
417 	return (retval);
418 }
419 
420 #define	SVPD_IBM_FW_DESIGNATION		0x03
421 
422 /*
423  * IBM LTO and TS tape drives have an INQUIRY VPD page 0x3 with the following
424  * format:
425  */
426 struct fw_ibm_tape_fw_designation {
427 	uint8_t	device;
428 	uint8_t page_code;
429 	uint8_t reserved;
430 	uint8_t length;
431 	uint8_t ascii_length;
432 	uint8_t reserved2[3];
433 	uint8_t load_id[4];
434 	uint8_t fw_rev[4];
435 	uint8_t ptf_number[4];
436 	uint8_t patch_number[4];
437 	uint8_t ru_name[8];
438 	uint8_t lib_seq_num[5];
439 };
440 
441 /*
442  * The firmware for IBM tape drives has the following header format.  The
443  * load_id and ru_name in the header file should match what is returned in
444  * VPD page 0x3.
445  */
446 struct fw_ibm_tape_fw_header {
447 	uint8_t unspec[4];
448 	uint8_t length[4];		/* Firmware and header! */
449 	uint8_t load_id[4];
450 	uint8_t fw_rev[4];
451 	uint8_t reserved[8];
452 	uint8_t ru_name[8];
453 };
454 
455 static int
fw_validate_ibm(struct cam_device * dev,int retry_count,int timeout,int fd,char * buf,const char * fw_img_path,int quiet)456 fw_validate_ibm(struct cam_device *dev, int retry_count, int timeout, int fd,
457 		char *buf, const char *fw_img_path, int quiet)
458 {
459 	union ccb *ccb;
460 	struct fw_ibm_tape_fw_designation vpd_page;
461 	struct fw_ibm_tape_fw_header *header;
462 	char drive_rev[sizeof(vpd_page.fw_rev) + 1];
463 	char file_rev[sizeof(vpd_page.fw_rev) + 1];
464 	int retval = 1;
465 
466 	ccb = cam_getccb(dev);
467 	if (ccb == NULL) {
468 		warnx("couldn't allocate CCB");
469 		goto bailout;
470 	}
471 
472 	bzero(&vpd_page, sizeof(vpd_page));
473 
474 	scsi_inquiry(&ccb->csio,
475 		     /*retries*/ retry_count,
476 		     /*cbfcnp*/ NULL,
477 		     /* tag_action */ MSG_SIMPLE_Q_TAG,
478 		     /* inq_buf */ (uint8_t *)&vpd_page,
479 		     /* inq_len */ sizeof(vpd_page),
480 		     /* evpd */ 1,
481 		     /* page_code */ SVPD_IBM_FW_DESIGNATION,
482 		     /* sense_len */ SSD_FULL_SIZE,
483 		     /* timeout */ timeout ? timeout : 5000);
484 
485 	/* Disable freezing the device queue */
486 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
487 
488 	if (retry_count != 0)
489 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
490 
491 	if (cam_send_ccb(dev, ccb) < 0) {
492 		warn("error getting firmware designation page");
493 
494 		cam_error_print(dev, ccb, CAM_ESF_ALL,
495 				CAM_EPF_ALL, stderr);
496 
497 		cam_freeccb(ccb);
498 		ccb = NULL;
499 		goto bailout;
500 	}
501 
502 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
503 		cam_error_print(dev, ccb, CAM_ESF_ALL,
504 				CAM_EPF_ALL, stderr);
505 		goto bailout;
506 	}
507 
508 	/*
509 	 * Read the firmware header only.
510 	 */
511 	if (read(fd, buf, sizeof(*header)) != sizeof(*header)) {
512 		warn("unable to read %zu bytes from %s", sizeof(*header),
513 		     fw_img_path);
514 		goto bailout;
515 	}
516 
517 	/* Rewind the file back to 0 for the full file read. */
518 	if (lseek(fd, 0, SEEK_SET) == -1) {
519 		warn("Unable to lseek");
520 		goto bailout;
521 	}
522 
523 	header = (struct fw_ibm_tape_fw_header *)buf;
524 
525 	bzero(drive_rev, sizeof(drive_rev));
526 	bcopy(vpd_page.fw_rev, drive_rev, sizeof(vpd_page.fw_rev));
527 	bzero(file_rev, sizeof(file_rev));
528 	bcopy(header->fw_rev, file_rev, sizeof(header->fw_rev));
529 
530 	if (quiet == 0) {
531 		fprintf(stdout, "Current Drive Firmware version: %s\n",
532 			drive_rev);
533 		fprintf(stdout, "Firmware File version: %s\n", file_rev);
534 	}
535 
536 	/*
537 	 * For IBM tape drives the load ID and RU name reported by the
538 	 * drive should match what is in the firmware file.
539 	 */
540 	if (bcmp(vpd_page.load_id, header->load_id,
541 		 MIN(sizeof(vpd_page.load_id), sizeof(header->load_id))) != 0) {
542 		warnx("Drive Firmware load ID 0x%x does not match firmware "
543 		      "file load ID 0x%x", scsi_4btoul(vpd_page.load_id),
544 		      scsi_4btoul(header->load_id));
545 		goto bailout;
546 	}
547 
548 	if (bcmp(vpd_page.ru_name, header->ru_name,
549 		 MIN(sizeof(vpd_page.ru_name), sizeof(header->ru_name))) != 0) {
550 		warnx("Drive Firmware RU name 0x%jx does not match firmware "
551 		      "file RU name 0x%jx",
552 		      (uintmax_t)scsi_8btou64(vpd_page.ru_name),
553 		      (uintmax_t)scsi_8btou64(header->ru_name));
554 		goto bailout;
555 	}
556 	if (quiet == 0)
557 		fprintf(stdout, "Firmware file is valid for this drive.\n");
558 	retval = 0;
559 bailout:
560 	cam_freeccb(ccb);
561 
562 	return (retval);
563 }
564 
565 /*
566  * Allocate a buffer and read fw image file into it
567  * from given path. Number of bytes read is stored
568  * in num_bytes.
569  */
570 static char *
fw_read_img(struct cam_device * dev,int retry_count,int timeout,int quiet,const char * fw_img_path,struct fw_vendor * vp,int * num_bytes)571 fw_read_img(struct cam_device *dev, int retry_count, int timeout, int quiet,
572 	    const char *fw_img_path, struct fw_vendor *vp, int *num_bytes)
573 {
574 	int fd;
575 	struct stat stbuf;
576 	char *buf;
577 	off_t img_size;
578 	int skip_bytes = 0;
579 
580 	if ((fd = open(fw_img_path, O_RDONLY)) < 0) {
581 		warn("Could not open image file %s", fw_img_path);
582 		return (NULL);
583 	}
584 	if (fstat(fd, &stbuf) < 0) {
585 		warn("Could not stat image file %s", fw_img_path);
586 		goto bailout1;
587 	}
588 	if ((img_size = stbuf.st_size) == 0) {
589 		warnx("Zero length image file %s", fw_img_path);
590 		goto bailout1;
591 	}
592 	if ((buf = malloc(img_size)) == NULL) {
593 		warnx("Could not allocate buffer to read image file %s",
594 		    fw_img_path);
595 		goto bailout1;
596 	}
597 	/* Skip headers if applicable. */
598 	switch (vp->type) {
599 	case VENDOR_SEAGATE:
600 		if (read(fd, buf, 16) != 16) {
601 			warn("Could not read image file %s", fw_img_path);
602 			goto bailout;
603 		}
604 		if (lseek(fd, 0, SEEK_SET) == -1) {
605 			warn("Unable to lseek");
606 			goto bailout;
607 		}
608 		if ((strncmp(buf, "SEAGATE,SEAGATE ", 16) == 0) ||
609 		    (img_size % 512 == 80))
610 			skip_bytes = 80;
611 		break;
612 	case VENDOR_QUALSTAR:
613 		skip_bytes = img_size % 1030;
614 		break;
615 	case VENDOR_IBM: {
616 		if (vp->dev_type != T_SEQUENTIAL)
617 			break;
618 		if (fw_validate_ibm(dev, retry_count, timeout, fd, buf,
619 				    fw_img_path, quiet) != 0)
620 			goto bailout;
621 		break;
622 	}
623 	default:
624 		break;
625 	}
626 	if (skip_bytes != 0) {
627 		fprintf(stdout, "Skipping %d byte header.\n", skip_bytes);
628 		if (lseek(fd, skip_bytes, SEEK_SET) == -1) {
629 			warn("Could not lseek");
630 			goto bailout;
631 		}
632 		img_size -= skip_bytes;
633 	}
634 	/* Read image into a buffer. */
635 	if (read(fd, buf, img_size) != img_size) {
636 		warn("Could not read image file %s", fw_img_path);
637 		goto bailout;
638 	}
639 	*num_bytes = img_size;
640 	close(fd);
641 	return (buf);
642 bailout:
643 	free(buf);
644 bailout1:
645 	close(fd);
646 	*num_bytes = 0;
647 	return (NULL);
648 }
649 
650 /*
651  * Returns 0 for "success", where success means that the device has met the
652  * requirement in the vendor structure for being ready or not ready when
653  * firmware is downloaded.
654  *
655  * Returns 1 for a failure to be ready to accept a firmware download.
656  * (e.g., a drive needs to be ready, but returns not ready)
657  *
658  * Returns -1 for any other failure.
659  */
660 static int
fw_check_device_ready(struct cam_device * dev,camcontrol_devtype devtype,struct fw_vendor * vp,int printerrors,int timeout)661 fw_check_device_ready(struct cam_device *dev, camcontrol_devtype devtype,
662 		      struct fw_vendor *vp, int printerrors, int timeout)
663 {
664 	union ccb *ccb;
665 	int retval = 0;
666 	int16_t *ptr = NULL;
667 	size_t dxfer_len = 0;
668 
669 	if ((ccb = cam_getccb(dev)) == NULL) {
670 		warnx("Could not allocate CCB");
671 		retval = -1;
672 		goto bailout;
673 	}
674 
675 	if (devtype != CC_DT_SCSI) {
676 		dxfer_len = sizeof(struct ata_params);
677 
678 		ptr = (uint16_t *)malloc(dxfer_len);
679 		if (ptr == NULL) {
680 			warnx("can't malloc memory for identify");
681 			retval = -1;
682 			goto bailout;
683 		}
684 		bzero(ptr, dxfer_len);
685 	}
686 
687 	switch (devtype) {
688 	case CC_DT_SCSI:
689 		scsi_test_unit_ready(&ccb->csio,
690 				     /*retries*/ 0,
691 				     /*cbfcnp*/ NULL,
692 				     /*tag_action*/ MSG_SIMPLE_Q_TAG,
693 		    		     /*sense_len*/ SSD_FULL_SIZE,
694 				     /*timeout*/ 5000);
695 		break;
696 	case CC_DT_SATL:
697 	case CC_DT_ATA: {
698 		retval = build_ata_cmd(ccb,
699 			     /*retries*/ 1,
700 			     /*flags*/ CAM_DIR_IN,
701 			     /*tag_action*/ MSG_SIMPLE_Q_TAG,
702 			     /*protocol*/ AP_PROTO_PIO_IN,
703 			     /*ata_flags*/ AP_FLAG_BYT_BLOK_BLOCKS |
704 					   AP_FLAG_TLEN_SECT_CNT |
705 					   AP_FLAG_TDIR_FROM_DEV,
706 			     /*features*/ 0,
707 			     /*sector_count*/ dxfer_len / 512,
708 			     /*lba*/ 0,
709 			     /*command*/ ATA_ATA_IDENTIFY,
710 			     /*auxiliary*/ 0,
711 			     /*data_ptr*/ (uint8_t *)ptr,
712 			     /*dxfer_len*/ dxfer_len,
713 			     /*cdb_storage*/ NULL,
714 			     /*cdb_storage_len*/ 0,
715 			     /*sense_len*/ SSD_FULL_SIZE,
716 			     /*timeout*/ timeout ? timeout : 30 * 1000,
717 			     /*is48bit*/ 0,
718 			     /*devtype*/ devtype);
719 		if (retval != 0) {
720 			retval = -1;
721 			warnx("%s: build_ata_cmd() failed, likely "
722 			    "programmer error", __func__);
723 			goto bailout;
724 		}
725 		break;
726 	}
727 	default:
728 		warnx("Unknown disk type %d", devtype);
729 		retval = -1;
730 		goto bailout;
731 		break; /*NOTREACHED*/
732 	}
733 
734 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
735 
736 	retval = cam_send_ccb(dev, ccb);
737 	if (retval != 0) {
738 		warn("error sending %s CCB", (devtype == CC_DT_SCSI) ?
739 		     "Test Unit Ready" : "Identify");
740 		retval = -1;
741 		goto bailout;
742 	}
743 
744 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
745 	 && (vp->tur_status == FW_TUR_READY)) {
746 		warnx("Device is not ready");
747 		if (printerrors)
748 			cam_error_print(dev, ccb, CAM_ESF_ALL,
749 			    CAM_EPF_ALL, stderr);
750 		retval = 1;
751 		goto bailout;
752 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
753 		&& (vp->tur_status == FW_TUR_NOT_READY)) {
754 		warnx("Device cannot have media loaded when firmware is "
755 		    "downloaded");
756 		retval = 1;
757 		goto bailout;
758 	}
759 bailout:
760 	free(ptr);
761 	cam_freeccb(ccb);
762 
763 	return (retval);
764 }
765 
766 /*
767  * After the firmware is downloaded, we know the sense data has changed (or is
768  * likely to change since it contains the firmware version).  Rescan the target
769  * with a flag to tell the kernel it's OK. This allows us to continnue using the
770  * old periph/disk in the kernel, which is less disruptive. We rescan the target
771  * because multilun devices usually update all the luns after the first firmware
772  * download.
773  */
774 static int
fw_rescan_target(struct cam_device * dev,bool printerrors,bool sim_mode)775 fw_rescan_target(struct cam_device *dev, bool printerrors, bool sim_mode)
776 {
777 	union ccb ccb;
778 	int fd;
779 
780 	printf("Rescanning target %d:%d:* to pick up new fw revision / parameters.\n",
781 	    dev->path_id, dev->target_id);
782 	if (sim_mode)
783 		return (0);
784 
785 	/* Can only send XPT_SCAN_TGT via /dev/xpt, not pass device in *dev */
786 	if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
787 		warnx("error opening transport layer device %s\n",
788 		    XPT_DEVICE);
789 		warn("%s", XPT_DEVICE);
790 		return (1);
791 	}
792 
793 	/* Rescan the target */
794 	bzero(&ccb, sizeof(union ccb));
795 	ccb.ccb_h.func_code = XPT_SCAN_TGT;
796 	ccb.ccb_h.path_id = dev->path_id;
797 	ccb.ccb_h.target_id = dev->target_id;
798 	ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
799 	ccb.crcn.flags = CAM_EXPECT_INQ_CHANGE;
800 	ccb.ccb_h.pinfo.priority = 5;	/* run this at a low priority */
801 
802 	if (ioctl(fd, CAMIOCOMMAND, &ccb) < 0) {
803 		warn("CAMIOCOMMAND XPT_SCAN_TGT ioctl failed");
804 		close(fd);
805 		return (1);
806 	}
807 	if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
808 		warn("Can't send rescan lun");
809 		if (printerrors)
810 			cam_error_print(dev, &ccb, CAM_ESF_ALL, CAM_EPF_ALL,
811 			    stderr);
812 		close(fd);
813 		return (1);
814 	}
815 	close(fd);
816 	return (0);
817 }
818 
819 /*
820  * Download firmware stored in buf to cam_dev. If simulation mode
821  * is enabled, only show what packet sizes would be sent to the
822  * device but do not sent any actual packets
823  */
824 static int
fw_download_img(struct cam_device * cam_dev,struct fw_vendor * vp,char * buf,int img_size,int sim_mode,int printerrors,int quiet,int retry_count,int timeout,const char * imgname,camcontrol_devtype devtype)825 fw_download_img(struct cam_device *cam_dev, struct fw_vendor *vp,
826     char *buf, int img_size, int sim_mode, int printerrors, int quiet,
827     int retry_count, int timeout, const char *imgname,
828     camcontrol_devtype devtype)
829 {
830 	struct scsi_write_buffer cdb;
831 	progress_t progress;
832 	int size = 0;
833 	union ccb *ccb = NULL;
834 	int pkt_count = 0;
835 	int max_pkt_size;
836 	uint32_t pkt_size = 0;
837 	char *pkt_ptr = buf;
838 	uint32_t offset;
839 	int last_pkt = 0;
840 	int retval = 0;
841 
842 	/*
843 	 * Check to see whether the device is ready to accept a firmware
844 	 * download.
845 	 */
846 	retval = fw_check_device_ready(cam_dev, devtype, vp, printerrors,
847 				       timeout);
848 	if (retval != 0)
849 		goto bailout;
850 
851 	if ((ccb = cam_getccb(cam_dev)) == NULL) {
852 		warnx("Could not allocate CCB");
853 		retval = 1;
854 		goto bailout;
855 	}
856 
857 	max_pkt_size = vp->max_pkt_size;
858 	if (max_pkt_size == 0)
859 		max_pkt_size = UNKNOWN_MAX_PKT_SIZE;
860 
861 	pkt_size = max_pkt_size;
862 	progress_init(&progress, imgname, size = img_size);
863 	/* Download single fw packets. */
864 	do {
865 		if (img_size <= max_pkt_size) {
866 			last_pkt = 1;
867 			pkt_size = img_size;
868 		}
869 		progress_update(&progress, size - img_size);
870 		if (((sim_mode == 0) && (quiet == 0))
871 		 || ((sim_mode != 0) && (printerrors == 0)))
872 			progress_draw(&progress);
873 		bzero(&cdb, sizeof(cdb));
874 		switch (devtype) {
875 		case CC_DT_SCSI:
876 			cdb.opcode  = WRITE_BUFFER;
877 			cdb.control = 0;
878 			/* Parameter list length. */
879 			scsi_ulto3b(pkt_size, &cdb.length[0]);
880 			offset = vp->inc_cdb_offset ? (pkt_ptr - buf) : 0;
881 			scsi_ulto3b(offset, &cdb.offset[0]);
882 			cdb.byte2 = last_pkt ? vp->cdb_byte2_last :
883 					       vp->cdb_byte2;
884 			cdb.buffer_id = vp->inc_cdb_buffer_id ? pkt_count : 0;
885 			/* Zero out payload of ccb union after ccb header. */
886 			CCB_CLEAR_ALL_EXCEPT_HDR(&ccb->csio);
887 			/*
888 			 * Copy previously constructed cdb into ccb_scsiio
889 			 * struct.
890 			 */
891 			bcopy(&cdb, &ccb->csio.cdb_io.cdb_bytes[0],
892 			    sizeof(struct scsi_write_buffer));
893 			/* Fill rest of ccb_scsiio struct. */
894 			cam_fill_csio(&ccb->csio,		/* ccb_scsiio*/
895 			    retry_count,			/* retries*/
896 			    NULL,				/* cbfcnp*/
897 			    CAM_DIR_OUT | CAM_DEV_QFRZDIS,	/* flags*/
898 			    CAM_TAG_ACTION_NONE,		/* tag_action*/
899 			    (u_char *)pkt_ptr,			/* data_ptr*/
900 			    pkt_size,				/* dxfer_len*/
901 			    SSD_FULL_SIZE,			/* sense_len*/
902 			    sizeof(struct scsi_write_buffer),	/* cdb_len*/
903 			    timeout ? timeout : WB_TIMEOUT);	/* timeout*/
904 			break;
905 		case CC_DT_ATA:
906 		case CC_DT_SATL: {
907 			uint32_t	off;
908 
909 			off = (uint32_t)(pkt_ptr - buf);
910 
911 			retval = build_ata_cmd(ccb,
912 			    /*retry_count*/ retry_count,
913 			    /*flags*/ CAM_DIR_OUT | CAM_DEV_QFRZDIS,
914 			    /*tag_action*/ CAM_TAG_ACTION_NONE,
915 			    /*protocol*/ AP_PROTO_PIO_OUT,
916 			    /*ata_flags*/ AP_FLAG_BYT_BLOK_BYTES |
917 					  AP_FLAG_TLEN_SECT_CNT |
918 					  AP_FLAG_TDIR_TO_DEV,
919 			    /*features*/ USE_OFFSETS_FEATURE,
920 			    /*sector_count*/ ATA_MAKE_SECTORS(pkt_size),
921 			    /*lba*/ ATA_MAKE_LBA(off, pkt_size),
922 			    /*command*/ ATA_DOWNLOAD_MICROCODE,
923 			    /*auxiliary*/ 0,
924 			    /*data_ptr*/ (uint8_t *)pkt_ptr,
925 			    /*dxfer_len*/ pkt_size,
926 			    /*cdb_storage*/ NULL,
927 			    /*cdb_storage_len*/ 0,
928 			    /*sense_len*/ SSD_FULL_SIZE,
929 			    /*timeout*/ timeout ? timeout : WB_TIMEOUT,
930 			    /*is48bit*/ 0,
931 			    /*devtype*/ devtype);
932 
933 			if (retval != 0) {
934 				warnx("%s: build_ata_cmd() failed, likely "
935 				    "programmer error", __func__);
936 				goto bailout;
937 			}
938 			break;
939 		}
940 		default:
941 			warnx("Unknown device type %d", devtype);
942 			retval = 1;
943 			goto bailout;
944 			break; /*NOTREACHED*/
945 		}
946 		if (!sim_mode) {
947 			/* Execute the command. */
948 			if (cam_send_ccb(cam_dev, ccb) < 0 ||
949 			    (ccb->ccb_h.status & CAM_STATUS_MASK) !=
950 			    CAM_REQ_CMP) {
951 				warnx("Error writing image to device");
952 				if (printerrors)
953 					cam_error_print(cam_dev, ccb,
954 					    CAM_ESF_ALL, CAM_EPF_ALL, stderr);
955 				retval = 1;
956 				goto bailout;
957 			}
958 		} else if (printerrors) {
959 			cam_error_print(cam_dev, ccb, CAM_ESF_COMMAND, 0,
960 			    stdout);
961 		}
962 
963 		/* Prepare next round. */
964 		pkt_count++;
965 		pkt_ptr += pkt_size;
966 		img_size -= pkt_size;
967 	} while(!last_pkt);
968 bailout:
969 	if (quiet == 0)
970 		progress_complete(&progress, size - img_size);
971 	cam_freeccb(ccb);
972 	if (retval == 0) {
973 		fw_rescan_target(cam_dev, printerrors, sim_mode);
974 	}
975 	return (retval);
976 }
977 
978 int
fwdownload(struct cam_device * device,int argc,char ** argv,char * combinedopt,int printerrors,int task_attr,int retry_count,int timeout)979 fwdownload(struct cam_device *device, int argc, char **argv,
980     char *combinedopt, int printerrors, int task_attr, int retry_count,
981     int timeout)
982 {
983 	union ccb *ccb = NULL;
984 	struct fw_vendor *vp;
985 	char *fw_img_path = NULL;
986 	struct ata_params *ident_buf = NULL;
987 	camcontrol_devtype devtype;
988 	char *buf = NULL;
989 	int img_size;
990 	int c;
991 	int sim_mode = 0;
992 	int confirmed = 0;
993 	int quiet = 0;
994 	int retval = 0;
995 
996 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
997 		switch (c) {
998 		case 'f':
999 			fw_img_path = optarg;
1000 			break;
1001 		case 'q':
1002 			quiet = 1;
1003 			break;
1004 		case 's':
1005 			sim_mode = 1;
1006 			break;
1007 		case 'y':
1008 			confirmed = 1;
1009 			break;
1010 		default:
1011 			break;
1012 		}
1013 	}
1014 
1015 	if (fw_img_path == NULL)
1016 		errx(1, "you must specify a firmware image file using -f "
1017 		     "option");
1018 
1019 	retval = get_device_type(device, retry_count, timeout, printerrors,
1020 				 &devtype);
1021 	if (retval != 0)
1022 		errx(1, "Unable to determine device type");
1023 
1024 	if ((devtype == CC_DT_ATA)
1025 	 || (devtype == CC_DT_SATL)) {
1026 		ccb = cam_getccb(device);
1027 		if (ccb == NULL) {
1028 			warnx("couldn't allocate CCB");
1029 			retval = 1;
1030 			goto bailout;
1031 		}
1032 
1033 		if (ata_do_identify(device, retry_count, timeout, ccb,
1034 		    		    &ident_buf) != 0) {
1035 			retval = 1;
1036 			goto bailout;
1037 		}
1038 	} else if (devtype != CC_DT_SCSI)
1039 		errx(1, "Unsupported device type %d", devtype);
1040 
1041 	vp = fw_get_vendor(device, ident_buf);
1042 	/*
1043 	 * Bail out if we have an unknown vendor and this isn't an ATA
1044 	 * disk.  For a SCSI disk, we have no chance of working properly
1045 	 * with the default values in the VENDOR_UNKNOWN case.  For an ATA
1046 	 * disk connected via an ATA transport, we may work for drives that
1047 	 * support the ATA_DOWNLOAD_MICROCODE command.
1048 	 */
1049 	if (((vp == NULL)
1050 	  || (vp->type == VENDOR_UNKNOWN))
1051 	 && (devtype == CC_DT_SCSI))
1052 		errx(1, "Unsupported device");
1053 
1054 	retval = fw_get_timeout(device, vp, task_attr, retry_count, timeout);
1055 	if (retval != 0) {
1056 		warnx("Unable to get a firmware download timeout value");
1057 		goto bailout;
1058 	}
1059 
1060 	buf = fw_read_img(device, retry_count, timeout, quiet, fw_img_path,
1061 	    vp, &img_size);
1062 	if (buf == NULL) {
1063 		retval = 1;
1064 		goto bailout;
1065 	}
1066 
1067 	if (!confirmed) {
1068 		fprintf(stdout, "You are about to download firmware image (%s)"
1069 		    " into the following device:\n",
1070 		    fw_img_path);
1071 		if (devtype == CC_DT_SCSI) {
1072 			if (scsidoinquiry(device, argc, argv, combinedopt,
1073 					  MSG_SIMPLE_Q_TAG, 0, 5000) != 0) {
1074 				warnx("Error sending inquiry");
1075 				retval = 1;
1076 				goto bailout;
1077 			}
1078 		} else {
1079 			printf("%s%d: ", device->device_name,
1080 			    device->dev_unit_num);
1081 			ata_print_ident(ident_buf);
1082 			camxferrate(device);
1083 			free(ident_buf);
1084 		}
1085 		fprintf(stdout, "Using a timeout of %u ms, which is %s.\n",
1086 			vp->timeout_ms,
1087 			fw_timeout_desc_table[vp->timeout_type].timeout_desc);
1088 		fprintf(stdout, "\nIt may damage your drive. ");
1089 		if (!get_confirmation()) {
1090 			retval = 1;
1091 			goto bailout;
1092 		}
1093 	}
1094 	if ((sim_mode != 0) && (quiet == 0))
1095 		fprintf(stdout, "Running in simulation mode\n");
1096 
1097 	if (fw_download_img(device, vp, buf, img_size, sim_mode, printerrors,
1098 	    quiet, retry_count, vp->timeout_ms, fw_img_path, devtype) != 0) {
1099 		fprintf(stderr, "Firmware download failed\n");
1100 		retval = 1;
1101 		goto bailout;
1102 	} else if (quiet == 0)
1103 		fprintf(stdout, "Firmware download successful\n");
1104 
1105 bailout:
1106 	cam_freeccb(ccb);
1107 	free(buf);
1108 	return (retval);
1109 }
1110 
1111