xref: /freebsd/sbin/camcontrol/fwdownload.c (revision a98ff317388a00b992f1bf8404dee596f9383f5e)
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	CMD_TIMEOUT 50000	/* 50 seconds */
72 
73 typedef enum {
74 	VENDOR_HITACHI,
75 	VENDOR_HP,
76 	VENDOR_IBM,
77 	VENDOR_PLEXTOR,
78 	VENDOR_QUALSTAR,
79 	VENDOR_QUANTUM,
80 	VENDOR_SEAGATE,
81 	VENDOR_UNKNOWN
82 } fw_vendor_t;
83 
84 struct fw_vendor {
85 	fw_vendor_t type;
86 	const char *pattern;
87 	int max_pkt_size;
88 	u_int8_t cdb_byte2;
89 	u_int8_t cdb_byte2_last;
90 	int inc_cdb_buffer_id;
91 	int inc_cdb_offset;
92 };
93 
94 static const struct fw_vendor vendors_list[] = {
95 	{VENDOR_HITACHI,	"HITACHI",	0x8000, 0x05, 0x05, 1, 0},
96 	{VENDOR_HP,		"HP",		0x8000, 0x07, 0x07, 0, 1},
97 	{VENDOR_IBM,		"IBM",		0x8000, 0x05, 0x05, 1, 0},
98 	{VENDOR_PLEXTOR,	"PLEXTOR",	0x2000, 0x04, 0x05, 0, 1},
99 	{VENDOR_QUALSTAR,	"QUALSTAR",	0x2030, 0x05, 0x05, 0, 0},
100 	{VENDOR_QUANTUM,	"QUANTUM",	0x2000, 0x04, 0x05, 0, 1},
101 	{VENDOR_SEAGATE,	"SEAGATE",	0x8000, 0x07, 0x07, 0, 1},
102 	/* the next 2 are SATA disks going through SAS HBA */
103 	{VENDOR_SEAGATE,	"ATA ST",	0x8000, 0x07, 0x07, 0, 1},
104 	{VENDOR_HITACHI,	"ATA HDS",	0x8000, 0x05, 0x05, 1, 0},
105 	{VENDOR_UNKNOWN,	NULL,		0x0000, 0x00, 0x00, 0, 0}
106 };
107 
108 #ifndef ATA_DOWNLOAD_MICROCODE
109 #define ATA_DOWNLOAD_MICROCODE	0x92
110 #endif
111 
112 #define USE_OFFSETS_FEATURE	0x3
113 
114 #ifndef LOW_SECTOR_SIZE
115 #define LOW_SECTOR_SIZE		512
116 #endif
117 
118 #define ATA_MAKE_LBA(o, p)	\
119 	((((((o) / LOW_SECTOR_SIZE) >> 8) & 0xff) << 16) | \
120 	  ((((o) / LOW_SECTOR_SIZE) & 0xff) << 8) | \
121 	  ((((p) / LOW_SECTOR_SIZE) >> 8) & 0xff))
122 
123 #define ATA_MAKE_SECTORS(p)	(((p) / 512) & 0xff)
124 
125 #ifndef UNKNOWN_MAX_PKT_SIZE
126 #define UNKNOWN_MAX_PKT_SIZE	0x8000
127 #endif
128 
129 static const struct fw_vendor *fw_get_vendor(struct cam_device *cam_dev);
130 static char	*fw_read_img(const char *fw_img_path,
131 		    const struct fw_vendor *vp, int *num_bytes);
132 static int	 fw_download_img(struct cam_device *cam_dev,
133 		    const struct fw_vendor *vp, char *buf, int img_size,
134 		    int sim_mode, int printerrors, int retry_count, int timeout,
135 		    const char */*name*/, const char */*type*/);
136 
137 /*
138  * Find entry in vendors list that belongs to
139  * the vendor of given cam device.
140  */
141 static const struct fw_vendor *
142 fw_get_vendor(struct cam_device *cam_dev)
143 {
144 	char vendor[SID_VENDOR_SIZE + 1];
145 	const struct fw_vendor *vp;
146 
147 	if (cam_dev == NULL)
148 		return (NULL);
149 	cam_strvis((u_char *)vendor, (u_char *)cam_dev->inq_data.vendor,
150 	    sizeof(cam_dev->inq_data.vendor), sizeof(vendor));
151 	for (vp = vendors_list; vp->pattern != NULL; vp++) {
152 		if (!cam_strmatch((const u_char *)vendor,
153 		    (const u_char *)vp->pattern, strlen(vendor)))
154 			break;
155 	}
156 	return (vp);
157 }
158 
159 /*
160  * Allocate a buffer and read fw image file into it
161  * from given path. Number of bytes read is stored
162  * in num_bytes.
163  */
164 static char *
165 fw_read_img(const char *fw_img_path, const struct fw_vendor *vp, int *num_bytes)
166 {
167 	int fd;
168 	struct stat stbuf;
169 	char *buf;
170 	off_t img_size;
171 	int skip_bytes = 0;
172 
173 	if ((fd = open(fw_img_path, O_RDONLY)) < 0) {
174 		warn("Could not open image file %s", fw_img_path);
175 		return (NULL);
176 	}
177 	if (fstat(fd, &stbuf) < 0) {
178 		warn("Could not stat image file %s", fw_img_path);
179 		goto bailout1;
180 	}
181 	if ((img_size = stbuf.st_size) == 0) {
182 		warnx("Zero length image file %s", fw_img_path);
183 		goto bailout1;
184 	}
185 	if ((buf = malloc(img_size)) == NULL) {
186 		warnx("Could not allocate buffer to read image file %s",
187 		    fw_img_path);
188 		goto bailout1;
189 	}
190 	/* Skip headers if applicable. */
191 	switch (vp->type) {
192 	case VENDOR_SEAGATE:
193 		if (read(fd, buf, 16) != 16) {
194 			warn("Could not read image file %s", fw_img_path);
195 			goto bailout;
196 		}
197 		if (lseek(fd, 0, SEEK_SET) == -1) {
198 			warn("Unable to lseek");
199 			goto bailout;
200 		}
201 		if ((strncmp(buf, "SEAGATE,SEAGATE ", 16) == 0) ||
202 		    (img_size % 512 == 80))
203 			skip_bytes = 80;
204 		break;
205 	case VENDOR_QUALSTAR:
206 		skip_bytes = img_size % 1030;
207 		break;
208 	default:
209 		break;
210 	}
211 	if (skip_bytes != 0) {
212 		fprintf(stdout, "Skipping %d byte header.\n", skip_bytes);
213 		if (lseek(fd, skip_bytes, SEEK_SET) == -1) {
214 			warn("Could not lseek");
215 			goto bailout;
216 		}
217 		img_size -= skip_bytes;
218 	}
219 	/* Read image into a buffer. */
220 	if (read(fd, buf, img_size) != img_size) {
221 		warn("Could not read image file %s", fw_img_path);
222 		goto bailout;
223 	}
224 	*num_bytes = img_size;
225 	return (buf);
226 bailout:
227 	free(buf);
228 bailout1:
229 	close(fd);
230 	*num_bytes = 0;
231 	return (NULL);
232 }
233 
234 /*
235  * Download firmware stored in buf to cam_dev. If simulation mode
236  * is enabled, only show what packet sizes would be sent to the
237  * device but do not sent any actual packets
238  */
239 static int
240 fw_download_img(struct cam_device *cam_dev, const struct fw_vendor *vp,
241     char *buf, int img_size, int sim_mode, int printerrors, int retry_count,
242     int timeout, const char *imgname, const char *type)
243 {
244 	struct scsi_write_buffer cdb;
245 	progress_t progress;
246 	int size;
247 	union ccb *ccb;
248 	int pkt_count = 0;
249 	int max_pkt_size;
250 	u_int32_t pkt_size = 0;
251 	char *pkt_ptr = buf;
252 	u_int32_t offset;
253 	int last_pkt = 0;
254 	int16_t *ptr;
255 
256 	if ((ccb = cam_getccb(cam_dev)) == NULL) {
257 		warnx("Could not allocate CCB");
258 		return (1);
259 	}
260 	if (strcmp(type, "scsi") == 0) {
261 		scsi_test_unit_ready(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG,
262 		    SSD_FULL_SIZE, 5000);
263 	} else if (strcmp(type, "ata") == 0) {
264 		/* cam_getccb cleans up the header, caller has to zero the payload */
265 		bzero(&(&ccb->ccb_h)[1],
266 		      sizeof(struct ccb_ataio) - sizeof(struct ccb_hdr));
267 
268 		ptr = (uint16_t *)malloc(sizeof(struct ata_params));
269 
270 		if (ptr == NULL) {
271 			cam_freeccb(ccb);
272 			warnx("can't malloc memory for identify\n");
273 			return(1);
274 		}
275 		bzero(ptr, sizeof(struct ata_params));
276 		cam_fill_ataio(&ccb->ataio,
277                       1,
278                       NULL,
279                       /*flags*/CAM_DIR_IN,
280                       MSG_SIMPLE_Q_TAG,
281                       /*data_ptr*/(uint8_t *)ptr,
282                       /*dxfer_len*/sizeof(struct ata_params),
283                       timeout ? timeout : 30 * 1000);
284 		ata_28bit_cmd(&ccb->ataio, ATA_ATA_IDENTIFY, 0, 0, 0);
285 	} else {
286 		warnx("weird disk type '%s'", type);
287 		return 1;
288 	}
289 	/* Disable freezing the device queue. */
290 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
291 	if (cam_send_ccb(cam_dev, ccb) < 0) {
292 		warnx("Error sending identify/test unit ready");
293 		if (printerrors)
294 			cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
295 			    CAM_EPF_ALL, stderr);
296 		cam_freeccb(ccb);
297 		return(1);
298 	}
299 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
300 		warnx("Device is not ready");
301 		if (printerrors)
302 			cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
303 			    CAM_EPF_ALL, stderr);
304 		cam_freeccb(ccb);
305 		return (1);
306 	}
307 	max_pkt_size = vp->max_pkt_size;
308 	if (vp->max_pkt_size == 0 && strcmp(type, "ata") == 0) {
309 		max_pkt_size = UNKNOWN_MAX_PKT_SIZE;
310 	}
311 	pkt_size = vp->max_pkt_size;
312 	progress_init(&progress, imgname, size = img_size);
313 	/* Download single fw packets. */
314 	do {
315 		if (img_size <= max_pkt_size) {
316 			last_pkt = 1;
317 			pkt_size = img_size;
318 		}
319 		progress_update(&progress, size - img_size);
320 		progress_draw(&progress);
321 		bzero(&cdb, sizeof(cdb));
322 		if (strcmp(type, "scsi") == 0) {
323 			cdb.opcode  = WRITE_BUFFER;
324 			cdb.control = 0;
325 			/* Parameter list length. */
326 			scsi_ulto3b(pkt_size, &cdb.length[0]);
327 			offset = vp->inc_cdb_offset ? (pkt_ptr - buf) : 0;
328 			scsi_ulto3b(offset, &cdb.offset[0]);
329 			cdb.byte2 = last_pkt ? vp->cdb_byte2_last : vp->cdb_byte2;
330 			cdb.buffer_id = vp->inc_cdb_buffer_id ? pkt_count : 0;
331 			/* Zero out payload of ccb union after ccb header. */
332 			bzero((u_char *)ccb + sizeof(struct ccb_hdr),
333 			    sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
334 			/* Copy previously constructed cdb into ccb_scsiio struct. */
335 			bcopy(&cdb, &ccb->csio.cdb_io.cdb_bytes[0],
336 			    sizeof(struct scsi_write_buffer));
337 			/* Fill rest of ccb_scsiio struct. */
338 			if (!sim_mode) {
339 				cam_fill_csio(&ccb->csio,		/* ccb_scsiio	*/
340 				    retry_count,			/* retries	*/
341 				    NULL,				/* cbfcnp	*/
342 				    CAM_DIR_OUT | CAM_DEV_QFRZDIS,	/* flags	*/
343 				    CAM_TAG_ACTION_NONE,		/* tag_action	*/
344 				    (u_char *)pkt_ptr,			/* data_ptr	*/
345 				    pkt_size,				/* dxfer_len	*/
346 				    SSD_FULL_SIZE,			/* sense_len	*/
347 				    sizeof(struct scsi_write_buffer),	/* cdb_len	*/
348 				    timeout ? timeout : CMD_TIMEOUT);	/* timeout	*/
349 			}
350 		} else if (strcmp(type, "ata") == 0) {
351 			bzero(&(&ccb->ccb_h)[1],
352 			      sizeof(struct ccb_ataio) - sizeof(struct ccb_hdr));
353 			if (!sim_mode) {
354 				uint32_t	off;
355 
356 				cam_fill_ataio(&ccb->ataio,
357 					(last_pkt) ? 256 : retry_count,
358 					NULL,
359 					/*flags*/CAM_DIR_OUT | CAM_DEV_QFRZDIS,
360 					CAM_TAG_ACTION_NONE,
361 					/*data_ptr*/(uint8_t *)pkt_ptr,
362 					/*dxfer_len*/pkt_size,
363 					timeout ? timeout : 30 * 1000);
364 				off = (uint32_t)(pkt_ptr - buf);
365 				ata_28bit_cmd(&ccb->ataio, ATA_DOWNLOAD_MICROCODE,
366 					USE_OFFSETS_FEATURE,
367 					ATA_MAKE_LBA(off, pkt_size),
368 					ATA_MAKE_SECTORS(pkt_size));
369 			}
370 		}
371 		if (!sim_mode) {
372 			/* Execute the command. */
373 			if (cam_send_ccb(cam_dev, ccb) < 0 ||
374 			    (ccb->ccb_h.status & CAM_STATUS_MASK) !=
375 			    CAM_REQ_CMP) {
376 				warnx("Error writing image to device");
377 				if (printerrors)
378 					cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
379 						   CAM_EPF_ALL, stderr);
380 				goto bailout;
381 			}
382 		}
383 		/* Prepare next round. */
384 		pkt_count++;
385 		pkt_ptr += pkt_size;
386 		img_size -= pkt_size;
387 	} while(!last_pkt);
388 	progress_complete(&progress, size - img_size);
389 	cam_freeccb(ccb);
390 	return (0);
391 bailout:
392 	progress_complete(&progress, size - img_size);
393 	cam_freeccb(ccb);
394 	return (1);
395 }
396 
397 int
398 fwdownload(struct cam_device *device, int argc, char **argv,
399     char *combinedopt, int printerrors, int retry_count, int timeout,
400     const char *type)
401 {
402 	const struct fw_vendor *vp;
403 	char *fw_img_path = NULL;
404 	char *buf;
405 	int img_size;
406 	int c;
407 	int sim_mode = 0;
408 	int confirmed = 0;
409 
410 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
411 		switch (c) {
412 		case 's':
413 			sim_mode = 1;
414 			confirmed = 1;
415 			break;
416 		case 'f':
417 			fw_img_path = optarg;
418 			break;
419 		case 'y':
420 			confirmed = 1;
421 			break;
422 		default:
423 			break;
424 		}
425 	}
426 
427 	if (fw_img_path == NULL)
428 		errx(1, "you must specify a firmware image file using -f option");
429 
430 	vp = fw_get_vendor(device);
431 	if (vp == NULL)
432 		errx(1, "NULL vendor");
433 	if (vp->type == VENDOR_UNKNOWN)
434 		warnx("Unsupported device - flashing through an HBA?");
435 
436 	buf = fw_read_img(fw_img_path, vp, &img_size);
437 	if (buf == NULL)
438 		goto fail;
439 
440 	if (!confirmed) {
441 		fprintf(stdout, "You are about to download firmware image (%s)"
442 		    " into the following device:\n",
443 		    fw_img_path);
444 		fprintf(stdout, "\nIt may damage your drive. ");
445 		if (!get_confirmation())
446 			goto fail;
447 	}
448 	if (sim_mode)
449 		fprintf(stdout, "Running in simulation mode\n");
450 
451 	if (fw_download_img(device, vp, buf, img_size, sim_mode, printerrors,
452 	    retry_count, timeout, fw_img_path, type) != 0) {
453 		fprintf(stderr, "Firmware download failed\n");
454 		goto fail;
455 	}
456 	else
457 		fprintf(stdout, "Firmware download successful\n");
458 
459 	free(buf);
460 	return (0);
461 fail:
462 	if (buf != NULL)
463 		free(buf);
464 	return (1);
465 }
466 
467