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