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