xref: /freebsd/sbin/camcontrol/fwdownload.c (revision 7138c819c484e71e2a21344bc3f91c66ca7b610a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
53 __FBSDID("$FreeBSD$");
54 
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 
58 #include <err.h>
59 #include <fcntl.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include <cam/scsi/scsi_all.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 	u_int8_t cdb_byte2;
168 	u_int8_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 
216 	/*
217 	 * We match any ATA device.  This is really just a placeholder,
218 	 * since we won't actually send a WRITE BUFFER with any of the
219 	 * listed parameters.  If a SATA device is behind a SAS controller,
220 	 * the SCSI to ATA translation code (at least for LSI) doesn't
221 	 * generally translate a SCSI WRITE BUFFER into an ATA DOWNLOAD
222 	 * MICROCODE command.  So, we use the SCSI ATA PASS_THROUGH command
223 	 * to send the ATA DOWNLOAD MICROCODE command instead.
224 	 */
225 	{VENDOR_ATA,		"ATA",		T_ANY,
226 	 0x8000, 0x07, 0x07, 0, 1, FW_TUR_READY, WB_TIMEOUT,
227 	 FW_TIMEOUT_NO_PROBE},
228 	{VENDOR_UNKNOWN,	NULL,		T_ANY,
229 	0x0000, 0x00, 0x00, 0, 0, FW_TUR_NONE, WB_TIMEOUT, FW_TIMEOUT_DEFAULT}
230 };
231 
232 struct fw_timeout_desc {
233 	fw_timeout_type timeout_type;
234 	const char *timeout_desc;
235 };
236 
237 static const struct fw_timeout_desc fw_timeout_desc_table[] = {
238 	{ FW_TIMEOUT_DEFAULT, "the default" },
239 	{ FW_TIMEOUT_DEV_REPORTED, "recommended by this particular device" },
240 	{ FW_TIMEOUT_NO_PROBE, "the default" },
241 	{ FW_TIMEOUT_USER_SPEC, "what was specified on the command line" }
242 };
243 
244 #ifndef ATA_DOWNLOAD_MICROCODE
245 #define ATA_DOWNLOAD_MICROCODE	0x92
246 #endif
247 
248 #define USE_OFFSETS_FEATURE	0x3
249 
250 #ifndef LOW_SECTOR_SIZE
251 #define LOW_SECTOR_SIZE		512
252 #endif
253 
254 #define ATA_MAKE_LBA(o, p)	\
255 	((((((o) / LOW_SECTOR_SIZE) >> 8) & 0xff) << 16) | \
256 	  ((((o) / LOW_SECTOR_SIZE) & 0xff) << 8) | \
257 	  ((((p) / LOW_SECTOR_SIZE) >> 8) & 0xff))
258 
259 #define ATA_MAKE_SECTORS(p)	(((p) / 512) & 0xff)
260 
261 #ifndef UNKNOWN_MAX_PKT_SIZE
262 #define UNKNOWN_MAX_PKT_SIZE	0x8000
263 #endif
264 
265 static struct fw_vendor *fw_get_vendor(struct cam_device *cam_dev,
266 				       struct ata_params *ident_buf);
267 static int fw_get_timeout(struct cam_device *cam_dev, struct fw_vendor *vp,
268 			  int task_attr, int retry_count, int timeout);
269 static int fw_validate_ibm(struct cam_device *dev, int retry_count,
270 			   int timeout, int fd, char *buf,
271 			    const char *fw_img_path, int quiet);
272 static char *fw_read_img(struct cam_device *dev, int retry_count,
273 			 int timeout, int quiet, const char *fw_img_path,
274 			 struct fw_vendor *vp, int *num_bytes);
275 static int fw_check_device_ready(struct cam_device *dev,
276 				 camcontrol_devtype devtype,
277 				 struct fw_vendor *vp, int printerrors,
278 				 int timeout);
279 static int fw_download_img(struct cam_device *cam_dev,
280 			   struct fw_vendor *vp, char *buf, int img_size,
281 			   int sim_mode, int printerrors, int quiet,
282 			   int retry_count, int timeout, const char */*name*/,
283 			   camcontrol_devtype devtype);
284 
285 /*
286  * Find entry in vendors list that belongs to
287  * the vendor of given cam device.
288  */
289 static struct fw_vendor *
290 fw_get_vendor(struct cam_device *cam_dev, struct ata_params *ident_buf)
291 {
292 	char vendor[42];
293 	struct fw_vendor *vp;
294 
295 	if (cam_dev == NULL)
296 		return (NULL);
297 
298 	if (ident_buf != NULL) {
299 		cam_strvis((u_char *)vendor, ident_buf->model,
300 		    sizeof(ident_buf->model), sizeof(vendor));
301 		for (vp = vendors_list; vp->pattern != NULL; vp++) {
302 			if (vp->type == VENDOR_ATA)
303 				return (vp);
304 		}
305 	} else {
306 		cam_strvis((u_char *)vendor, (u_char *)cam_dev->inq_data.vendor,
307 		    sizeof(cam_dev->inq_data.vendor), sizeof(vendor));
308 	}
309 	for (vp = vendors_list; vp->pattern != NULL; vp++) {
310 		if (!cam_strmatch((const u_char *)vendor,
311 		    (const u_char *)vp->pattern, strlen(vendor))) {
312 			if ((vp->dev_type == T_ANY)
313 			 || (vp->dev_type == SID_TYPE(&cam_dev->inq_data)))
314 				break;
315 		}
316 	}
317 	return (vp);
318 }
319 
320 static int
321 fw_get_timeout(struct cam_device *cam_dev, struct fw_vendor *vp,
322 	       int task_attr, int retry_count, int timeout)
323 {
324 	struct scsi_report_supported_opcodes_one *one;
325 	struct scsi_report_supported_opcodes_timeout *td;
326 	uint8_t *buf = NULL;
327 	uint32_t fill_len = 0, cdb_len = 0, rec_timeout = 0;
328 	int retval = 0;
329 
330 	/*
331 	 * If the user has specified a timeout on the command line, we let
332 	 * him override any default or probed value.
333 	 */
334 	if (timeout != 0) {
335 		vp->timeout_type = FW_TIMEOUT_USER_SPEC;
336 		vp->timeout_ms = timeout;
337 		goto bailout;
338 	}
339 
340 	/*
341 	 * Check to see whether we should probe for a timeout for this
342 	 * device.
343 	 */
344 	if (vp->timeout_type == FW_TIMEOUT_NO_PROBE)
345 		goto bailout;
346 
347 	retval = scsigetopcodes(/*device*/ cam_dev,
348 				/*opcode_set*/ 1,
349 				/*opcode*/ WRITE_BUFFER,
350 				/*show_sa_errors*/ 1,
351 				/*sa_set*/ 0,
352 				/*service_action*/ 0,
353 				/*timeout_desc*/ 1,
354 				/*task_attr*/ task_attr,
355 				/*retry_count*/ retry_count,
356 				/*timeout*/ 10000,
357 				/*verbose*/ 0,
358 				/*fill_len*/ &fill_len,
359 				/*data_ptr*/ &buf);
360 	/*
361 	 * It isn't an error if we can't get a timeout descriptor.  We just
362 	 * continue on with the default timeout.
363 	 */
364 	if (retval != 0) {
365 		retval = 0;
366 		goto bailout;
367 	}
368 
369 	/*
370 	 * Even if the drive didn't return a SCSI error, if we don't have
371 	 * enough data to contain the one opcode descriptor, the CDB
372 	 * structure and a timeout descriptor, we don't have the timeout
373 	 * value we're looking for.  So we'll just fall back to the
374 	 * default value.
375 	 */
376 	if (fill_len < (sizeof(*one) + sizeof(struct scsi_write_buffer) +
377 	    sizeof(*td)))
378 		goto bailout;
379 
380 	one = (struct scsi_report_supported_opcodes_one *)buf;
381 
382 	/*
383 	 * If the drive claims to not support the WRITE BUFFER command...
384 	 * fall back to the default timeout value and let things fail on
385 	 * the actual firmware download.
386 	 */
387 	if ((one->support & RSO_ONE_SUP_MASK) == RSO_ONE_SUP_NOT_SUP)
388 		goto bailout;
389 
390 	cdb_len = scsi_2btoul(one->cdb_length);
391 	td = (struct scsi_report_supported_opcodes_timeout *)
392 	    &buf[sizeof(*one) + cdb_len];
393 
394 	rec_timeout = scsi_4btoul(td->recommended_time);
395 	/*
396 	 * If the recommended timeout is 0, then the device has probably
397 	 * returned a bogus value.
398 	 */
399 	if (rec_timeout == 0)
400 		goto bailout;
401 
402 	/* CAM timeouts are in ms */
403 	rec_timeout *= 1000;
404 
405 	vp->timeout_ms = rec_timeout;
406 	vp->timeout_type = FW_TIMEOUT_DEV_REPORTED;
407 
408 bailout:
409 	return (retval);
410 }
411 
412 #define	SVPD_IBM_FW_DESIGNATION		0x03
413 
414 /*
415  * IBM LTO and TS tape drives have an INQUIRY VPD page 0x3 with the following
416  * format:
417  */
418 struct fw_ibm_tape_fw_designation {
419 	uint8_t	device;
420 	uint8_t page_code;
421 	uint8_t reserved;
422 	uint8_t length;
423 	uint8_t ascii_length;
424 	uint8_t reserved2[3];
425 	uint8_t load_id[4];
426 	uint8_t fw_rev[4];
427 	uint8_t ptf_number[4];
428 	uint8_t patch_number[4];
429 	uint8_t ru_name[8];
430 	uint8_t lib_seq_num[5];
431 };
432 
433 /*
434  * The firmware for IBM tape drives has the following header format.  The
435  * load_id and ru_name in the header file should match what is returned in
436  * VPD page 0x3.
437  */
438 struct fw_ibm_tape_fw_header {
439 	uint8_t unspec[4];
440 	uint8_t length[4];		/* Firmware and header! */
441 	uint8_t load_id[4];
442 	uint8_t fw_rev[4];
443 	uint8_t reserved[8];
444 	uint8_t ru_name[8];
445 };
446 
447 static int
448 fw_validate_ibm(struct cam_device *dev, int retry_count, int timeout, int fd,
449 		char *buf, const char *fw_img_path, int quiet)
450 {
451 	union ccb *ccb;
452 	struct fw_ibm_tape_fw_designation vpd_page;
453 	struct fw_ibm_tape_fw_header *header;
454 	char drive_rev[sizeof(vpd_page.fw_rev) + 1];
455 	char file_rev[sizeof(vpd_page.fw_rev) + 1];
456 	int retval = 1;
457 
458 	ccb = cam_getccb(dev);
459 	if (ccb == NULL) {
460 		warnx("couldn't allocate CCB");
461 		goto bailout;
462 	}
463 
464 	/* cam_getccb cleans up the header, caller has to zero the payload */
465 	CCB_CLEAR_ALL_EXCEPT_HDR(&ccb->csio);
466 
467 	bzero(&vpd_page, sizeof(vpd_page));
468 
469 	scsi_inquiry(&ccb->csio,
470 		     /*retries*/ retry_count,
471 		     /*cbfcnp*/ NULL,
472 		     /* tag_action */ MSG_SIMPLE_Q_TAG,
473 		     /* inq_buf */ (u_int8_t *)&vpd_page,
474 		     /* inq_len */ sizeof(vpd_page),
475 		     /* evpd */ 1,
476 		     /* page_code */ SVPD_IBM_FW_DESIGNATION,
477 		     /* sense_len */ SSD_FULL_SIZE,
478 		     /* timeout */ timeout ? timeout : 5000);
479 
480 	/* Disable freezing the device queue */
481 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
482 
483 	if (retry_count != 0)
484 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
485 
486 	if (cam_send_ccb(dev, ccb) < 0) {
487 		warn("error getting firmware designation page");
488 
489 		cam_error_print(dev, ccb, CAM_ESF_ALL,
490 				CAM_EPF_ALL, stderr);
491 
492 		cam_freeccb(ccb);
493 		ccb = NULL;
494 		goto bailout;
495 	}
496 
497 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
498 		cam_error_print(dev, ccb, CAM_ESF_ALL,
499 				CAM_EPF_ALL, stderr);
500 		goto bailout;
501 	}
502 
503 	/*
504 	 * Read the firmware header only.
505 	 */
506 	if (read(fd, buf, sizeof(*header)) != sizeof(*header)) {
507 		warn("unable to read %zu bytes from %s", sizeof(*header),
508 		     fw_img_path);
509 		goto bailout;
510 	}
511 
512 	/* Rewind the file back to 0 for the full file read. */
513 	if (lseek(fd, 0, SEEK_SET) == -1) {
514 		warn("Unable to lseek");
515 		goto bailout;
516 	}
517 
518 	header = (struct fw_ibm_tape_fw_header *)buf;
519 
520 	bzero(drive_rev, sizeof(drive_rev));
521 	bcopy(vpd_page.fw_rev, drive_rev, sizeof(vpd_page.fw_rev));
522 	bzero(file_rev, sizeof(file_rev));
523 	bcopy(header->fw_rev, file_rev, sizeof(header->fw_rev));
524 
525 	if (quiet == 0) {
526 		fprintf(stdout, "Current Drive Firmware version: %s\n",
527 			drive_rev);
528 		fprintf(stdout, "Firmware File version: %s\n", file_rev);
529 	}
530 
531 	/*
532 	 * For IBM tape drives the load ID and RU name reported by the
533 	 * drive should match what is in the firmware file.
534 	 */
535 	if (bcmp(vpd_page.load_id, header->load_id,
536 		 MIN(sizeof(vpd_page.load_id), sizeof(header->load_id))) != 0) {
537 		warnx("Drive Firmware load ID 0x%x does not match firmware "
538 		      "file load ID 0x%x", scsi_4btoul(vpd_page.load_id),
539 		      scsi_4btoul(header->load_id));
540 		goto bailout;
541 	}
542 
543 	if (bcmp(vpd_page.ru_name, header->ru_name,
544 		 MIN(sizeof(vpd_page.ru_name), sizeof(header->ru_name))) != 0) {
545 		warnx("Drive Firmware RU name 0x%jx does not match firmware "
546 		      "file RU name 0x%jx",
547 		      (uintmax_t)scsi_8btou64(vpd_page.ru_name),
548 		      (uintmax_t)scsi_8btou64(header->ru_name));
549 		goto bailout;
550 	}
551 	if (quiet == 0)
552 		fprintf(stdout, "Firmware file is valid for this drive.\n");
553 	retval = 0;
554 bailout:
555 	cam_freeccb(ccb);
556 
557 	return (retval);
558 }
559 
560 /*
561  * Allocate a buffer and read fw image file into it
562  * from given path. Number of bytes read is stored
563  * in num_bytes.
564  */
565 static char *
566 fw_read_img(struct cam_device *dev, int retry_count, int timeout, int quiet,
567 	    const char *fw_img_path, struct fw_vendor *vp, int *num_bytes)
568 {
569 	int fd;
570 	struct stat stbuf;
571 	char *buf;
572 	off_t img_size;
573 	int skip_bytes = 0;
574 
575 	if ((fd = open(fw_img_path, O_RDONLY)) < 0) {
576 		warn("Could not open image file %s", fw_img_path);
577 		return (NULL);
578 	}
579 	if (fstat(fd, &stbuf) < 0) {
580 		warn("Could not stat image file %s", fw_img_path);
581 		goto bailout1;
582 	}
583 	if ((img_size = stbuf.st_size) == 0) {
584 		warnx("Zero length image file %s", fw_img_path);
585 		goto bailout1;
586 	}
587 	if ((buf = malloc(img_size)) == NULL) {
588 		warnx("Could not allocate buffer to read image file %s",
589 		    fw_img_path);
590 		goto bailout1;
591 	}
592 	/* Skip headers if applicable. */
593 	switch (vp->type) {
594 	case VENDOR_SEAGATE:
595 		if (read(fd, buf, 16) != 16) {
596 			warn("Could not read image file %s", fw_img_path);
597 			goto bailout;
598 		}
599 		if (lseek(fd, 0, SEEK_SET) == -1) {
600 			warn("Unable to lseek");
601 			goto bailout;
602 		}
603 		if ((strncmp(buf, "SEAGATE,SEAGATE ", 16) == 0) ||
604 		    (img_size % 512 == 80))
605 			skip_bytes = 80;
606 		break;
607 	case VENDOR_QUALSTAR:
608 		skip_bytes = img_size % 1030;
609 		break;
610 	case VENDOR_IBM: {
611 		if (vp->dev_type != T_SEQUENTIAL)
612 			break;
613 		if (fw_validate_ibm(dev, retry_count, timeout, fd, buf,
614 				    fw_img_path, quiet) != 0)
615 			goto bailout;
616 		break;
617 	}
618 	default:
619 		break;
620 	}
621 	if (skip_bytes != 0) {
622 		fprintf(stdout, "Skipping %d byte header.\n", skip_bytes);
623 		if (lseek(fd, skip_bytes, SEEK_SET) == -1) {
624 			warn("Could not lseek");
625 			goto bailout;
626 		}
627 		img_size -= skip_bytes;
628 	}
629 	/* Read image into a buffer. */
630 	if (read(fd, buf, img_size) != img_size) {
631 		warn("Could not read image file %s", fw_img_path);
632 		goto bailout;
633 	}
634 	*num_bytes = img_size;
635 	close(fd);
636 	return (buf);
637 bailout:
638 	free(buf);
639 bailout1:
640 	close(fd);
641 	*num_bytes = 0;
642 	return (NULL);
643 }
644 
645 /*
646  * Returns 0 for "success", where success means that the device has met the
647  * requirement in the vendor structure for being ready or not ready when
648  * firmware is downloaded.
649  *
650  * Returns 1 for a failure to be ready to accept a firmware download.
651  * (e.g., a drive needs to be ready, but returns not ready)
652  *
653  * Returns -1 for any other failure.
654  */
655 static int
656 fw_check_device_ready(struct cam_device *dev, camcontrol_devtype devtype,
657 		      struct fw_vendor *vp, int printerrors, int timeout)
658 {
659 	union ccb *ccb;
660 	int retval = 0;
661 	int16_t *ptr = NULL;
662 	size_t dxfer_len = 0;
663 
664 	if ((ccb = cam_getccb(dev)) == NULL) {
665 		warnx("Could not allocate CCB");
666 		retval = -1;
667 		goto bailout;
668 	}
669 
670 	CCB_CLEAR_ALL_EXCEPT_HDR(ccb);
671 
672 	if (devtype != CC_DT_SCSI) {
673 		dxfer_len = sizeof(struct ata_params);
674 
675 		ptr = (uint16_t *)malloc(dxfer_len);
676 		if (ptr == NULL) {
677 			warnx("can't malloc memory for identify");
678 			retval = -1;
679 			goto bailout;
680 		}
681 		bzero(ptr, dxfer_len);
682 	}
683 
684 	switch (devtype) {
685 	case CC_DT_SCSI:
686 		scsi_test_unit_ready(&ccb->csio,
687 				     /*retries*/ 0,
688 				     /*cbfcnp*/ NULL,
689 				     /*tag_action*/ MSG_SIMPLE_Q_TAG,
690 		    		     /*sense_len*/ SSD_FULL_SIZE,
691 				     /*timeout*/ 5000);
692 		break;
693 	case CC_DT_ATA_BEHIND_SCSI:
694 	case CC_DT_ATA: {
695 		retval = build_ata_cmd(ccb,
696 			     /*retries*/ 1,
697 			     /*flags*/ CAM_DIR_IN,
698 			     /*tag_action*/ MSG_SIMPLE_Q_TAG,
699 			     /*protocol*/ AP_PROTO_PIO_IN,
700 			     /*ata_flags*/ AP_FLAG_BYT_BLOK_BYTES |
701 					   AP_FLAG_TLEN_SECT_CNT |
702 					   AP_FLAG_TDIR_FROM_DEV,
703 			     /*features*/ 0,
704 			     /*sector_count*/ (uint8_t) dxfer_len,
705 			     /*lba*/ 0,
706 			     /*command*/ ATA_ATA_IDENTIFY,
707 			     /*auxiliary*/ 0,
708 			     /*data_ptr*/ (uint8_t *)ptr,
709 			     /*dxfer_len*/ dxfer_len,
710 			     /*cdb_storage*/ NULL,
711 			     /*cdb_storage_len*/ 0,
712 			     /*sense_len*/ SSD_FULL_SIZE,
713 			     /*timeout*/ timeout ? timeout : 30 * 1000,
714 			     /*is48bit*/ 0,
715 			     /*devtype*/ devtype);
716 		if (retval != 0) {
717 			retval = -1;
718 			warnx("%s: build_ata_cmd() failed, likely "
719 			    "programmer error", __func__);
720 			goto bailout;
721 		}
722 		break;
723 	}
724 	default:
725 		warnx("Unknown disk type %d", devtype);
726 		retval = -1;
727 		goto bailout;
728 		break; /*NOTREACHED*/
729 	}
730 
731 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
732 
733 	retval = cam_send_ccb(dev, ccb);
734 	if (retval != 0) {
735 		warn("error sending %s CCB", (devtype == CC_DT_SCSI) ?
736 		     "Test Unit Ready" : "Identify");
737 		retval = -1;
738 		goto bailout;
739 	}
740 
741 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
742 	 && (vp->tur_status == FW_TUR_READY)) {
743 		warnx("Device is not ready");
744 		if (printerrors)
745 			cam_error_print(dev, ccb, CAM_ESF_ALL,
746 			    CAM_EPF_ALL, stderr);
747 		retval = 1;
748 		goto bailout;
749 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
750 		&& (vp->tur_status == FW_TUR_NOT_READY)) {
751 		warnx("Device cannot have media loaded when firmware is "
752 		    "downloaded");
753 		retval = 1;
754 		goto bailout;
755 	}
756 bailout:
757 	free(ptr);
758 	cam_freeccb(ccb);
759 
760 	return (retval);
761 }
762 
763 /*
764  * Download firmware stored in buf to cam_dev. If simulation mode
765  * is enabled, only show what packet sizes would be sent to the
766  * device but do not sent any actual packets
767  */
768 static int
769 fw_download_img(struct cam_device *cam_dev, struct fw_vendor *vp,
770     char *buf, int img_size, int sim_mode, int printerrors, int quiet,
771     int retry_count, int timeout, const char *imgname,
772     camcontrol_devtype devtype)
773 {
774 	struct scsi_write_buffer cdb;
775 	progress_t progress;
776 	int size = 0;
777 	union ccb *ccb = NULL;
778 	int pkt_count = 0;
779 	int max_pkt_size;
780 	u_int32_t pkt_size = 0;
781 	char *pkt_ptr = buf;
782 	u_int32_t offset;
783 	int last_pkt = 0;
784 	int retval = 0;
785 
786 	/*
787 	 * Check to see whether the device is ready to accept a firmware
788 	 * download.
789 	 */
790 	retval = fw_check_device_ready(cam_dev, devtype, vp, printerrors,
791 				       timeout);
792 	if (retval != 0)
793 		goto bailout;
794 
795 	if ((ccb = cam_getccb(cam_dev)) == NULL) {
796 		warnx("Could not allocate CCB");
797 		retval = 1;
798 		goto bailout;
799 	}
800 
801 	CCB_CLEAR_ALL_EXCEPT_HDR(ccb);
802 
803 	max_pkt_size = vp->max_pkt_size;
804 	if (max_pkt_size == 0)
805 		max_pkt_size = UNKNOWN_MAX_PKT_SIZE;
806 
807 	pkt_size = max_pkt_size;
808 	progress_init(&progress, imgname, size = img_size);
809 	/* Download single fw packets. */
810 	do {
811 		if (img_size <= max_pkt_size) {
812 			last_pkt = 1;
813 			pkt_size = img_size;
814 		}
815 		progress_update(&progress, size - img_size);
816 		if (((sim_mode == 0) && (quiet == 0))
817 		 || ((sim_mode != 0) && (printerrors == 0)))
818 			progress_draw(&progress);
819 		bzero(&cdb, sizeof(cdb));
820 		switch (devtype) {
821 		case CC_DT_SCSI:
822 			cdb.opcode  = WRITE_BUFFER;
823 			cdb.control = 0;
824 			/* Parameter list length. */
825 			scsi_ulto3b(pkt_size, &cdb.length[0]);
826 			offset = vp->inc_cdb_offset ? (pkt_ptr - buf) : 0;
827 			scsi_ulto3b(offset, &cdb.offset[0]);
828 			cdb.byte2 = last_pkt ? vp->cdb_byte2_last :
829 					       vp->cdb_byte2;
830 			cdb.buffer_id = vp->inc_cdb_buffer_id ? pkt_count : 0;
831 			/* Zero out payload of ccb union after ccb header. */
832 			CCB_CLEAR_ALL_EXCEPT_HDR(&ccb->csio);
833 			/*
834 			 * Copy previously constructed cdb into ccb_scsiio
835 			 * struct.
836 			 */
837 			bcopy(&cdb, &ccb->csio.cdb_io.cdb_bytes[0],
838 			    sizeof(struct scsi_write_buffer));
839 			/* Fill rest of ccb_scsiio struct. */
840 			cam_fill_csio(&ccb->csio,		/* ccb_scsiio*/
841 			    retry_count,			/* retries*/
842 			    NULL,				/* cbfcnp*/
843 			    CAM_DIR_OUT | CAM_DEV_QFRZDIS,	/* flags*/
844 			    CAM_TAG_ACTION_NONE,		/* tag_action*/
845 			    (u_char *)pkt_ptr,			/* data_ptr*/
846 			    pkt_size,				/* dxfer_len*/
847 			    SSD_FULL_SIZE,			/* sense_len*/
848 			    sizeof(struct scsi_write_buffer),	/* cdb_len*/
849 			    timeout ? timeout : WB_TIMEOUT);	/* timeout*/
850 			break;
851 		case CC_DT_ATA:
852 		case CC_DT_ATA_BEHIND_SCSI: {
853 			uint32_t	off;
854 
855 			off = (uint32_t)(pkt_ptr - buf);
856 
857 			retval = build_ata_cmd(ccb,
858 			    /*retry_count*/ retry_count,
859 			    /*flags*/ CAM_DIR_OUT | CAM_DEV_QFRZDIS,
860 			    /*tag_action*/ CAM_TAG_ACTION_NONE,
861 			    /*protocol*/ AP_PROTO_PIO_OUT,
862 			    /*ata_flags*/ AP_FLAG_BYT_BLOK_BYTES |
863 					  AP_FLAG_TLEN_SECT_CNT |
864 					  AP_FLAG_TDIR_TO_DEV,
865 			    /*features*/ USE_OFFSETS_FEATURE,
866 			    /*sector_count*/ ATA_MAKE_SECTORS(pkt_size),
867 			    /*lba*/ ATA_MAKE_LBA(off, pkt_size),
868 			    /*command*/ ATA_DOWNLOAD_MICROCODE,
869 			    /*auxiliary*/ 0,
870 			    /*data_ptr*/ (uint8_t *)pkt_ptr,
871 			    /*dxfer_len*/ pkt_size,
872 			    /*cdb_storage*/ NULL,
873 			    /*cdb_storage_len*/ 0,
874 			    /*sense_len*/ SSD_FULL_SIZE,
875 			    /*timeout*/ timeout ? timeout : WB_TIMEOUT,
876 			    /*is48bit*/ 0,
877 			    /*devtype*/ devtype);
878 
879 			if (retval != 0) {
880 				warnx("%s: build_ata_cmd() failed, likely "
881 				    "programmer error", __func__);
882 				goto bailout;
883 			}
884 			break;
885 		}
886 		default:
887 			warnx("Unknown device type %d", devtype);
888 			retval = 1;
889 			goto bailout;
890 			break; /*NOTREACHED*/
891 		}
892 		if (!sim_mode) {
893 			/* Execute the command. */
894 			if (cam_send_ccb(cam_dev, ccb) < 0 ||
895 			    (ccb->ccb_h.status & CAM_STATUS_MASK) !=
896 			    CAM_REQ_CMP) {
897 				warnx("Error writing image to device");
898 				if (printerrors)
899 					cam_error_print(cam_dev, ccb,
900 					    CAM_ESF_ALL, CAM_EPF_ALL, stderr);
901 				retval = 1;
902 				goto bailout;
903 			}
904 		} else if (printerrors) {
905 			cam_error_print(cam_dev, ccb, CAM_ESF_COMMAND, 0,
906 			    stdout);
907 		}
908 
909 		/* Prepare next round. */
910 		pkt_count++;
911 		pkt_ptr += pkt_size;
912 		img_size -= pkt_size;
913 	} while(!last_pkt);
914 bailout:
915 	if (quiet == 0)
916 		progress_complete(&progress, size - img_size);
917 	cam_freeccb(ccb);
918 	return (retval);
919 }
920 
921 int
922 fwdownload(struct cam_device *device, int argc, char **argv,
923     char *combinedopt, int printerrors, int task_attr, int retry_count,
924     int timeout)
925 {
926 	union ccb *ccb = NULL;
927 	struct fw_vendor *vp;
928 	char *fw_img_path = NULL;
929 	struct ata_params *ident_buf = NULL;
930 	camcontrol_devtype devtype;
931 	char *buf = NULL;
932 	int img_size;
933 	int c;
934 	int sim_mode = 0;
935 	int confirmed = 0;
936 	int quiet = 0;
937 	int retval = 0;
938 
939 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
940 		switch (c) {
941 		case 'f':
942 			fw_img_path = optarg;
943 			break;
944 		case 'q':
945 			quiet = 1;
946 			break;
947 		case 's':
948 			sim_mode = 1;
949 			break;
950 		case 'y':
951 			confirmed = 1;
952 			break;
953 		default:
954 			break;
955 		}
956 	}
957 
958 	if (fw_img_path == NULL)
959 		errx(1, "you must specify a firmware image file using -f "
960 		     "option");
961 
962 	retval = get_device_type(device, retry_count, timeout, printerrors,
963 				 &devtype);
964 	if (retval != 0)
965 		errx(1, "Unable to determine device type");
966 
967 	if ((devtype == CC_DT_ATA)
968 	 || (devtype == CC_DT_ATA_BEHIND_SCSI)) {
969 		ccb = cam_getccb(device);
970 		if (ccb == NULL) {
971 			warnx("couldn't allocate CCB");
972 			retval = 1;
973 			goto bailout;
974 		}
975 
976 		if (ata_do_identify(device, retry_count, timeout, ccb,
977 		    		    &ident_buf) != 0) {
978 			retval = 1;
979 			goto bailout;
980 		}
981 	} else if (devtype != CC_DT_SCSI)
982 		errx(1, "Unsupported device type %d", devtype);
983 
984 	vp = fw_get_vendor(device, ident_buf);
985 	/*
986 	 * Bail out if we have an unknown vendor and this isn't an ATA
987 	 * disk.  For a SCSI disk, we have no chance of working properly
988 	 * with the default values in the VENDOR_UNKNOWN case.  For an ATA
989 	 * disk connected via an ATA transport, we may work for drives that
990 	 * support the ATA_DOWNLOAD_MICROCODE command.
991 	 */
992 	if (((vp == NULL)
993 	  || (vp->type == VENDOR_UNKNOWN))
994 	 && (devtype == CC_DT_SCSI))
995 		errx(1, "Unsupported device");
996 
997 	retval = fw_get_timeout(device, vp, task_attr, retry_count, timeout);
998 	if (retval != 0) {
999 		warnx("Unable to get a firmware download timeout value");
1000 		goto bailout;
1001 	}
1002 
1003 	buf = fw_read_img(device, retry_count, timeout, quiet, fw_img_path,
1004 	    vp, &img_size);
1005 	if (buf == NULL) {
1006 		retval = 1;
1007 		goto bailout;
1008 	}
1009 
1010 	if (!confirmed) {
1011 		fprintf(stdout, "You are about to download firmware image (%s)"
1012 		    " into the following device:\n",
1013 		    fw_img_path);
1014 		if (devtype == CC_DT_SCSI) {
1015 			if (scsidoinquiry(device, argc, argv, combinedopt,
1016 					  MSG_SIMPLE_Q_TAG, 0, 5000) != 0) {
1017 				warnx("Error sending inquiry");
1018 				retval = 1;
1019 				goto bailout;
1020 			}
1021 		} else {
1022 			printf("%s%d: ", device->device_name,
1023 			    device->dev_unit_num);
1024 			ata_print_ident(ident_buf);
1025 			camxferrate(device);
1026 			free(ident_buf);
1027 		}
1028 		fprintf(stdout, "Using a timeout of %u ms, which is %s.\n",
1029 			vp->timeout_ms,
1030 			fw_timeout_desc_table[vp->timeout_type].timeout_desc);
1031 		fprintf(stdout, "\nIt may damage your drive. ");
1032 		if (!get_confirmation()) {
1033 			retval = 1;
1034 			goto bailout;
1035 		}
1036 	}
1037 	if ((sim_mode != 0) && (quiet == 0))
1038 		fprintf(stdout, "Running in simulation mode\n");
1039 
1040 	if (fw_download_img(device, vp, buf, img_size, sim_mode, printerrors,
1041 	    quiet, retry_count, vp->timeout_ms, fw_img_path, devtype) != 0) {
1042 		fprintf(stderr, "Firmware download failed\n");
1043 		retval = 1;
1044 		goto bailout;
1045 	} else if (quiet == 0)
1046 		fprintf(stdout, "Firmware download successful\n");
1047 
1048 bailout:
1049 	cam_freeccb(ccb);
1050 	free(buf);
1051 	return (retval);
1052 }
1053 
1054