]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - scsicmds.cpp
9d0439469006fc4826583f72af7bd7102c3c2aa6
[mirror_smartmontools-debian.git] / scsicmds.cpp
1 /*
2 * scsicmds.cpp
3 *
4 * Home page of code is: http://www.smartmontools.org
5 *
6 * Copyright (C) 2002-8 Bruce Allen
7 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
8 * Copyright (C) 2003-16 Douglas Gilbert <dgilbert@interlog.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
13 * any later version.
14 *
15 * You should have received a copy of the GNU General Public License
16 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
17 *
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
22 *
23 *
24 * In the SCSI world "SMART" is a dead or withdrawn standard. In recent
25 * SCSI standards (since SCSI-3) it goes under the awkward name of
26 * "Informational Exceptions" ["IE" or "IEC" (with the "C" for "control")].
27 * The relevant information is spread around several SCSI draft
28 * standards available at http://www.t10.org . Reference is made in the
29 * code to the following acronyms:
30 * - SAM [SCSI Architectural model, versions 2 or 3]
31 * - SPC [SCSI Primary commands, versions 2 or 3]
32 * - SBC [SCSI Block commands, versions 2]
33 *
34 * Some SCSI disk vendors have snippets of "SMART" information in their
35 * product manuals.
36 */
37
38 #include <stdio.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <ctype.h>
42
43 #include "config.h"
44 #include "int64.h"
45 #include "scsicmds.h"
46 #include "atacmds.h" // FIXME: for smart_command_set only
47 #include "dev_interface.h"
48 #include "utility.h"
49
50 const char *scsicmds_c_cvsid="$Id: scsicmds.cpp 4414 2017-03-27 21:00:46Z chrfranke $"
51 SCSICMDS_H_CVSID;
52
53 // Print SCSI debug messages?
54 unsigned char scsi_debugmode = 0;
55
56 supported_vpd_pages * supported_vpd_pages_p = NULL;
57
58
59 supported_vpd_pages::supported_vpd_pages(scsi_device * device) : num_valid(0)
60 {
61 unsigned char b[0xfc]; /* pre SPC-3 INQUIRY max response size */
62 memset(b, 0, sizeof(b));
63 if (device && (0 == scsiInquiryVpd(device, SCSI_VPD_SUPPORTED_VPD_PAGES,
64 b, sizeof(b)))) {
65 num_valid = (b[2] << 8) + b[3];
66 int n = sizeof(pages);
67 if (num_valid > n)
68 num_valid = n;
69 memcpy(pages, b + 4, num_valid);
70 }
71 }
72
73 bool
74 supported_vpd_pages::is_supported(int vpd_page_num) const
75 {
76 /* Supported VPD pages numbers start at offset 4 and should be in
77 * ascending order but don't assume that. */
78 for (int k = 0; k < num_valid; ++k) {
79 if (vpd_page_num == pages[k])
80 return true;
81 }
82 return false;
83 }
84
85 /* output binary in hex and optionally ascii */
86 void
87 dStrHex(const char* str, int len, int no_ascii)
88 {
89 const char* p = str;
90 char buff[82];
91 int a = 0;
92 const int bpstart = 5;
93 const int cpstart = 60;
94 int cpos = cpstart;
95 int bpos = bpstart;
96 int i, k;
97
98 if (len <= 0) return;
99 memset(buff,' ',80);
100 buff[80]='\0';
101 k = snprintf(buff+1, sizeof(buff)-1, "%.2x", a);
102 buff[k + 1] = ' ';
103 if (bpos >= ((bpstart + (9 * 3))))
104 bpos++;
105
106 for(i = 0; i < len; i++)
107 {
108 unsigned char c = *p++;
109 bpos += 3;
110 if (bpos == (bpstart + (9 * 3)))
111 bpos++;
112 snprintf(buff+bpos, sizeof(buff)-bpos, "%.2x", (int)(unsigned char)c);
113 buff[bpos + 2] = ' ';
114 if (no_ascii)
115 buff[cpos++] = ' ';
116 else {
117 if ((c < ' ') || (c >= 0x7f))
118 c='.';
119 buff[cpos++] = c;
120 }
121 if (cpos > (cpstart+15))
122 {
123 while (cpos > 0 && buff[cpos-1] == ' ')
124 cpos--;
125 buff[cpos] = 0;
126 pout("%s\n", buff);
127 bpos = bpstart;
128 cpos = cpstart;
129 a += 16;
130 memset(buff,' ',80);
131 k = snprintf(buff+1, sizeof(buff)-1, "%.2x", a);
132 buff[k + 1] = ' ';
133 }
134 }
135 if (cpos > cpstart)
136 {
137 while (cpos > 0 && buff[cpos-1] == ' ')
138 cpos--;
139 buff[cpos] = 0;
140 pout("%s\n", buff);
141 }
142 }
143
144 struct scsi_opcode_name {
145 UINT8 opcode;
146 const char * name;
147 };
148
149 static struct scsi_opcode_name opcode_name_arr[] = {
150 /* in ascending opcode order */
151 {TEST_UNIT_READY, "test unit ready"}, /* 0x00 */
152 {REQUEST_SENSE, "request sense"}, /* 0x03 */
153 {INQUIRY, "inquiry"}, /* 0x12 */
154 {MODE_SELECT, "mode select(6)"}, /* 0x15 */
155 {MODE_SENSE, "mode sense(6)"}, /* 0x1a */
156 {START_STOP_UNIT, "start stop unit"}, /* 0x1b */
157 {RECEIVE_DIAGNOSTIC, "receive diagnostic"}, /* 0x1c */
158 {SEND_DIAGNOSTIC, "send diagnostic"}, /* 0x1d */
159 {READ_CAPACITY_10, "read capacity(10)"}, /* 0x25 */
160 {READ_DEFECT_10, "read defect list(10)"}, /* 0x37 */
161 {LOG_SELECT, "log select"}, /* 0x4c */
162 {LOG_SENSE, "log sense"}, /* 0x4d */
163 {MODE_SELECT_10, "mode select(10)"}, /* 0x55 */
164 {MODE_SENSE_10, "mode sense(10)"}, /* 0x5a */
165 {SAT_ATA_PASSTHROUGH_16, "ata pass-through(16)"}, /* 0x85 */
166 {READ_CAPACITY_16, "read capacity(16)"}, /* 0x9e,0x10 */
167 {REPORT_LUNS, "report luns"}, /* 0xa0 */
168 {SAT_ATA_PASSTHROUGH_12, "ata pass-through(12)"}, /* 0xa1 */
169 {READ_DEFECT_12, "read defect list(12)"}, /* 0xb7 */
170 };
171
172 static const char * vendor_specific = "<vendor specific>";
173
174 /* Need to expand to take service action into account. For commands
175 * of interest the service action is in the 2nd command byte */
176 const char *
177 scsi_get_opcode_name(UINT8 opcode)
178 {
179 int len = sizeof(opcode_name_arr) / sizeof(opcode_name_arr[0]);
180
181 if (opcode >= 0xc0)
182 return vendor_specific;
183 for (int k = 0; k < len; ++k) {
184 struct scsi_opcode_name * onp = &opcode_name_arr[k];
185 if (opcode == onp->opcode)
186 return onp->name;
187 else if (opcode < onp->opcode)
188 return NULL;
189 }
190 return NULL;
191 }
192
193 void
194 scsi_do_sense_disect(const struct scsi_cmnd_io * io_buf,
195 struct scsi_sense_disect * out)
196 {
197 memset(out, 0, sizeof(struct scsi_sense_disect));
198 if (SCSI_STATUS_CHECK_CONDITION == io_buf->scsi_status) {
199 int resp_code = (io_buf->sensep[0] & 0x7f);
200 out->resp_code = resp_code;
201 if (resp_code >= 0x72) {
202 out->sense_key = (io_buf->sensep[1] & 0xf);
203 out->asc = io_buf->sensep[2];
204 out->ascq = io_buf->sensep[3];
205 } else if (resp_code >= 0x70) {
206 out->sense_key = (io_buf->sensep[2] & 0xf);
207 if (io_buf->resp_sense_len > 13) {
208 out->asc = io_buf->sensep[12];
209 out->ascq = io_buf->sensep[13];
210 }
211 }
212 }
213 }
214
215 int
216 scsiSimpleSenseFilter(const struct scsi_sense_disect * sinfo)
217 {
218 switch (sinfo->sense_key) {
219 case SCSI_SK_NO_SENSE:
220 case SCSI_SK_RECOVERED_ERR:
221 return SIMPLE_NO_ERROR;
222 case SCSI_SK_NOT_READY:
223 if (SCSI_ASC_NO_MEDIUM == sinfo->asc)
224 return SIMPLE_ERR_NO_MEDIUM;
225 else if (SCSI_ASC_NOT_READY == sinfo->asc) {
226 if (0x1 == sinfo->ascq)
227 return SIMPLE_ERR_BECOMING_READY;
228 else
229 return SIMPLE_ERR_NOT_READY;
230 } else
231 return SIMPLE_ERR_NOT_READY;
232 case SCSI_SK_MEDIUM_ERROR:
233 case SCSI_SK_HARDWARE_ERROR:
234 return SIMPLE_ERR_MEDIUM_HARDWARE;
235 case SCSI_SK_ILLEGAL_REQUEST:
236 if (SCSI_ASC_UNKNOWN_OPCODE == sinfo->asc)
237 return SIMPLE_ERR_BAD_OPCODE;
238 else if (SCSI_ASC_INVALID_FIELD == sinfo->asc)
239 return SIMPLE_ERR_BAD_FIELD;
240 else if (SCSI_ASC_UNKNOWN_PARAM == sinfo->asc)
241 return SIMPLE_ERR_BAD_PARAM;
242 else
243 return SIMPLE_ERR_BAD_PARAM; /* all other illegal request */
244 case SCSI_SK_UNIT_ATTENTION:
245 return SIMPLE_ERR_TRY_AGAIN;
246 case SCSI_SK_ABORTED_COMMAND:
247 return SIMPLE_ERR_ABORTED_COMMAND;
248 default:
249 return SIMPLE_ERR_UNKNOWN;
250 }
251 }
252
253 const char *
254 scsiErrString(int scsiErr)
255 {
256 if (scsiErr < 0)
257 return strerror(-scsiErr);
258 switch (scsiErr) {
259 case SIMPLE_NO_ERROR:
260 return "no error";
261 case SIMPLE_ERR_NOT_READY:
262 return "device not ready";
263 case SIMPLE_ERR_BAD_OPCODE:
264 return "unsupported scsi opcode";
265 case SIMPLE_ERR_BAD_FIELD:
266 return "unsupported field in scsi command";
267 case SIMPLE_ERR_BAD_PARAM:
268 return "badly formed scsi parameters";
269 case SIMPLE_ERR_BAD_RESP:
270 return "scsi response fails sanity test";
271 case SIMPLE_ERR_NO_MEDIUM:
272 return "no medium present";
273 case SIMPLE_ERR_BECOMING_READY:
274 return "device will be ready soon";
275 case SIMPLE_ERR_TRY_AGAIN:
276 return "unit attention reported, try again";
277 case SIMPLE_ERR_MEDIUM_HARDWARE:
278 return "medium or hardware error (serious)";
279 case SIMPLE_ERR_UNKNOWN:
280 return "unknown error (unexpected sense key)";
281 case SIMPLE_ERR_ABORTED_COMMAND:
282 return "aborted command";
283 default:
284 return "unknown error";
285 }
286 }
287
288 /* Iterates to next designation descriptor in the device identification
289 * VPD page. The 'initial_desig_desc' should point to start of first
290 * descriptor with 'page_len' being the number of valid bytes in that
291 * and following descriptors. To start, 'off' should point to a negative
292 * value, thereafter it should point to the value yielded by the previous
293 * call. If 0 returned then 'initial_desig_desc + *off' should be a valid
294 * descriptor; returns -1 if normal end condition and -2 for an abnormal
295 * termination. Matches association, designator_type and/or code_set when
296 * any of those values are greater than or equal to zero. */
297 int
298 scsi_vpd_dev_id_iter(const unsigned char * initial_desig_desc, int page_len,
299 int * off, int m_assoc, int m_desig_type, int m_code_set)
300 {
301 const unsigned char * ucp;
302 int k;
303
304 for (k = *off, ucp = initial_desig_desc ; (k + 3) < page_len; ) {
305 k = (k < 0) ? 0 : (k + ucp[k + 3] + 4);
306 if ((k + 4) > page_len)
307 break;
308 int c_set = (ucp[k] & 0xf);
309 if ((m_code_set >= 0) && (m_code_set != c_set))
310 continue;
311 int assoc = ((ucp[k + 1] >> 4) & 0x3);
312 if ((m_assoc >= 0) && (m_assoc != assoc))
313 continue;
314 int desig_type = (ucp[k + 1] & 0xf);
315 if ((m_desig_type >= 0) && (m_desig_type != desig_type))
316 continue;
317 *off = k;
318 return 0;
319 }
320 return (k == page_len) ? -1 : -2;
321 }
322
323 /* Decode VPD page 0x83 logical unit designator into a string. If both
324 * numeric address and SCSI name string present, prefer the former.
325 * Returns 0 on success, -1 on error with error string in s. */
326 int
327 scsi_decode_lu_dev_id(const unsigned char * b, int blen, char * s, int slen,
328 int * transport)
329 {
330 if (transport)
331 *transport = -1;
332 if (slen < 32) {
333 if (slen > 0)
334 s[0] = '\0';
335 return -1;
336 }
337
338 s[0] = '\0';
339 int si = 0;
340 int have_scsi_ns = 0;
341 int off = -1;
342 int u;
343 while ((u = scsi_vpd_dev_id_iter(b, blen, &off, -1, -1, -1)) == 0) {
344 const unsigned char * ucp = b + off;
345 int i_len = ucp[3];
346 if ((off + i_len + 4) > blen) {
347 snprintf(s+si, slen-si, "error: designator length");
348 return -1;
349 }
350 int assoc = ((ucp[1] >> 4) & 0x3);
351 if (transport && assoc && (ucp[1] & 0x80) && (*transport < 0))
352 *transport = (ucp[0] >> 4) & 0xf;
353 if (0 != assoc)
354 continue;
355 const unsigned char * ip = ucp + 4;
356 int c_set = (ucp[0] & 0xf);
357 int desig_type = (ucp[1] & 0xf);
358
359 int naa;
360 switch (desig_type) {
361 case 0: /* vendor specific */
362 case 1: /* T10 vendor identification */
363 break;
364 case 2: /* EUI-64 based */
365 if ((8 != i_len) && (12 != i_len) && (16 != i_len)) {
366 snprintf(s+si, slen-si, "error: EUI-64 length");
367 return -1;
368 }
369 if (have_scsi_ns)
370 si = 0;
371 si += snprintf(s+si, slen-si, "0x");
372 for (int m = 0; m < i_len; ++m)
373 si += snprintf(s+si, slen-si, "%02x", (unsigned int)ip[m]);
374 break;
375 case 3: /* NAA */
376 if (1 != c_set) {
377 snprintf(s+si, slen-si, "error: NAA bad code_set");
378 return -1;
379 }
380 naa = (ip[0] >> 4) & 0xff;
381 if ((naa < 2) || (naa > 6) || (4 == naa)) {
382 snprintf(s+si, slen-si, "error: unexpected NAA");
383 return -1;
384 }
385 if (have_scsi_ns)
386 si = 0;
387 if (2 == naa) { /* NAA IEEE Extended */
388 if (8 != i_len) {
389 snprintf(s+si, slen-si, "error: NAA 2 length");
390 return -1;
391 }
392 si += snprintf(s+si, slen-si, "0x");
393 for (int m = 0; m < 8; ++m)
394 si += snprintf(s+si, slen-si, "%02x", (unsigned int)ip[m]);
395 } else if ((3 == naa ) || (5 == naa)) {
396 /* NAA=3 Locally assigned; NAA=5 IEEE Registered */
397 if (8 != i_len) {
398 snprintf(s+si, slen-si, "error: NAA 3 or 5 length");
399 return -1;
400 }
401 si += snprintf(s+si, slen-si, "0x");
402 for (int m = 0; m < 8; ++m)
403 si += snprintf(s+si, slen-si, "%02x", (unsigned int)ip[m]);
404 } else if (6 == naa) { /* NAA IEEE Registered extended */
405 if (16 != i_len) {
406 snprintf(s+si, slen-si, "error: NAA 6 length");
407 return -1;
408 }
409 si += snprintf(s+si, slen-si, "0x");
410 for (int m = 0; m < 16; ++m)
411 si += snprintf(s+si, slen-si, "%02x", (unsigned int)ip[m]);
412 }
413 break;
414 case 4: /* Relative target port */
415 case 5: /* (primary) Target port group */
416 case 6: /* Logical unit group */
417 case 7: /* MD5 logical unit identifier */
418 break;
419 case 8: /* SCSI name string */
420 if (3 != c_set) {
421 snprintf(s+si, slen-si, "error: SCSI name string");
422 return -1;
423 }
424 /* does %s print out UTF-8 ok?? */
425 if (si == 0) {
426 si += snprintf(s+si, slen-si, "%s", (const char *)ip);
427 ++have_scsi_ns;
428 }
429 break;
430 default: /* reserved */
431 break;
432 }
433 }
434 if (-2 == u) {
435 snprintf(s+si, slen-si, "error: bad structure");
436 return -1;
437 }
438 return 0;
439 }
440
441 /* Sends LOG SENSE command. Returns 0 if ok, 1 if device NOT READY, 2 if
442 command not supported, 3 if field (within command) not supported or
443 returns negated errno. SPC-3 sections 6.6 and 7.2 (rec 22a).
444 N.B. Sets PC==1 to fetch "current cumulative" log pages.
445 If known_resp_len > 0 then a single fetch is done for this response
446 length. If known_resp_len == 0 then twin fetches are performed, the
447 first to deduce the response length, then send the same command again
448 requesting the deduced response length. This protects certain fragile
449 HBAs. The twin fetch technique should not be used with the TapeAlert
450 log page since it clears its state flags after each fetch. */
451 int
452 scsiLogSense(scsi_device * device, int pagenum, int subpagenum, UINT8 *pBuf,
453 int bufLen, int known_resp_len)
454 {
455 struct scsi_cmnd_io io_hdr;
456 struct scsi_sense_disect sinfo;
457 UINT8 cdb[10];
458 UINT8 sense[32];
459 int pageLen;
460
461 if (known_resp_len > bufLen)
462 return -EIO;
463 if (known_resp_len > 0)
464 pageLen = known_resp_len;
465 else {
466 /* Starting twin fetch strategy: first fetch to find respone length */
467 pageLen = 4;
468 if (pageLen > bufLen)
469 return -EIO;
470 else
471 memset(pBuf, 0, pageLen);
472
473 memset(&io_hdr, 0, sizeof(io_hdr));
474 memset(cdb, 0, sizeof(cdb));
475 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
476 io_hdr.dxfer_len = pageLen;
477 io_hdr.dxferp = pBuf;
478 cdb[0] = LOG_SENSE;
479 cdb[2] = 0x40 | (pagenum & 0x3f); /* Page control (PC)==1 */
480 cdb[3] = subpagenum;
481 cdb[7] = (pageLen >> 8) & 0xff;
482 cdb[8] = pageLen & 0xff;
483 io_hdr.cmnd = cdb;
484 io_hdr.cmnd_len = sizeof(cdb);
485 io_hdr.sensep = sense;
486 io_hdr.max_sense_len = sizeof(sense);
487 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
488
489 if (!device->scsi_pass_through(&io_hdr))
490 return -device->get_errno();
491 scsi_do_sense_disect(&io_hdr, &sinfo);
492 int res;
493 if ((res = scsiSimpleSenseFilter(&sinfo)))
494 return res;
495 /* sanity check on response */
496 if ((SUPPORTED_LPAGES != pagenum) && ((pBuf[0] & 0x3f) != pagenum))
497 return SIMPLE_ERR_BAD_RESP;
498 if (0 == ((pBuf[2] << 8) + pBuf[3]))
499 return SIMPLE_ERR_BAD_RESP;
500 pageLen = (pBuf[2] << 8) + pBuf[3] + 4;
501 if (4 == pageLen) /* why define a lpage with no payload? */
502 pageLen = 252; /* some IBM tape drives don't like double fetch */
503 /* some SCSI HBA don't like "odd" length transfers */
504 if (pageLen % 2)
505 pageLen += 1;
506 if (pageLen > bufLen)
507 pageLen = bufLen;
508 }
509 memset(pBuf, 0, 4);
510 memset(&io_hdr, 0, sizeof(io_hdr));
511 memset(cdb, 0, sizeof(cdb));
512 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
513 io_hdr.dxfer_len = pageLen;
514 io_hdr.dxferp = pBuf;
515 cdb[0] = LOG_SENSE;
516 cdb[2] = 0x40 | (pagenum & 0x3f); /* Page control (PC)==1 */
517 cdb[7] = (pageLen >> 8) & 0xff;
518 cdb[8] = pageLen & 0xff;
519 io_hdr.cmnd = cdb;
520 io_hdr.cmnd_len = sizeof(cdb);
521 io_hdr.sensep = sense;
522 io_hdr.max_sense_len = sizeof(sense);
523 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
524
525 if (!device->scsi_pass_through(&io_hdr))
526 return -device->get_errno();
527 scsi_do_sense_disect(&io_hdr, &sinfo);
528 int status = scsiSimpleSenseFilter(&sinfo);
529 if (0 != status)
530 return status;
531 /* sanity check on response */
532 if ((SUPPORTED_LPAGES != pagenum) && ((pBuf[0] & 0x3f) != pagenum))
533 return SIMPLE_ERR_BAD_RESP;
534 if (0 == ((pBuf[2] << 8) + pBuf[3]))
535 return SIMPLE_ERR_BAD_RESP;
536 return 0;
537 }
538
539 /* Sends a LOG SELECT command. Can be used to set log page values
540 * or reset one log page (or all of them) to its defaults (typically zero).
541 * Returns 0 if ok, 1 if NOT READY, 2 if command not supported, * 3 if
542 * field in command not supported, * 4 if bad parameter to command or
543 * returns negated errno. SPC-4 sections 6.5 and 7.2 (rev 20) */
544 int
545 scsiLogSelect(scsi_device * device, int pcr, int sp, int pc, int pagenum,
546 int subpagenum, UINT8 *pBuf, int bufLen)
547 {
548 struct scsi_cmnd_io io_hdr;
549 struct scsi_sense_disect sinfo;
550 UINT8 cdb[10];
551 UINT8 sense[32];
552
553 memset(&io_hdr, 0, sizeof(io_hdr));
554 memset(cdb, 0, sizeof(cdb));
555 io_hdr.dxfer_dir = DXFER_TO_DEVICE;
556 io_hdr.dxfer_len = bufLen;
557 io_hdr.dxferp = pBuf;
558 cdb[0] = LOG_SELECT;
559 cdb[1] = (pcr ? 2 : 0) | (sp ? 1 : 0);
560 cdb[2] = ((pc << 6) & 0xc0) | (pagenum & 0x3f);
561 cdb[3] = (subpagenum & 0xff);
562 cdb[7] = ((bufLen >> 8) & 0xff);
563 cdb[8] = (bufLen & 0xff);
564 io_hdr.cmnd = cdb;
565 io_hdr.cmnd_len = sizeof(cdb);
566 io_hdr.sensep = sense;
567 io_hdr.max_sense_len = sizeof(sense);
568 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
569
570 if (!device->scsi_pass_through(&io_hdr))
571 return -device->get_errno();
572 scsi_do_sense_disect(&io_hdr, &sinfo);
573 return scsiSimpleSenseFilter(&sinfo);
574 }
575
576 /* Send MODE SENSE (6 byte) command. Returns 0 if ok, 1 if NOT READY,
577 * 2 if command not supported (then MODE SENSE(10) should be supported),
578 * 3 if field in command not supported or returns negated errno.
579 * SPC-3 sections 6.9 and 7.4 (rev 22a) [mode subpage==0] */
580 int
581 scsiModeSense(scsi_device * device, int pagenum, int subpagenum, int pc,
582 UINT8 *pBuf, int bufLen)
583 {
584 struct scsi_cmnd_io io_hdr;
585 struct scsi_sense_disect sinfo;
586 UINT8 cdb[6];
587 UINT8 sense[32];
588
589 if ((bufLen < 0) || (bufLen > 255))
590 return -EINVAL;
591 memset(&io_hdr, 0, sizeof(io_hdr));
592 memset(cdb, 0, sizeof(cdb));
593 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
594 io_hdr.dxfer_len = bufLen;
595 io_hdr.dxferp = pBuf;
596 cdb[0] = MODE_SENSE;
597 cdb[2] = (pc << 6) | (pagenum & 0x3f);
598 cdb[3] = subpagenum;
599 cdb[4] = bufLen;
600 io_hdr.cmnd = cdb;
601 io_hdr.cmnd_len = sizeof(cdb);
602 io_hdr.sensep = sense;
603 io_hdr.max_sense_len = sizeof(sense);
604 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
605
606 if (!device->scsi_pass_through(&io_hdr))
607 return -device->get_errno();
608 scsi_do_sense_disect(&io_hdr, &sinfo);
609 int status = scsiSimpleSenseFilter(&sinfo);
610 if (SIMPLE_ERR_TRY_AGAIN == status) {
611 if (!device->scsi_pass_through(&io_hdr))
612 return -device->get_errno();
613 scsi_do_sense_disect(&io_hdr, &sinfo);
614 status = scsiSimpleSenseFilter(&sinfo);
615 }
616 if ((0 == status) && (ALL_MODE_PAGES != pagenum)) {
617 int offset;
618
619 offset = scsiModePageOffset(pBuf, bufLen, 0);
620 if (offset < 0)
621 return SIMPLE_ERR_BAD_RESP;
622 else if (pagenum != (pBuf[offset] & 0x3f))
623 return SIMPLE_ERR_BAD_RESP;
624 }
625 return status;
626 }
627
628 /* Sends a 6 byte MODE SELECT command. Assumes given pBuf is the response
629 * from a corresponding 6 byte MODE SENSE command. Such a response should
630 * have a 4 byte header followed by 0 or more 8 byte block descriptors
631 * (normally 1) and then 1 mode page. Returns 0 if ok, 1 if NOT READY,
632 * 2 if command not supported (then MODE SELECT(10) may be supported),
633 * 3 if field in command not supported, 4 if bad parameter to command
634 * or returns negated errno. SPC-3 sections 6.7 and 7.4 (rev 22a) */
635 int
636 scsiModeSelect(scsi_device * device, int sp, UINT8 *pBuf, int bufLen)
637 {
638 struct scsi_cmnd_io io_hdr;
639 struct scsi_sense_disect sinfo;
640 UINT8 cdb[6];
641 UINT8 sense[32];
642 int pg_offset, pg_len, hdr_plus_1_pg;
643
644 pg_offset = 4 + pBuf[3];
645 if (pg_offset + 2 >= bufLen)
646 return -EINVAL;
647 pg_len = pBuf[pg_offset + 1] + 2;
648 hdr_plus_1_pg = pg_offset + pg_len;
649 if (hdr_plus_1_pg > bufLen)
650 return -EINVAL;
651 pBuf[0] = 0; /* Length of returned mode sense data reserved for SELECT */
652 pBuf[pg_offset] &= 0x7f; /* Mask out PS bit from byte 0 of page data */
653 memset(&io_hdr, 0, sizeof(io_hdr));
654 memset(cdb, 0, sizeof(cdb));
655 io_hdr.dxfer_dir = DXFER_TO_DEVICE;
656 io_hdr.dxfer_len = hdr_plus_1_pg;
657 io_hdr.dxferp = pBuf;
658 cdb[0] = MODE_SELECT;
659 cdb[1] = 0x10 | (sp & 1); /* set PF (page format) bit always */
660 cdb[4] = hdr_plus_1_pg; /* make sure only one page sent */
661 io_hdr.cmnd = cdb;
662 io_hdr.cmnd_len = sizeof(cdb);
663 io_hdr.sensep = sense;
664 io_hdr.max_sense_len = sizeof(sense);
665 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
666
667 if (!device->scsi_pass_through(&io_hdr))
668 return -device->get_errno();
669 scsi_do_sense_disect(&io_hdr, &sinfo);
670 return scsiSimpleSenseFilter(&sinfo);
671 }
672
673 /* MODE SENSE (10 byte). Returns 0 if ok, 1 if NOT READY, 2 if command
674 * not supported (then MODE SENSE(6) might be supported), 3 if field in
675 * command not supported or returns negated errno.
676 * SPC-3 sections 6.10 and 7.4 (rev 22a) [mode subpage==0] */
677 int
678 scsiModeSense10(scsi_device * device, int pagenum, int subpagenum, int pc,
679 UINT8 *pBuf, int bufLen)
680 {
681 struct scsi_cmnd_io io_hdr;
682 struct scsi_sense_disect sinfo;
683 UINT8 cdb[10];
684 UINT8 sense[32];
685
686 memset(&io_hdr, 0, sizeof(io_hdr));
687 memset(cdb, 0, sizeof(cdb));
688 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
689 io_hdr.dxfer_len = bufLen;
690 io_hdr.dxferp = pBuf;
691 cdb[0] = MODE_SENSE_10;
692 cdb[2] = (pc << 6) | (pagenum & 0x3f);
693 cdb[3] = subpagenum;
694 cdb[7] = (bufLen >> 8) & 0xff;
695 cdb[8] = bufLen & 0xff;
696 io_hdr.cmnd = cdb;
697 io_hdr.cmnd_len = sizeof(cdb);
698 io_hdr.sensep = sense;
699 io_hdr.max_sense_len = sizeof(sense);
700 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
701
702 if (!device->scsi_pass_through(&io_hdr))
703 return -device->get_errno();
704 scsi_do_sense_disect(&io_hdr, &sinfo);
705 int status = scsiSimpleSenseFilter(&sinfo);
706 if (SIMPLE_ERR_TRY_AGAIN == status) {
707 if (!device->scsi_pass_through(&io_hdr))
708 return -device->get_errno();
709 scsi_do_sense_disect(&io_hdr, &sinfo);
710 status = scsiSimpleSenseFilter(&sinfo);
711 }
712 if ((0 == status) && (ALL_MODE_PAGES != pagenum)) {
713 int offset;
714
715 offset = scsiModePageOffset(pBuf, bufLen, 1);
716 if (offset < 0)
717 return SIMPLE_ERR_BAD_RESP;
718 else if (pagenum != (pBuf[offset] & 0x3f))
719 return SIMPLE_ERR_BAD_RESP;
720 }
721 return status;
722 }
723
724 /* Sends a 10 byte MODE SELECT command. Assumes given pBuf is the response
725 * from a corresponding 10 byte MODE SENSE command. Such a response should
726 * have a 8 byte header followed by 0 or more 8 byte block descriptors
727 * (normally 1) and then 1 mode page. Returns 0 if ok, 1 NOT REAFY, 2 if
728 * command not supported (then MODE SELECT(6) may be supported), 3 if field
729 * in command not supported, 4 if bad parameter to command or returns
730 * negated errno. SPC-3 sections 6.8 and 7.4 (rev 22a) */
731 int
732 scsiModeSelect10(scsi_device * device, int sp, UINT8 *pBuf, int bufLen)
733 {
734 struct scsi_cmnd_io io_hdr;
735 struct scsi_sense_disect sinfo;
736 UINT8 cdb[10];
737 UINT8 sense[32];
738 int pg_offset, pg_len, hdr_plus_1_pg;
739
740 pg_offset = 8 + (pBuf[6] << 8) + pBuf[7];
741 if (pg_offset + 2 >= bufLen)
742 return -EINVAL;
743 pg_len = pBuf[pg_offset + 1] + 2;
744 hdr_plus_1_pg = pg_offset + pg_len;
745 if (hdr_plus_1_pg > bufLen)
746 return -EINVAL;
747 pBuf[0] = 0;
748 pBuf[1] = 0; /* Length of returned mode sense data reserved for SELECT */
749 pBuf[pg_offset] &= 0x7f; /* Mask out PS bit from byte 0 of page data */
750 memset(&io_hdr, 0, sizeof(io_hdr));
751 memset(cdb, 0, sizeof(cdb));
752 io_hdr.dxfer_dir = DXFER_TO_DEVICE;
753 io_hdr.dxfer_len = hdr_plus_1_pg;
754 io_hdr.dxferp = pBuf;
755 cdb[0] = MODE_SELECT_10;
756 cdb[1] = 0x10 | (sp & 1); /* set PF (page format) bit always */
757 cdb[8] = hdr_plus_1_pg; /* make sure only one page sent */
758 io_hdr.cmnd = cdb;
759 io_hdr.cmnd_len = sizeof(cdb);
760 io_hdr.sensep = sense;
761 io_hdr.max_sense_len = sizeof(sense);
762 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
763
764 if (!device->scsi_pass_through(&io_hdr))
765 return -device->get_errno();
766 scsi_do_sense_disect(&io_hdr, &sinfo);
767 return scsiSimpleSenseFilter(&sinfo);
768 }
769
770 /* Standard INQUIRY returns 0 for ok, anything else is a major problem.
771 * bufLen should be 36 for unsafe devices (like USB mass storage stuff)
772 * otherwise they can lock up! SPC-3 sections 6.4 and 7.6 (rev 22a) */
773 int
774 scsiStdInquiry(scsi_device * device, UINT8 *pBuf, int bufLen)
775 {
776 struct scsi_sense_disect sinfo;
777 struct scsi_cmnd_io io_hdr;
778 UINT8 cdb[6];
779 UINT8 sense[32];
780
781 if ((bufLen < 0) || (bufLen > 1023))
782 return -EINVAL;
783 memset(&io_hdr, 0, sizeof(io_hdr));
784 memset(cdb, 0, sizeof(cdb));
785 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
786 io_hdr.dxfer_len = bufLen;
787 io_hdr.dxferp = pBuf;
788 cdb[0] = INQUIRY;
789 cdb[3] = (bufLen >> 8) & 0xff;
790 cdb[4] = (bufLen & 0xff);
791 io_hdr.cmnd = cdb;
792 io_hdr.cmnd_len = sizeof(cdb);
793 io_hdr.sensep = sense;
794 io_hdr.max_sense_len = sizeof(sense);
795 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
796
797 if (!device->scsi_pass_through(&io_hdr))
798 return -device->get_errno();
799 scsi_do_sense_disect(&io_hdr, &sinfo);
800 return scsiSimpleSenseFilter(&sinfo);
801 }
802
803 /* INQUIRY to fetch Vital Page Data. Returns 0 if ok, 1 if NOT READY
804 * (unlikely), 2 if command not supported, 3 if field in command not
805 * supported, 5 if response indicates that EVPD bit ignored or returns
806 * negated errno. SPC-3 section 6.4 and 7.6 (rev 22a) */
807 int
808 scsiInquiryVpd(scsi_device * device, int vpd_page, UINT8 *pBuf, int bufLen)
809 {
810 struct scsi_cmnd_io io_hdr;
811 struct scsi_sense_disect sinfo;
812 UINT8 cdb[6];
813 UINT8 sense[32];
814 int res;
815
816 /* Assume SCSI_VPD_SUPPORTED_VPD_PAGES is first VPD page fetched */
817 if ((SCSI_VPD_SUPPORTED_VPD_PAGES != vpd_page) &&
818 supported_vpd_pages_p &&
819 (! supported_vpd_pages_p->is_supported(vpd_page)))
820 return 3;
821
822 if ((bufLen < 0) || (bufLen > 1023))
823 return -EINVAL;
824 try_again:
825 memset(&io_hdr, 0, sizeof(io_hdr));
826 memset(cdb, 0, sizeof(cdb));
827 if (bufLen > 1)
828 pBuf[1] = 0x0;
829 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
830 io_hdr.dxfer_len = bufLen;
831 io_hdr.dxferp = pBuf;
832 cdb[0] = INQUIRY;
833 cdb[1] = 0x1; /* set EVPD bit (enable Vital Product Data) */
834 cdb[2] = vpd_page;
835 cdb[3] = (bufLen >> 8) & 0xff;
836 cdb[4] = (bufLen & 0xff);
837 io_hdr.cmnd = cdb;
838 io_hdr.cmnd_len = sizeof(cdb);
839 io_hdr.sensep = sense;
840 io_hdr.max_sense_len = sizeof(sense);
841 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
842
843 if (!device->scsi_pass_through(&io_hdr))
844 return -device->get_errno();
845 scsi_do_sense_disect(&io_hdr, &sinfo);
846 if ((SCSI_STATUS_CHECK_CONDITION == io_hdr.scsi_status) &&
847 (SCSI_SK_ILLEGAL_REQUEST == sinfo.sense_key) &&
848 (SCSI_ASC_INVALID_FIELD == sinfo.asc) &&
849 (cdb[3] > 0)) {
850 bufLen &= 0xff; /* make sure cdb[3] is 0 next time around */
851 goto try_again;
852 }
853
854 if ((res = scsiSimpleSenseFilter(&sinfo)))
855 return res;
856 /* Guard against devices that ignore EVPD bit and do standard INQUIRY */
857 if (bufLen > 1) {
858 if (vpd_page == pBuf[1]) {
859 if ((0x80 == vpd_page) && (bufLen > 2) && (0x0 != pBuf[2]))
860 return SIMPLE_ERR_BAD_RESP;
861 } else
862 return SIMPLE_ERR_BAD_RESP;
863 }
864 return 0;
865 }
866
867 /* REQUEST SENSE command. Returns 0 if ok, anything else major problem.
868 * SPC-3 section 6.27 (rev 22a) */
869 int
870 scsiRequestSense(scsi_device * device, struct scsi_sense_disect * sense_info)
871 {
872 struct scsi_cmnd_io io_hdr;
873 UINT8 cdb[6];
874 UINT8 sense[32];
875 UINT8 buff[18];
876
877 memset(&io_hdr, 0, sizeof(io_hdr));
878 memset(cdb, 0, sizeof(cdb));
879 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
880 io_hdr.dxfer_len = sizeof(buff);
881 io_hdr.dxferp = buff;
882 cdb[0] = REQUEST_SENSE;
883 cdb[4] = sizeof(buff);
884 io_hdr.cmnd = cdb;
885 io_hdr.cmnd_len = sizeof(cdb);
886 io_hdr.sensep = sense;
887 io_hdr.max_sense_len = sizeof(sense);
888 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
889
890 if (!device->scsi_pass_through(&io_hdr))
891 return -device->get_errno();
892 if (sense_info) {
893 UINT8 resp_code = buff[0] & 0x7f;
894 sense_info->resp_code = resp_code;
895 sense_info->sense_key = buff[2] & 0xf;
896 sense_info->asc = 0;
897 sense_info->ascq = 0;
898 if ((0x70 == resp_code) || (0x71 == resp_code)) {
899 int len = buff[7] + 8;
900 if (len > 13) {
901 sense_info->asc = buff[12];
902 sense_info->ascq = buff[13];
903 }
904 }
905 // fill progrss indicator, if available
906 sense_info->progress = -1;
907 switch (resp_code) {
908 const unsigned char * ucp;
909 int sk, sk_pr;
910 case 0x70:
911 case 0x71:
912 sk = (buff[2] & 0xf);
913 if ((sizeof(buff) < 18) ||
914 ((SCSI_SK_NO_SENSE != sk) && (SCSI_SK_NOT_READY != sk))) {
915 break;
916 }
917 if (buff[15] & 0x80) { /* SKSV bit set */
918 sense_info->progress = (buff[16] << 8) + buff[17];
919 break;
920 } else {
921 break;
922 }
923 case 0x72:
924 case 0x73:
925 /* sense key specific progress (0x2) or progress descriptor (0xa) */
926 sk = (buff[1] & 0xf);
927 sk_pr = (SCSI_SK_NO_SENSE == sk) || (SCSI_SK_NOT_READY == sk);
928 if (sk_pr && ((ucp = sg_scsi_sense_desc_find(buff, sizeof(buff), 2))) &&
929 (0x6 == ucp[1]) && (0x80 & ucp[4])) {
930 sense_info->progress = (ucp[5] << 8) + ucp[6];
931 break;
932 } else if (((ucp = sg_scsi_sense_desc_find(buff, sizeof(buff), 0xa))) &&
933 ((0x6 == ucp[1]))) {
934 sense_info->progress = (ucp[6] << 8) + ucp[7];
935 break;
936 } else
937 break;
938 default:
939 return 0;
940 }
941 }
942 return 0;
943 }
944
945 /* SEND DIAGNOSTIC command. Returns 0 if ok, 1 if NOT READY, 2 if command
946 * not supported, 3 if field in command not supported or returns negated
947 * errno. SPC-3 section 6.28 (rev 22a) */
948 int
949 scsiSendDiagnostic(scsi_device * device, int functioncode, UINT8 *pBuf,
950 int bufLen)
951 {
952 struct scsi_cmnd_io io_hdr;
953 struct scsi_sense_disect sinfo;
954 UINT8 cdb[6];
955 UINT8 sense[32];
956
957 memset(&io_hdr, 0, sizeof(io_hdr));
958 memset(cdb, 0, sizeof(cdb));
959 io_hdr.dxfer_dir = bufLen ? DXFER_TO_DEVICE: DXFER_NONE;
960 io_hdr.dxfer_len = bufLen;
961 io_hdr.dxferp = pBuf;
962 cdb[0] = SEND_DIAGNOSTIC;
963 if (SCSI_DIAG_DEF_SELF_TEST == functioncode)
964 cdb[1] = 0x4; /* SelfTest bit */
965 else if (SCSI_DIAG_NO_SELF_TEST != functioncode)
966 cdb[1] = (functioncode & 0x7) << 5; /* SelfTest _code_ */
967 else /* SCSI_DIAG_NO_SELF_TEST == functioncode */
968 cdb[1] = 0x10; /* PF bit */
969 cdb[3] = (bufLen >> 8) & 0xff;
970 cdb[4] = bufLen & 0xff;
971 io_hdr.cmnd = cdb;
972 io_hdr.cmnd_len = sizeof(cdb);
973 io_hdr.sensep = sense;
974 io_hdr.max_sense_len = sizeof(sense);
975 /* worst case is an extended foreground self test on a big disk */
976 io_hdr.timeout = SCSI_TIMEOUT_SELF_TEST;
977
978 if (!device->scsi_pass_through(&io_hdr))
979 return -device->get_errno();
980 scsi_do_sense_disect(&io_hdr, &sinfo);
981 return scsiSimpleSenseFilter(&sinfo);
982 }
983
984 /* TEST UNIT READY command. SPC-3 section 6.33 (rev 22a) */
985 static int
986 _testunitready(scsi_device * device, struct scsi_sense_disect * sinfo)
987 {
988 struct scsi_cmnd_io io_hdr;
989 UINT8 cdb[6];
990 UINT8 sense[32];
991
992 memset(&io_hdr, 0, sizeof(io_hdr));
993 memset(cdb, 0, sizeof(cdb));
994 io_hdr.dxfer_dir = DXFER_NONE;
995 io_hdr.dxfer_len = 0;
996 io_hdr.dxferp = NULL;
997 cdb[0] = TEST_UNIT_READY;
998 io_hdr.cmnd = cdb;
999 io_hdr.cmnd_len = sizeof(cdb);
1000 io_hdr.sensep = sense;
1001 io_hdr.max_sense_len = sizeof(sense);
1002 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1003
1004 if (!device->scsi_pass_through(&io_hdr))
1005 return -device->get_errno();
1006 scsi_do_sense_disect(&io_hdr, sinfo);
1007 return 0;
1008 }
1009
1010 /* Returns 0 for device responds and media ready, 1 for device responds and
1011 media not ready, or returns a negated errno value */
1012 int
1013 scsiTestUnitReady(scsi_device * device)
1014 {
1015 struct scsi_sense_disect sinfo;
1016 int status;
1017
1018 status = _testunitready(device, &sinfo);
1019 if (0 != status)
1020 return status;
1021 status = scsiSimpleSenseFilter(&sinfo);
1022 if (SIMPLE_ERR_TRY_AGAIN == status) {
1023 /* power on reset, media changed, ok ... try again */
1024 status = _testunitready(device, &sinfo);
1025 if (0 != status)
1026 return status;
1027 status = scsiSimpleSenseFilter(&sinfo);
1028 }
1029 return status;
1030 }
1031
1032 /* READ DEFECT (10) command. Returns 0 if ok, 1 if NOT READY, 2 if
1033 * command not supported, 3 if field in command not supported, 101 if
1034 * defect list not found (e.g. SSD may not have defect list) or returns
1035 * negated errno. SBC-2 section 5.12 (rev 16) */
1036 int
1037 scsiReadDefect10(scsi_device * device, int req_plist, int req_glist,
1038 int dl_format, UINT8 *pBuf, int bufLen)
1039 {
1040 struct scsi_cmnd_io io_hdr;
1041 struct scsi_sense_disect sinfo;
1042 UINT8 cdb[10];
1043 UINT8 sense[32];
1044
1045 memset(&io_hdr, 0, sizeof(io_hdr));
1046 memset(cdb, 0, sizeof(cdb));
1047 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
1048 io_hdr.dxfer_len = bufLen;
1049 io_hdr.dxferp = pBuf;
1050 cdb[0] = READ_DEFECT_10;
1051 cdb[2] = (unsigned char)(((req_plist << 4) & 0x10) |
1052 ((req_glist << 3) & 0x8) | (dl_format & 0x7));
1053 cdb[7] = (bufLen >> 8) & 0xff;
1054 cdb[8] = bufLen & 0xff;
1055 io_hdr.cmnd = cdb;
1056 io_hdr.cmnd_len = sizeof(cdb);
1057 io_hdr.sensep = sense;
1058 io_hdr.max_sense_len = sizeof(sense);
1059 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1060
1061 if (!device->scsi_pass_through(&io_hdr))
1062 return -device->get_errno();
1063 scsi_do_sense_disect(&io_hdr, &sinfo);
1064 /* Look for "(Primary|Grown) defect list not found" */
1065 if ((sinfo.resp_code >= 0x70) && (0x1c == sinfo.asc))
1066 return 101;
1067 return scsiSimpleSenseFilter(&sinfo);
1068 }
1069
1070 /* READ DEFECT (12) command. Returns 0 if ok, 1 if NOT READY, 2 if
1071 * command not supported, 3 if field in command not supported, 101 if
1072 * defect list not found (e.g. SSD may not have defect list) or returns
1073 * negated errno. SBC-3 section 5.18 (rev 35; vale Mark Evans) */
1074 int
1075 scsiReadDefect12(scsi_device * device, int req_plist, int req_glist,
1076 int dl_format, int addrDescIndex, UINT8 *pBuf, int bufLen)
1077 {
1078 struct scsi_cmnd_io io_hdr;
1079 struct scsi_sense_disect sinfo;
1080 UINT8 cdb[12];
1081 UINT8 sense[32];
1082
1083 memset(&io_hdr, 0, sizeof(io_hdr));
1084 memset(cdb, 0, sizeof(cdb));
1085 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
1086 io_hdr.dxfer_len = bufLen;
1087 io_hdr.dxferp = pBuf;
1088 cdb[0] = READ_DEFECT_12;
1089 cdb[1] = (unsigned char)(((req_plist << 4) & 0x10) |
1090 ((req_glist << 3) & 0x8) | (dl_format & 0x7));
1091 cdb[2] = (addrDescIndex >> 24) & 0xff;
1092 cdb[3] = (addrDescIndex >> 16) & 0xff;
1093 cdb[4] = (addrDescIndex >> 8) & 0xff;
1094 cdb[5] = addrDescIndex & 0xff;
1095 cdb[6] = (bufLen >> 24) & 0xff;
1096 cdb[7] = (bufLen >> 16) & 0xff;
1097 cdb[8] = (bufLen >> 8) & 0xff;
1098 cdb[9] = bufLen & 0xff;
1099 io_hdr.cmnd = cdb;
1100 io_hdr.cmnd_len = sizeof(cdb);
1101 io_hdr.sensep = sense;
1102 io_hdr.max_sense_len = sizeof(sense);
1103 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1104
1105 if (!device->scsi_pass_through(&io_hdr))
1106 return -device->get_errno();
1107 scsi_do_sense_disect(&io_hdr, &sinfo);
1108 /* Look for "(Primary|Grown) defect list not found" */
1109 if ((sinfo.resp_code >= 0x70) && (0x1c == sinfo.asc))
1110 return 101;
1111 return scsiSimpleSenseFilter(&sinfo);
1112 }
1113
1114 /* READ CAPACITY (10) command. Returns 0 if ok, 1 if NOT READY, 2 if
1115 * command not supported, 3 if field in command not supported or returns
1116 * negated errno. SBC-3 section 5.15 (rev 26) */
1117 int
1118 scsiReadCapacity10(scsi_device * device, unsigned int * last_lbap,
1119 unsigned int * lb_sizep)
1120 {
1121 int res;
1122 struct scsi_cmnd_io io_hdr;
1123 struct scsi_sense_disect sinfo;
1124 UINT8 cdb[10];
1125 UINT8 sense[32];
1126 UINT8 resp[8];
1127
1128 memset(&io_hdr, 0, sizeof(io_hdr));
1129 memset(cdb, 0, sizeof(cdb));
1130 memset(resp, 0, sizeof(resp));
1131 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
1132 io_hdr.dxfer_len = sizeof(resp);
1133 io_hdr.dxferp = resp;
1134 cdb[0] = READ_CAPACITY_10;
1135 io_hdr.cmnd = cdb;
1136 io_hdr.cmnd_len = sizeof(cdb);
1137 io_hdr.sensep = sense;
1138 io_hdr.max_sense_len = sizeof(sense);
1139 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1140
1141 if (!device->scsi_pass_through(&io_hdr))
1142 return -device->get_errno();
1143 scsi_do_sense_disect(&io_hdr, &sinfo);
1144 res = scsiSimpleSenseFilter(&sinfo);
1145 if (res)
1146 return res;
1147 if (last_lbap)
1148 *last_lbap = (resp[0] << 24) | (resp[1] << 16) | (resp[2] << 8) |
1149 resp[3];
1150 if (lb_sizep)
1151 *lb_sizep = (resp[4] << 24) | (resp[5] << 16) | (resp[6] << 8) |
1152 resp[7];
1153 return 0;
1154 }
1155
1156 /* READ CAPACITY (16) command. The bufLen argument should be 32. Returns 0
1157 * if ok, 1 if NOT READY, 2 if command not supported, 3 if field in command
1158 * not supported or returns negated errno. SBC-3 section 5.16 (rev 26) */
1159 int
1160 scsiReadCapacity16(scsi_device * device, UINT8 *pBuf, int bufLen)
1161 {
1162 struct scsi_cmnd_io io_hdr;
1163 struct scsi_sense_disect sinfo;
1164 UINT8 cdb[16];
1165 UINT8 sense[32];
1166
1167 memset(&io_hdr, 0, sizeof(io_hdr));
1168 memset(cdb, 0, sizeof(cdb));
1169 io_hdr.dxfer_dir = DXFER_FROM_DEVICE;
1170 io_hdr.dxfer_len = bufLen;
1171 io_hdr.dxferp = pBuf;
1172 cdb[0] = READ_CAPACITY_16;
1173 cdb[1] = SAI_READ_CAPACITY_16;
1174 cdb[10] = (bufLen >> 24) & 0xff;
1175 cdb[11] = (bufLen >> 16) & 0xff;
1176 cdb[12] = (bufLen >> 8) & 0xff;
1177 cdb[13] = bufLen & 0xff;
1178 io_hdr.cmnd = cdb;
1179 io_hdr.cmnd_len = sizeof(cdb);
1180 io_hdr.sensep = sense;
1181 io_hdr.max_sense_len = sizeof(sense);
1182 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1183
1184 if (!device->scsi_pass_through(&io_hdr))
1185 return -device->get_errno();
1186 scsi_do_sense_disect(&io_hdr, &sinfo);
1187 return scsiSimpleSenseFilter(&sinfo);
1188 }
1189
1190 /* Return number of bytes of storage in 'device' or 0 if error. If
1191 * successful and lb_sizep is not NULL then the logical block size
1192 * in bytes is written to the location pointed to by lb_sizep. */
1193 uint64_t
1194 scsiGetSize(scsi_device * device, unsigned int * lb_sizep,
1195 int * lb_per_pb_expp)
1196 {
1197 unsigned int last_lba = 0, lb_size = 0;
1198 int res;
1199 uint64_t ret_val = 0;
1200 UINT8 rc16resp[32];
1201
1202 res = scsiReadCapacity10(device, &last_lba, &lb_size);
1203 if (res) {
1204 if (scsi_debugmode)
1205 pout("scsiGetSize: READ CAPACITY(10) failed, res=%d\n", res);
1206 return 0;
1207 }
1208 if (0xffffffff == last_lba) {
1209 res = scsiReadCapacity16(device, rc16resp, sizeof(rc16resp));
1210 if (res) {
1211 if (scsi_debugmode)
1212 pout("scsiGetSize: READ CAPACITY(16) failed, res=%d\n", res);
1213 return 0;
1214 }
1215 for (int k = 0; k < 8; ++k) {
1216 if (k > 0)
1217 ret_val <<= 8;
1218 ret_val |= rc16resp[k + 0];
1219 }
1220 if (lb_per_pb_expp)
1221 *lb_per_pb_expp = (rc16resp[13] & 0xf);
1222 } else {
1223 ret_val = last_lba;
1224 if (lb_per_pb_expp)
1225 *lb_per_pb_expp = 0;
1226 }
1227 if (lb_sizep)
1228 *lb_sizep = lb_size;
1229 ++ret_val; /* last_lba is origin 0 so need to bump to get number of */
1230 return ret_val * lb_size;
1231 }
1232
1233 /* Gets drive Protection and Logical/Physical block information. Writes
1234 * back bytes 12 to 31 from a READ CAPACITY 16 command to the rc16_12_31p
1235 * pointer. So rc16_12_31p should point to an array of 20 bytes. Returns 0
1236 * if ok, 1 if NOT READY, 2 if command not supported, 3 if field in command
1237 * not supported or returns negated errno. */
1238 int
1239 scsiGetProtPBInfo(scsi_device * device, unsigned char * rc16_12_31p)
1240 {
1241 int res;
1242 UINT8 rc16resp[32];
1243
1244 res = scsiReadCapacity16(device, rc16resp, sizeof(rc16resp));
1245 if (res) {
1246 if (scsi_debugmode)
1247 pout("scsiGetSize: READ CAPACITY(16) failed, res=%d\n", res);
1248 return res;
1249 }
1250 if (rc16_12_31p)
1251 memcpy(rc16_12_31p, rc16resp + 12, 20);
1252 return 0;
1253 }
1254
1255 /* Offset into mode sense (6 or 10 byte) response that actual mode page
1256 * starts at (relative to resp[0]). Returns -1 if problem */
1257 int
1258 scsiModePageOffset(const UINT8 * resp, int len, int modese_len)
1259 {
1260 int offset = -1;
1261
1262 if (resp) {
1263 int resp_len, bd_len;
1264 if (10 == modese_len) {
1265 resp_len = (resp[0] << 8) + resp[1] + 2;
1266 bd_len = (resp[6] << 8) + resp[7];
1267 offset = bd_len + 8;
1268 } else {
1269 resp_len = resp[0] + 1;
1270 bd_len = resp[3];
1271 offset = bd_len + 4;
1272 }
1273 if ((offset + 2) > len) {
1274 pout("scsiModePageOffset: raw_curr too small, offset=%d "
1275 "resp_len=%d bd_len=%d\n", offset, resp_len, bd_len);
1276 offset = -1;
1277 } else if ((offset + 2) > resp_len) {
1278 if ((resp_len > 2) || scsi_debugmode)
1279 pout("scsiModePageOffset: response length too short, "
1280 "resp_len=%d offset=%d bd_len=%d\n", resp_len,
1281 offset, bd_len);
1282 offset = -1;
1283 }
1284 }
1285 return offset;
1286 }
1287
1288 /* IEC mode page byte 2 bit masks */
1289 #define DEXCPT_ENABLE 0x08
1290 #define EWASC_ENABLE 0x10
1291 #define DEXCPT_DISABLE 0xf7
1292 #define EWASC_DISABLE 0xef
1293 #define TEST_DISABLE 0xfb
1294
1295 /* Fetches the Informational Exceptions Control mode page. First tries
1296 * the 6 byte MODE SENSE command and if that fails with an illegal opcode
1297 * tries a 10 byte MODE SENSE command. Returns 0 if successful, a positive
1298 * number if a known error (see SIMPLE_ERR_ ...) or a negative errno
1299 * value. */
1300 int
1301 scsiFetchIECmpage(scsi_device * device, struct scsi_iec_mode_page *iecp,
1302 int modese_len)
1303 {
1304 int err = 0;
1305
1306 memset(iecp, 0, sizeof(*iecp));
1307 iecp->modese_len = modese_len;
1308 iecp->requestedCurrent = 1;
1309 if (iecp->modese_len <= 6) {
1310 if ((err = scsiModeSense(device, INFORMATIONAL_EXCEPTIONS_CONTROL_PAGE,
1311 0, MPAGE_CONTROL_CURRENT,
1312 iecp->raw_curr, sizeof(iecp->raw_curr)))) {
1313 if (SIMPLE_ERR_BAD_OPCODE == err)
1314 iecp->modese_len = 10;
1315 else {
1316 iecp->modese_len = 0;
1317 return err;
1318 }
1319 } else if (0 == iecp->modese_len)
1320 iecp->modese_len = 6;
1321 }
1322 if (10 == iecp->modese_len) {
1323 err = scsiModeSense10(device, INFORMATIONAL_EXCEPTIONS_CONTROL_PAGE,
1324 0, MPAGE_CONTROL_CURRENT,
1325 iecp->raw_curr, sizeof(iecp->raw_curr));
1326 if (err) {
1327 iecp->modese_len = 0;
1328 return err;
1329 }
1330 }
1331 iecp->gotCurrent = 1;
1332 iecp->requestedChangeable = 1;
1333 if (10 == iecp->modese_len)
1334 err = scsiModeSense10(device, INFORMATIONAL_EXCEPTIONS_CONTROL_PAGE,
1335 0, MPAGE_CONTROL_CHANGEABLE,
1336 iecp->raw_chg, sizeof(iecp->raw_chg));
1337 else if (6 == iecp->modese_len)
1338 err = scsiModeSense(device, INFORMATIONAL_EXCEPTIONS_CONTROL_PAGE,
1339 0, MPAGE_CONTROL_CHANGEABLE,
1340 iecp->raw_chg, sizeof(iecp->raw_chg));
1341 if (err)
1342 return err;
1343 iecp->gotChangeable = 1;
1344 return 0;
1345 }
1346
1347 int
1348 scsi_IsExceptionControlEnabled(const struct scsi_iec_mode_page *iecp)
1349 {
1350 if (iecp && iecp->gotCurrent) {
1351 int offset = scsiModePageOffset(iecp->raw_curr, sizeof(iecp->raw_curr),
1352 iecp->modese_len);
1353 if (offset >= 0)
1354 return (iecp->raw_curr[offset + 2] & DEXCPT_ENABLE) ? 0 : 1;
1355 else
1356 return 0;
1357 } else
1358 return 0;
1359 }
1360
1361 int
1362 scsi_IsWarningEnabled(const struct scsi_iec_mode_page *iecp)
1363 {
1364 if (iecp && iecp->gotCurrent) {
1365 int offset = scsiModePageOffset(iecp->raw_curr, sizeof(iecp->raw_curr),
1366 iecp->modese_len);
1367 if (offset >= 0)
1368 return (iecp->raw_curr[offset + 2] & EWASC_ENABLE) ? 1 : 0;
1369 else
1370 return 0;
1371 } else
1372 return 0;
1373 }
1374
1375 /* set EWASC and clear PERF, EBF, DEXCPT TEST and LOGERR */
1376 #define SCSI_IEC_MP_BYTE2_ENABLED 0x10
1377 #define SCSI_IEC_MP_BYTE2_TEST_MASK 0x4
1378 /* exception/warning via an unrequested REQUEST SENSE command */
1379 #define SCSI_IEC_MP_MRIE 6
1380 #define SCSI_IEC_MP_INTERVAL_T 0
1381 #define SCSI_IEC_MP_REPORT_COUNT 1
1382
1383 /* Try to set (or clear) both Exception Control and Warning in the IE
1384 * mode page subject to the "changeable" mask. The object pointed to
1385 * by iecp is (possibly) inaccurate after this call, therefore
1386 * scsiFetchIECmpage() should be called again if the IEC mode page
1387 * is to be re-examined.
1388 * When -r ioctl is invoked 3 or more time on 'smartctl -s on ...'
1389 * then set the TEST bit (causes asc,ascq pair of 0x5d,0xff). */
1390 int
1391 scsiSetExceptionControlAndWarning(scsi_device * device, int enabled,
1392 const struct scsi_iec_mode_page *iecp)
1393 {
1394 int offset, resp_len;
1395 int err = 0;
1396 UINT8 rout[SCSI_IECMP_RAW_LEN];
1397
1398 if ((! iecp) || (! iecp->gotCurrent))
1399 return -EINVAL;
1400 offset = scsiModePageOffset(iecp->raw_curr, sizeof(iecp->raw_curr),
1401 iecp->modese_len);
1402 if (offset < 0)
1403 return -EINVAL;
1404 memcpy(rout, iecp->raw_curr, SCSI_IECMP_RAW_LEN);
1405 /* mask out DPOFUA device specific (disk) parameter bit */
1406 if (10 == iecp->modese_len) {
1407 resp_len = (rout[0] << 8) + rout[1] + 2;
1408 rout[3] &= 0xef;
1409 } else {
1410 resp_len = rout[0] + 1;
1411 rout[2] &= 0xef;
1412 }
1413 int sp = (rout[offset] & 0x80) ? 1 : 0; /* PS bit becomes 'SELECT's SP bit */
1414 if (enabled) {
1415 rout[offset + 2] = SCSI_IEC_MP_BYTE2_ENABLED;
1416 if (scsi_debugmode > 2)
1417 rout[offset + 2] |= SCSI_IEC_MP_BYTE2_TEST_MASK;
1418 rout[offset + 3] = SCSI_IEC_MP_MRIE;
1419 rout[offset + 4] = (SCSI_IEC_MP_INTERVAL_T >> 24) & 0xff;
1420 rout[offset + 5] = (SCSI_IEC_MP_INTERVAL_T >> 16) & 0xff;
1421 rout[offset + 6] = (SCSI_IEC_MP_INTERVAL_T >> 8) & 0xff;
1422 rout[offset + 7] = SCSI_IEC_MP_INTERVAL_T & 0xff;
1423 rout[offset + 8] = (SCSI_IEC_MP_REPORT_COUNT >> 24) & 0xff;
1424 rout[offset + 9] = (SCSI_IEC_MP_REPORT_COUNT >> 16) & 0xff;
1425 rout[offset + 10] = (SCSI_IEC_MP_REPORT_COUNT >> 8) & 0xff;
1426 rout[offset + 11] = SCSI_IEC_MP_REPORT_COUNT & 0xff;
1427 if (iecp->gotChangeable) {
1428 UINT8 chg2 = iecp->raw_chg[offset + 2];
1429
1430 rout[offset + 2] = chg2 ? (rout[offset + 2] & chg2) :
1431 iecp->raw_curr[offset + 2];
1432 for (int k = 3; k < 12; ++k) {
1433 if (0 == iecp->raw_chg[offset + k])
1434 rout[offset + k] = iecp->raw_curr[offset + k];
1435 }
1436 }
1437 if (0 == memcmp(&rout[offset + 2], &iecp->raw_chg[offset + 2], 10)) {
1438 if (scsi_debugmode > 0)
1439 pout("scsiSetExceptionControlAndWarning: already enabled\n");
1440 return 0;
1441 }
1442 } else { /* disabling Exception Control and (temperature) Warnings */
1443 int eCEnabled = (rout[offset + 2] & DEXCPT_ENABLE) ? 0 : 1;
1444 int wEnabled = (rout[offset + 2] & EWASC_ENABLE) ? 1 : 0;
1445 if ((! eCEnabled) && (! wEnabled)) {
1446 if (scsi_debugmode > 0)
1447 pout("scsiSetExceptionControlAndWarning: already disabled\n");
1448 return 0; /* nothing to do, leave other setting alone */
1449 }
1450 if (wEnabled)
1451 rout[offset + 2] &= EWASC_DISABLE;
1452 if (eCEnabled) {
1453 if (iecp->gotChangeable &&
1454 (iecp->raw_chg[offset + 2] & DEXCPT_ENABLE))
1455 rout[offset + 2] |= DEXCPT_ENABLE;
1456 rout[offset + 2] &= TEST_DISABLE; /* clear TEST bit for spec */
1457 }
1458 }
1459 if (10 == iecp->modese_len)
1460 err = scsiModeSelect10(device, sp, rout, resp_len);
1461 else if (6 == iecp->modese_len)
1462 err = scsiModeSelect(device, sp, rout, resp_len);
1463 return err;
1464 }
1465
1466 int
1467 scsiGetTemp(scsi_device * device, UINT8 *currenttemp, UINT8 *triptemp)
1468 {
1469 UINT8 tBuf[252];
1470 int err;
1471
1472 memset(tBuf, 0, sizeof(tBuf));
1473 if ((err = scsiLogSense(device, TEMPERATURE_LPAGE, 0, tBuf,
1474 sizeof(tBuf), 0))) {
1475 *currenttemp = 0;
1476 *triptemp = 0;
1477 pout("Log Sense for temperature failed [%s]\n", scsiErrString(err));
1478 return err;
1479 }
1480 *currenttemp = tBuf[9];
1481 *triptemp = tBuf[15];
1482 return 0;
1483 }
1484
1485 /* Read informational exception log page or Request Sense response.
1486 * Fetching asc/ascq code potentially flagging an exception or warning.
1487 * Returns 0 if ok, else error number. A current temperature of 255
1488 * (Celsius) implies that the temperature not available. */
1489 int
1490 scsiCheckIE(scsi_device * device, int hasIELogPage, int hasTempLogPage,
1491 UINT8 *asc, UINT8 *ascq, UINT8 *currenttemp, UINT8 *triptemp)
1492 {
1493 UINT8 tBuf[252];
1494 struct scsi_sense_disect sense_info;
1495 int err;
1496 UINT8 currTemp, trTemp;
1497
1498 *asc = 0;
1499 *ascq = 0;
1500 *currenttemp = 0;
1501 *triptemp = 0;
1502 memset(tBuf,0,sizeof(tBuf)); // need to clear stack space of junk
1503 memset(&sense_info, 0, sizeof(sense_info));
1504 if (hasIELogPage) {
1505 if ((err = scsiLogSense(device, IE_LPAGE, 0, tBuf,
1506 sizeof(tBuf), 0))) {
1507 pout("Log Sense failed, IE page [%s]\n", scsiErrString(err));
1508 return err;
1509 }
1510 // pull out page size from response, don't forget to add 4
1511 unsigned short pagesize = (unsigned short) ((tBuf[2] << 8) | tBuf[3]) + 4;
1512 if ((pagesize < 4) || tBuf[4] || tBuf[5]) {
1513 pout("Log Sense failed, IE page, bad parameter code or length\n");
1514 return SIMPLE_ERR_BAD_PARAM;
1515 }
1516 if (tBuf[7] > 1) {
1517 sense_info.asc = tBuf[8];
1518 sense_info.ascq = tBuf[9];
1519 if (! hasTempLogPage) {
1520 if (tBuf[7] > 2)
1521 *currenttemp = tBuf[10];
1522 if (tBuf[7] > 3) /* IBM extension in SMART (IE) lpage */
1523 *triptemp = tBuf[11];
1524 }
1525 }
1526 }
1527 if (0 == sense_info.asc) {
1528 /* ties in with MRIE field of 6 in IEC mode page (0x1c) */
1529 if ((err = scsiRequestSense(device, &sense_info))) {
1530 pout("Request Sense failed, [%s]\n", scsiErrString(err));
1531 return err;
1532 }
1533 }
1534 *asc = sense_info.asc;
1535 *ascq = sense_info.ascq;
1536 if (hasTempLogPage) {
1537 if (0 == scsiGetTemp(device, &currTemp, &trTemp)) {
1538 *currenttemp = currTemp;
1539 *triptemp = trTemp;
1540 }
1541 }
1542 return 0;
1543 }
1544
1545 // The first character (W, C, I) tells the severity
1546 static const char * TapeAlertsMessageTable[]= {
1547 " ",
1548 /* 0x01 */
1549 "W: The tape drive is having problems reading data. No data has been lost,\n"
1550 " but there has been a reduction in the performance of the tape.",
1551 /* 0x02 */
1552 "W: The tape drive is having problems writing data. No data has been lost,\n"
1553 " but there has been a reduction in the capacity of the tape.",
1554 /* 0x03 */
1555 "W: The operation has stopped because an error has occurred while reading\n"
1556 " or writing data that the drive cannot correct.",
1557 /* 0x04 */
1558 "C: Your data is at risk:\n"
1559 " 1. Copy any data you require from this tape. \n"
1560 " 2. Do not use this tape again.\n"
1561 " 3. Restart the operation with a different tape.",
1562 /* 0x05 */
1563 "C: The tape is damaged or the drive is faulty. Call the tape drive\n"
1564 " supplier helpline.",
1565 /* 0x06 */
1566 "C: The tape is from a faulty batch or the tape drive is faulty:\n"
1567 " 1. Use a good tape to test the drive.\n"
1568 " 2. If problem persists, call the tape drive supplier helpline.",
1569 /* 0x07 */
1570 "W: The tape cartridge has reached the end of its calculated useful life:\n"
1571 " 1. Copy data you need to another tape.\n"
1572 " 2. Discard the old tape.",
1573 /* 0x08 */
1574 "W: The tape cartridge is not data-grade. Any data you back up to the tape\n"
1575 " is at risk. Replace the cartridge with a data-grade tape.",
1576 /* 0x09 */
1577 "C: You are trying to write to a write-protected cartridge. Remove the\n"
1578 " write-protection or use another tape.",
1579 /* 0x0a */
1580 "I: You cannot eject the cartridge because the tape drive is in use. Wait\n"
1581 " until the operation is complete before ejecting the cartridge.",
1582 /* 0x0b */
1583 "I: The tape in the drive is a cleaning cartridge.",
1584 /* 0x0c */
1585 "I: You have tried to load a cartridge of a type which is not supported\n"
1586 " by this drive.",
1587 /* 0x0d */
1588 "C: The operation has failed because the tape in the drive has experienced\n"
1589 " a mechanical failure:\n"
1590 " 1. Discard the old tape.\n"
1591 " 2. Restart the operation with a different tape.",
1592 /* 0x0e */
1593 "C: The operation has failed because the tape in the drive has experienced\n"
1594 " a mechanical failure:\n"
1595 " 1. Do not attempt to extract the tape cartridge\n"
1596 " 2. Call the tape drive supplier helpline.",
1597 /* 0x0f */
1598 "W: The memory in the tape cartridge has failed, which reduces\n"
1599 " performance. Do not use the cartridge for further write operations.",
1600 /* 0x10 */
1601 "C: The operation has failed because the tape cartridge was manually\n"
1602 " de-mounted while the tape drive was actively writing or reading.",
1603 /* 0x11 */
1604 "W: You have loaded a cartridge of a type that is read-only in this drive.\n"
1605 " The cartridge will appear as write-protected.",
1606 /* 0x12 */
1607 "W: The tape directory on the tape cartridge has been corrupted. File\n"
1608 " search performance will be degraded. The tape directory can be rebuilt\n"
1609 " by reading all the data on the cartridge.",
1610 /* 0x13 */
1611 "I: The tape cartridge is nearing the end of its calculated life. It is\n"
1612 " recommended that you:\n"
1613 " 1. Use another tape cartridge for your next backup.\n"
1614 " 2. Store this tape in a safe place in case you need to restore "
1615 " data from it.",
1616 /* 0x14 */
1617 "C: The tape drive needs cleaning:\n"
1618 " 1. If the operation has stopped, eject the tape and clean the drive.\n"
1619 " 2. If the operation has not stopped, wait for it to finish and then\n"
1620 " clean the drive.\n"
1621 " Check the tape drive users manual for device specific cleaning instructions.",
1622 /* 0x15 */
1623 "W: The tape drive is due for routine cleaning:\n"
1624 " 1. Wait for the current operation to finish.\n"
1625 " 2. The use a cleaning cartridge.\n"
1626 " Check the tape drive users manual for device specific cleaning instructions.",
1627 /* 0x16 */
1628 "C: The last cleaning cartridge used in the tape drive has worn out:\n"
1629 " 1. Discard the worn out cleaning cartridge.\n"
1630 " 2. Wait for the current operation to finish.\n"
1631 " 3. Then use a new cleaning cartridge.",
1632 /* 0x17 */
1633 "C: The last cleaning cartridge used in the tape drive was an invalid\n"
1634 " type:\n"
1635 " 1. Do not use this cleaning cartridge in this drive.\n"
1636 " 2. Wait for the current operation to finish.\n"
1637 " 3. Then use a new cleaning cartridge.",
1638 /* 0x18 */
1639 "W: The tape drive has requested a retention operation",
1640 /* 0x19 */
1641 "W: A redundant interface port on the tape drive has failed",
1642 /* 0x1a */
1643 "W: A tape drive cooling fan has failed",
1644 /* 0x1b */
1645 "W: A redundant power supply has failed inside the tape drive enclosure.\n"
1646 " Check the enclosure users manual for instructions on replacing the\n"
1647 " failed power supply.",
1648 /* 0x1c */
1649 "W: The tape drive power consumption is outside the specified range.",
1650 /* 0x1d */
1651 "W: Preventive maintenance of the tape drive is required. Check the tape\n"
1652 " drive users manual for device specific preventive maintenance\n"
1653 " tasks or call the tape drive supplier helpline.",
1654 /* 0x1e */
1655 "C: The tape drive has a hardware fault:\n"
1656 " 1. Eject the tape or magazine.\n"
1657 " 2. Reset the drive.\n"
1658 " 3. Restart the operation.",
1659 /* 0x1f */
1660 "C: The tape drive has a hardware fault:\n"
1661 " 1. Turn the tape drive off and then on again.\n"
1662 " 2. Restart the operation.\n"
1663 " 3. If the problem persists, call the tape drive supplier helpline.",
1664 /* 0x20 */
1665 "W: The tape drive has a problem with the application client interface:\n"
1666 " 1. Check the cables and cable connections.\n"
1667 " 2. Restart the operation.",
1668 /* 0x21 */
1669 "C: The operation has failed:\n"
1670 " 1. Eject the tape or magazine.\n"
1671 " 2. Insert the tape or magazine again.\n"
1672 " 3. Restart the operation.",
1673 /* 0x22 */
1674 "W: The firmware download has failed because you have tried to use the\n"
1675 " incorrect firmware for this tape drive. Obtain the correct\n"
1676 " firmware and try again.",
1677 /* 0x23 */
1678 "W: Environmental conditions inside the tape drive are outside the\n"
1679 " specified humidity range.",
1680 /* 0x24 */
1681 "W: Environmental conditions inside the tape drive are outside the\n"
1682 " specified temperature range.",
1683 /* 0x25 */
1684 "W: The voltage supply to the tape drive is outside the specified range.",
1685 /* 0x26 */
1686 "C: A hardware failure of the tape drive is predicted. Call the tape\n"
1687 " drive supplier helpline.",
1688 /* 0x27 */
1689 "W: The tape drive may have a hardware fault. Run extended diagnostics to\n"
1690 " verify and diagnose the problem. Check the tape drive users manual for\n"
1691 " device specific instructions on running extended diagnostic tests.",
1692 /* 0x28 */
1693 "C: The changer mechanism is having difficulty communicating with the tape\n"
1694 " drive:\n"
1695 " 1. Turn the autoloader off then on.\n"
1696 " 2. Restart the operation.\n"
1697 " 3. If problem persists, call the tape drive supplier helpline.",
1698 /* 0x29 */
1699 "C: A tape has been left in the autoloader by a previous hardware fault:\n"
1700 " 1. Insert an empty magazine to clear the fault.\n"
1701 " 2. If the fault does not clear, turn the autoloader off and then\n"
1702 " on again.\n"
1703 " 3. If the problem persists, call the tape drive supplier helpline.",
1704 /* 0x2a */
1705 "W: There is a problem with the autoloader mechanism.",
1706 /* 0x2b */
1707 "C: The operation has failed because the autoloader door is open:\n"
1708 " 1. Clear any obstructions from the autoloader door.\n"
1709 " 2. Eject the magazine and then insert it again.\n"
1710 " 3. If the fault does not clear, turn the autoloader off and then\n"
1711 " on again.\n"
1712 " 4. If the problem persists, call the tape drive supplier helpline.",
1713 /* 0x2c */
1714 "C: The autoloader has a hardware fault:\n"
1715 " 1. Turn the autoloader off and then on again.\n"
1716 " 2. Restart the operation.\n"
1717 " 3. If the problem persists, call the tape drive supplier helpline.\n"
1718 " Check the autoloader users manual for device specific instructions\n"
1719 " on turning the device power on and off.",
1720 /* 0x2d */
1721 "C: The autoloader cannot operate without the magazine,\n"
1722 " 1. Insert the magazine into the autoloader.\n"
1723 " 2. Restart the operation.",
1724 /* 0x2e */
1725 "W: A hardware failure of the changer mechanism is predicted. Call the\n"
1726 " tape drive supplier helpline.",
1727 /* 0x2f */
1728 "I: Reserved.",
1729 /* 0x30 */
1730 "I: Reserved.",
1731 /* 0x31 */
1732 "I: Reserved.",
1733 /* 0x32 */
1734 "W: Media statistics have been lost at some time in the past",
1735 /* 0x33 */
1736 "W: The tape directory on the tape cartridge just unloaded has been\n"
1737 " corrupted. File search performance will be degraded. The tape\n"
1738 " directory can be rebuilt by reading all the data.",
1739 /* 0x34 */
1740 "C: The tape just unloaded could not write its system area successfully:\n"
1741 " 1. Copy data to another tape cartridge.\n"
1742 " 2. Discard the old cartridge.",
1743 /* 0x35 */
1744 "C: The tape system are could not be read successfully at load time:\n"
1745 " 1. Copy data to another tape cartridge.\n",
1746 /* 0x36 */
1747 "C: The start or data could not be found on the tape:\n"
1748 " 1. Check you are using the correct format tape.\n"
1749 " 2. Discard the tape or return the tape to your supplier",
1750 /* 0x37 */
1751 "C: The operation has failed because the media cannot be loaded\n"
1752 " and threaded.\n"
1753 " 1. Remove the cartridge, inspect it as specified in the product\n"
1754 " manual, and retry the operation.\n"
1755 " 2. If the problem persists, call the tape drive supplier help line.",
1756 /* 0x38 */
1757 "C: The operation has failed because the medium cannot be unloaded:\n"
1758 " 1. Do not attempt to extract the tape cartridge.\n"
1759 " 2. Call the tape driver supplier help line.",
1760 /* 0x39 */
1761 "C: The tape drive has a problem with the automation interface:\n"
1762 " 1. Check the power to the automation system.\n"
1763 " 2. Check the cables and cable connections.\n"
1764 " 3. Call the supplier help line if problem persists.",
1765 /* 0x3a */
1766 "W: The tape drive has reset itself due to a detected firmware\n"
1767 " fault. If problem persists, call the supplier help line.",
1768 };
1769
1770 const char *
1771 scsiTapeAlertsTapeDevice(unsigned short code)
1772 {
1773 const int num = sizeof(TapeAlertsMessageTable) /
1774 sizeof(TapeAlertsMessageTable[0]);
1775
1776 return (code < num) ? TapeAlertsMessageTable[code] : "Unknown Alert";
1777 }
1778
1779 // The first character (W, C, I) tells the severity
1780 static const char * ChangerTapeAlertsMessageTable[]= {
1781 " ",
1782 /* 0x01 */
1783 "C: The library mechanism is having difficulty communicating with the\n"
1784 " drive:\n"
1785 " 1. Turn the library off then on.\n"
1786 " 2. Restart the operation.\n"
1787 " 3. If the problem persists, call the library supplier help line.",
1788 /* 0x02 */
1789 "W: There is a problem with the library mechanism. If problem persists,\n"
1790 " call the library supplier help line.",
1791 /* 0x03 */
1792 "C: The library has a hardware fault:\n"
1793 " 1. Reset the library.\n"
1794 " 2. Restart the operation.\n"
1795 " Check the library users manual for device specific instructions on resetting\n"
1796 " the device.",
1797 /* 0x04 */
1798 "C: The library has a hardware fault:\n"
1799 " 1. Turn the library off then on again.\n"
1800 " 2. Restart the operation.\n"
1801 " 3. If the problem persists, call the library supplier help line.\n"
1802 " Check the library users manual for device specific instructions on turning the\n"
1803 " device power on and off.",
1804 /* 0x05 */
1805 "W: The library mechanism may have a hardware fault.\n"
1806 " Run extended diagnostics to verify and diagnose the problem. Check the library\n"
1807 " users manual for device specific instructions on running extended diagnostic\n"
1808 " tests.",
1809 /* 0x06 */
1810 "C: The library has a problem with the host interface:\n"
1811 " 1. Check the cables and connections.\n"
1812 " 2. Restart the operation.",
1813 /* 0x07 */
1814 "W: A hardware failure of the library is predicted. Call the library\n"
1815 " supplier help line.",
1816 /* 0x08 */
1817 "W: Preventive maintenance of the library is required.\n"
1818 " Check the library users manual for device specific preventative maintenance\n"
1819 " tasks, or call your library supplier help line.",
1820 /* 0x09 */
1821 "C: General environmental conditions inside the library are outside the\n"
1822 " specified humidity range.",
1823 /* 0x0a */
1824 "C: General environmental conditions inside the library are outside the\n"
1825 " specified temperature range.",
1826 /* 0x0b */
1827 "C: The voltage supply to the library is outside the specified range.\n"
1828 " There is a potential problem with the power supply or failure of\n"
1829 " a redundant power supply.",
1830 /* 0x0c */
1831 "C: A cartridge has been left inside the library by a previous hardware\n"
1832 " fault:\n"
1833 " 1. Insert an empty magazine to clear the fault.\n"
1834 " 2. If the fault does not clear, turn the library off and then on again.\n"
1835 " 3. If the problem persists, call the library supplier help line.",
1836 /* 0x0d */
1837 "W: There is a potential problem with the drive ejecting cartridges or\n"
1838 " with the library mechanism picking a cartridge from a slot.\n"
1839 " 1. No action needs to be taken at this time.\n"
1840 " 2. If the problem persists, call the library supplier help line.",
1841 /* 0x0e */
1842 "W: There is a potential problem with the library mechanism placing a\n"
1843 " cartridge into a slot.\n"
1844 " 1. No action needs to be taken at this time.\n"
1845 " 2. If the problem persists, call the library supplier help line.",
1846 /* 0x0f */
1847 "W: There is a potential problem with the drive or the library mechanism\n"
1848 " loading cartridges, or an incompatible cartridge.",
1849 /* 0x10 */
1850 "C: The library has failed because the door is open:\n"
1851 " 1. Clear any obstructions from the library door.\n"
1852 " 2. Close the library door.\n"
1853 " 3. If the problem persists, call the library supplier help line.",
1854 /* 0x11 */
1855 "C: There is a mechanical problem with the library media import/export\n"
1856 " mailslot.",
1857 /* 0x12 */
1858 "C: The library cannot operate without the magazine.\n"
1859 " 1. Insert the magazine into the library.\n"
1860 " 2. Restart the operation.",
1861 /* 0x13 */
1862 "W: Library security has been compromised.",
1863 /* 0x14 */
1864 "I: The library security mode has been changed.\n"
1865 " The library has either been put into secure mode, or the library has exited\n"
1866 " the secure mode.\n"
1867 " This is for information purposes only. No action is required.",
1868 /* 0x15 */
1869 "I: The library has been manually turned offline and is unavailable for use.",
1870 /* 0x16 */
1871 "I: A drive inside the library has been taken offline.\n"
1872 " This is for information purposes only. No action is required.",
1873 /* 0x17 */
1874 "W: There is a potential problem with the bar code label or the scanner\n"
1875 " hardware in the library mechanism.\n"
1876 " 1. No action needs to be taken at this time.\n"
1877 " 2. If the problem persists, call the library supplier help line.",
1878 /* 0x18 */
1879 "C: The library has detected an inconsistency in its inventory.\n"
1880 " 1. Redo the library inventory to correct inconsistency.\n"
1881 " 2. Restart the operation.\n"
1882 " Check the applications users manual or the hardware users manual for\n"
1883 " specific instructions on redoing the library inventory.",
1884 /* 0x19 */
1885 "W: A library operation has been attempted that is invalid at this time.",
1886 /* 0x1a */
1887 "W: A redundant interface port on the library has failed.",
1888 /* 0x1b */
1889 "W: A library cooling fan has failed.",
1890 /* 0x1c */
1891 "W: A redundant power supply has failed inside the library. Check the\n"
1892 " library users manual for instructions on replacing the failed power supply.",
1893 /* 0x1d */
1894 "W: The library power consumption is outside the specified range.",
1895 /* 0x1e */
1896 "C: A failure has occurred in the cartridge pass-through mechanism between\n"
1897 " two library modules.",
1898 /* 0x1f */
1899 "C: A cartridge has been left in the pass-through mechanism from a\n"
1900 " previous hardware fault. Check the library users guide for instructions on\n"
1901 " clearing this fault.",
1902 /* 0x20 */
1903 "I: The library was unable to read the bar code on a cartridge.",
1904 };
1905
1906 const char *
1907 scsiTapeAlertsChangerDevice(unsigned short code)
1908 {
1909 const int num = sizeof(ChangerTapeAlertsMessageTable) /
1910 sizeof(ChangerTapeAlertsMessageTable[0]);
1911
1912 return (code < num) ? ChangerTapeAlertsMessageTable[code] : "Unknown Alert";
1913 }
1914
1915
1916 /* this is a subset of the SCSI additional sense code strings indexed
1917 * by "ascq" for the case when asc==SCSI_ASC_IMPENDING_FAILURE (0x5d)
1918 */
1919 static const char * strs_for_asc_5d[] = {
1920 /* 0x00 */ "FAILURE PREDICTION THRESHOLD EXCEEDED",
1921 "MEDIA FAILURE PREDICTION THRESHOLD EXCEEDED",
1922 "LOGICAL UNIT FAILURE PREDICTION THRESHOLD EXCEEDED",
1923 "SPARE AREA EXHAUSTION PREDICTION THRESHOLD EXCEEDED",
1924 "",
1925 "",
1926 "",
1927 "",
1928 "",
1929 "",
1930 "",
1931 "",
1932 "",
1933 "",
1934 "",
1935 "",
1936 /* 0x10 */ "HARDWARE IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
1937 "HARDWARE IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
1938 "HARDWARE IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
1939 "HARDWARE IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
1940 "HARDWARE IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
1941 "HARDWARE IMPENDING FAILURE ACCESS TIMES TOO HIGH",
1942 "HARDWARE IMPENDING FAILURE START UNIT TIMES TOO HIGH",
1943 "HARDWARE IMPENDING FAILURE CHANNEL PARAMETRICS",
1944 "HARDWARE IMPENDING FAILURE CONTROLLER DETECTED",
1945 "HARDWARE IMPENDING FAILURE THROUGHPUT PERFORMANCE",
1946 "HARDWARE IMPENDING FAILURE SEEK TIME PERFORMANCE",
1947 "HARDWARE IMPENDING FAILURE SPIN-UP RETRY COUNT",
1948 "HARDWARE IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT",
1949 "",
1950 "",
1951 "",
1952 /* 0x20 */ "CONTROLLER IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
1953 "CONTROLLER IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
1954 "CONTROLLER IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
1955 "CONTROLLER IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
1956 "CONTROLLER IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
1957 "CONTROLLER IMPENDING FAILURE ACCESS TIMES TOO HIGH",
1958 "CONTROLLER IMPENDING FAILURE START UNIT TIMES TOO HIGH",
1959 "CONTROLLER IMPENDING FAILURE CHANNEL PARAMETRICS",
1960 "CONTROLLER IMPENDING FAILURE CONTROLLER DETECTED",
1961 "CONTROLLER IMPENDING FAILURE THROUGHPUT PERFORMANCE",
1962 "CONTROLLER IMPENDING FAILURE SEEK TIME PERFORMANCE",
1963 "CONTROLLER IMPENDING FAILURE SPIN-UP RETRY COUNT",
1964 "CONTROLLER IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT",
1965 "",
1966 "",
1967 "",
1968 /* 0x30 */ "DATA CHANNEL IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
1969 "DATA CHANNEL IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
1970 "DATA CHANNEL IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
1971 "DATA CHANNEL IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
1972 "DATA CHANNEL IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
1973 "DATA CHANNEL IMPENDING FAILURE ACCESS TIMES TOO HIGH",
1974 "DATA CHANNEL IMPENDING FAILURE START UNIT TIMES TOO HIGH",
1975 "DATA CHANNEL IMPENDING FAILURE CHANNEL PARAMETRICS",
1976 "DATA CHANNEL IMPENDING FAILURE CONTROLLER DETECTED",
1977 "DATA CHANNEL IMPENDING FAILURE THROUGHPUT PERFORMANCE",
1978 "DATA CHANNEL IMPENDING FAILURE SEEK TIME PERFORMANCE",
1979 "DATA CHANNEL IMPENDING FAILURE SPIN-UP RETRY COUNT",
1980 "DATA CHANNEL IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT",
1981 "",
1982 "",
1983 "",
1984 /* 0x40 */ "SERVO IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
1985 "SERVO IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
1986 "SERVO IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
1987 "SERVO IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
1988 "SERVO IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
1989 "SERVO IMPENDING FAILURE ACCESS TIMES TOO HIGH",
1990 "SERVO IMPENDING FAILURE START UNIT TIMES TOO HIGH",
1991 "SERVO IMPENDING FAILURE CHANNEL PARAMETRICS",
1992 "SERVO IMPENDING FAILURE CONTROLLER DETECTED",
1993 "SERVO IMPENDING FAILURE THROUGHPUT PERFORMANCE",
1994 "SERVO IMPENDING FAILURE SEEK TIME PERFORMANCE",
1995 "SERVO IMPENDING FAILURE SPIN-UP RETRY COUNT",
1996 "SERVO IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT",
1997 "",
1998 "",
1999 "",
2000 /* 0x50 */ "SPINDLE IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
2001 "SPINDLE IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
2002 "SPINDLE IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
2003 "SPINDLE IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
2004 "SPINDLE IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
2005 "SPINDLE IMPENDING FAILURE ACCESS TIMES TOO HIGH",
2006 "SPINDLE IMPENDING FAILURE START UNIT TIMES TOO HIGH",
2007 "SPINDLE IMPENDING FAILURE CHANNEL PARAMETRICS",
2008 "SPINDLE IMPENDING FAILURE CONTROLLER DETECTED",
2009 "SPINDLE IMPENDING FAILURE THROUGHPUT PERFORMANCE",
2010 "SPINDLE IMPENDING FAILURE SEEK TIME PERFORMANCE",
2011 "SPINDLE IMPENDING FAILURE SPIN-UP RETRY COUNT",
2012 "SPINDLE IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT",
2013 "",
2014 "",
2015 "",
2016 /* 0x60 */ "FIRMWARE IMPENDING FAILURE GENERAL HARD DRIVE FAILURE",
2017 "FIRMWARE IMPENDING FAILURE DRIVE ERROR RATE TOO HIGH",
2018 "FIRMWARE IMPENDING FAILURE DATA ERROR RATE TOO HIGH",
2019 "FIRMWARE IMPENDING FAILURE SEEK ERROR RATE TOO HIGH",
2020 "FIRMWARE IMPENDING FAILURE TOO MANY BLOCK REASSIGNS",
2021 "FIRMWARE IMPENDING FAILURE ACCESS TIMES TOO HIGH",
2022 "FIRMWARE IMPENDING FAILURE START UNIT TIMES TOO HIGH",
2023 "FIRMWARE IMPENDING FAILURE CHANNEL PARAMETRICS",
2024 "FIRMWARE IMPENDING FAILURE CONTROLLER DETECTED",
2025 "FIRMWARE IMPENDING FAILURE THROUGHPUT PERFORMANCE",
2026 "FIRMWARE IMPENDING FAILURE SEEK TIME PERFORMANCE",
2027 "FIRMWARE IMPENDING FAILURE SPIN-UP RETRY COUNT",
2028 /* 0x6c */ "FIRMWARE IMPENDING FAILURE DRIVE CALIBRATION RETRY COUNT"};
2029
2030
2031 /* this is a subset of the SCSI additional sense code strings indexed
2032 * * by "ascq" for the case when asc==SCSI_ASC_WARNING (0xb)
2033 * */
2034 static const char * strs_for_asc_b[] = {
2035 /* 0x00 */ "WARNING",
2036 "WARNING - SPECIFIED TEMPERATURE EXCEEDED",
2037 "WARNING - ENCLOSURE DEGRADED"};
2038
2039 static char spare_buff[128];
2040
2041 const char *
2042 scsiGetIEString(UINT8 asc, UINT8 ascq)
2043 {
2044 const char * rp;
2045
2046 if (SCSI_ASC_IMPENDING_FAILURE == asc) {
2047 if (ascq == 0xff)
2048 return "FAILURE PREDICTION THRESHOLD EXCEEDED (FALSE)";
2049 else if (ascq <
2050 (sizeof(strs_for_asc_5d) / sizeof(strs_for_asc_5d[0]))) {
2051 rp = strs_for_asc_5d[ascq];
2052 if (strlen(rp) > 0)
2053 return rp;
2054 }
2055 snprintf(spare_buff, sizeof(spare_buff),
2056 "FAILURE PREDICTION THRESHOLD EXCEEDED: ascq=0x%x", ascq);
2057 return spare_buff;
2058 } else if (SCSI_ASC_WARNING == asc) {
2059 if (ascq < (sizeof(strs_for_asc_b) / sizeof(strs_for_asc_b[0]))) {
2060 rp = strs_for_asc_b[ascq];
2061 if (strlen(rp) > 0)
2062 return rp;
2063 }
2064 snprintf(spare_buff, sizeof(spare_buff), "WARNING: ascq=0x%x", ascq);
2065 return spare_buff;
2066 }
2067 return NULL; /* not a IE additional sense code */
2068 }
2069
2070
2071 int
2072 scsiSmartDefaultSelfTest(scsi_device * device)
2073 {
2074 int res;
2075
2076 res = scsiSendDiagnostic(device, SCSI_DIAG_DEF_SELF_TEST, NULL, 0);
2077 if (res)
2078 pout("Default self test failed [%s]\n", scsiErrString(res));
2079 return res;
2080 }
2081
2082 int
2083 scsiSmartShortSelfTest(scsi_device * device)
2084 {
2085 int res;
2086
2087 res = scsiSendDiagnostic(device, SCSI_DIAG_BG_SHORT_SELF_TEST, NULL, 0);
2088 if (res)
2089 pout("Short offline self test failed [%s]\n", scsiErrString(res));
2090 return res;
2091 }
2092
2093 int
2094 scsiSmartExtendSelfTest(scsi_device * device)
2095 {
2096 int res;
2097
2098 res = scsiSendDiagnostic(device, SCSI_DIAG_BG_EXTENDED_SELF_TEST, NULL, 0);
2099 if (res)
2100 pout("Long (extended) offline self test failed [%s]\n",
2101 scsiErrString(res));
2102 return res;
2103 }
2104
2105 int
2106 scsiSmartShortCapSelfTest(scsi_device * device)
2107 {
2108 int res;
2109
2110 res = scsiSendDiagnostic(device, SCSI_DIAG_FG_SHORT_SELF_TEST, NULL, 0);
2111 if (res)
2112 pout("Short foreground self test failed [%s]\n", scsiErrString(res));
2113 return res;
2114 }
2115
2116 int
2117 scsiSmartExtendCapSelfTest(scsi_device * device)
2118 {
2119 int res;
2120
2121 res = scsiSendDiagnostic(device, SCSI_DIAG_FG_EXTENDED_SELF_TEST, NULL, 0);
2122 if (res)
2123 pout("Long (extended) foreground self test failed [%s]\n",
2124 scsiErrString(res));
2125 return res;
2126 }
2127
2128 int
2129 scsiSmartSelfTestAbort(scsi_device * device)
2130 {
2131 int res;
2132
2133 res = scsiSendDiagnostic(device, SCSI_DIAG_ABORT_SELF_TEST, NULL, 0);
2134 if (res)
2135 pout("Abort self test failed [%s]\n", scsiErrString(res));
2136 return res;
2137 }
2138
2139 /* Returns 0 and the expected duration of an extended self test (in seconds)
2140 if successful; any other return value indicates a failure. */
2141 int
2142 scsiFetchExtendedSelfTestTime(scsi_device * device, int * durationSec,
2143 int modese_len)
2144 {
2145 int err, offset;
2146 UINT8 buff[64];
2147
2148 memset(buff, 0, sizeof(buff));
2149 if (modese_len <= 6) {
2150 if ((err = scsiModeSense(device, CONTROL_MODE_PAGE, 0,
2151 MPAGE_CONTROL_CURRENT,
2152 buff, sizeof(buff)))) {
2153 if (SIMPLE_ERR_BAD_OPCODE == err)
2154 modese_len = 10;
2155 else
2156 return err;
2157 } else if (0 == modese_len)
2158 modese_len = 6;
2159 }
2160 if (10 == modese_len) {
2161 err = scsiModeSense10(device, CONTROL_MODE_PAGE, 0,
2162 MPAGE_CONTROL_CURRENT,
2163 buff, sizeof(buff));
2164 if (err)
2165 return err;
2166 }
2167 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2168 if (offset < 0)
2169 return -EINVAL;
2170 if (buff[offset + 1] >= 0xa) {
2171 int res = (buff[offset + 10] << 8) | buff[offset + 11];
2172 *durationSec = res;
2173 return 0;
2174 }
2175 else
2176 return -EINVAL;
2177 }
2178
2179 void
2180 scsiDecodeErrCounterPage(unsigned char * resp, struct scsiErrorCounter *ecp)
2181 {
2182 memset(ecp, 0, sizeof(*ecp));
2183 int num = (resp[2] << 8) | resp[3];
2184 unsigned char * ucp = &resp[0] + 4;
2185 while (num > 3) {
2186 int pc = (ucp[0] << 8) | ucp[1];
2187 int pl = ucp[3] + 4;
2188 uint64_t * ullp;
2189 switch (pc) {
2190 case 0:
2191 case 1:
2192 case 2:
2193 case 3:
2194 case 4:
2195 case 5:
2196 case 6:
2197 ecp->gotPC[pc] = 1;
2198 ullp = &ecp->counter[pc];
2199 break;
2200 default:
2201 ecp->gotExtraPC = 1;
2202 ullp = &ecp->counter[7];
2203 break;
2204 }
2205 int k = pl - 4;
2206 unsigned char * xp = ucp + 4;
2207 if (k > (int)sizeof(*ullp)) {
2208 xp += (k - sizeof(*ullp));
2209 k = sizeof(*ullp);
2210 }
2211 *ullp = 0;
2212 for (int j = 0; j < k; ++j) {
2213 if (j > 0)
2214 *ullp <<= 8;
2215 *ullp |= xp[j];
2216 }
2217 num -= pl;
2218 ucp += pl;
2219 }
2220 }
2221
2222 void
2223 scsiDecodeNonMediumErrPage(unsigned char *resp,
2224 struct scsiNonMediumError *nmep)
2225 {
2226 memset(nmep, 0, sizeof(*nmep));
2227 int num = (resp[2] << 8) | resp[3];
2228 unsigned char * ucp = &resp[0] + 4;
2229 int szof = sizeof(nmep->counterPC0);
2230 while (num > 3) {
2231 int pc = (ucp[0] << 8) | ucp[1];
2232 int pl = ucp[3] + 4;
2233 int k;
2234 unsigned char * xp;
2235 switch (pc) {
2236 case 0:
2237 nmep->gotPC0 = 1;
2238 k = pl - 4;
2239 xp = ucp + 4;
2240 if (k > szof) {
2241 xp += (k - szof);
2242 k = szof;
2243 }
2244 nmep->counterPC0 = 0;
2245 for (int j = 0; j < k; ++j) {
2246 if (j > 0)
2247 nmep->counterPC0 <<= 8;
2248 nmep->counterPC0 |= xp[j];
2249 }
2250 break;
2251 case 0x8009:
2252 nmep->gotTFE_H = 1;
2253 k = pl - 4;
2254 xp = ucp + 4;
2255 if (k > szof) {
2256 xp += (k - szof);
2257 k = szof;
2258 }
2259 nmep->counterTFE_H = 0;
2260 for (int j = 0; j < k; ++j) {
2261 if (j > 0)
2262 nmep->counterTFE_H <<= 8;
2263 nmep->counterTFE_H |= xp[j];
2264 }
2265 break;
2266 case 0x8015:
2267 nmep->gotPE_H = 1;
2268 k = pl - 4;
2269 xp = ucp + 4;
2270 if (k > szof) {
2271 xp += (k - szof);
2272 k = szof;
2273 }
2274 nmep->counterPE_H = 0;
2275 for (int j = 0; j < k; ++j) {
2276 if (j > 0)
2277 nmep->counterPE_H <<= 8;
2278 nmep->counterPE_H |= xp[j];
2279 }
2280 break;
2281 default:
2282 nmep->gotExtraPC = 1;
2283 break;
2284 }
2285 num -= pl;
2286 ucp += pl;
2287 }
2288 }
2289
2290 /* Counts number of failed self-tests. Also encodes the poweron_hour
2291 of the most recent failed self-test. Return value is negative if
2292 this function has a problem (typically -1), otherwise the bottom 8
2293 bits are the number of failed self tests and the 16 bits above that
2294 are the poweron hour of the most recent failure. Note: aborted self
2295 tests (typically by the user) and self tests in progress are not
2296 considered failures. See Working Draft SCSI Primary Commands - 3
2297 (SPC-3) section 7.2.10 T10/1416-D (rev 22a) */
2298 int
2299 scsiCountFailedSelfTests(scsi_device * fd, int noisy)
2300 {
2301 int num, k, err, fails, fail_hour;
2302 UINT8 * ucp;
2303 unsigned char resp[LOG_RESP_SELF_TEST_LEN];
2304
2305 if ((err = scsiLogSense(fd, SELFTEST_RESULTS_LPAGE, 0, resp,
2306 LOG_RESP_SELF_TEST_LEN, 0))) {
2307 if (noisy)
2308 pout("scsiCountSelfTests Failed [%s]\n", scsiErrString(err));
2309 return -1;
2310 }
2311 if ((resp[0] & 0x3f) != SELFTEST_RESULTS_LPAGE) {
2312 if (noisy)
2313 pout("Self-test Log Sense Failed, page mismatch\n");
2314 return -1;
2315 }
2316 // compute page length
2317 num = (resp[2] << 8) + resp[3];
2318 // Log sense page length 0x190 bytes
2319 if (num != 0x190) {
2320 if (noisy)
2321 pout("Self-test Log Sense length is 0x%x not 0x190 bytes\n", num);
2322 return -1;
2323 }
2324 fails = 0;
2325 fail_hour = 0;
2326 // loop through the twenty possible entries
2327 for (k = 0, ucp = resp + 4; k < 20; ++k, ucp += 20 ) {
2328
2329 // timestamp in power-on hours (or zero if test in progress)
2330 int n = (ucp[6] << 8) | ucp[7];
2331
2332 // The spec says "all 20 bytes will be zero if no test" but
2333 // DG has found otherwise. So this is a heuristic.
2334 if ((0 == n) && (0 == ucp[4]))
2335 break;
2336 int res = ucp[4] & 0xf;
2337 if ((res > 2) && (res < 8)) {
2338 fails++;
2339 if (1 == fails)
2340 fail_hour = (ucp[6] << 8) + ucp[7];
2341 }
2342 }
2343 return (fail_hour << 8) + fails;
2344 }
2345
2346 /* Returns 0 if able to read self test log page; then outputs 1 into
2347 *inProgress if self test still in progress, else outputs 0. */
2348 int
2349 scsiSelfTestInProgress(scsi_device * fd, int * inProgress)
2350 {
2351 int num;
2352 UINT8 * ucp;
2353 unsigned char resp[LOG_RESP_SELF_TEST_LEN];
2354
2355 if (scsiLogSense(fd, SELFTEST_RESULTS_LPAGE, 0, resp,
2356 LOG_RESP_SELF_TEST_LEN, 0))
2357 return -1;
2358 if (resp[0] != SELFTEST_RESULTS_LPAGE)
2359 return -1;
2360 // compute page length
2361 num = (resp[2] << 8) + resp[3];
2362 // Log sense page length 0x190 bytes
2363 if (num != 0x190) {
2364 return -1;
2365 }
2366 ucp = resp + 4;
2367 if (inProgress)
2368 *inProgress = (0xf == (ucp[4] & 0xf)) ? 1 : 0;
2369 return 0;
2370 }
2371
2372 /* Returns a negative value if failed to fetch Contol mode page or it was
2373 malformed. Returns 0 if GLTSD bit is zero and returns 1 if the GLTSD
2374 bit is set. Examines default mode page when current==0 else examines
2375 current mode page. */
2376 int
2377 scsiFetchControlGLTSD(scsi_device * device, int modese_len, int current)
2378 {
2379 int err, offset;
2380 UINT8 buff[64];
2381 int pc = current ? MPAGE_CONTROL_CURRENT : MPAGE_CONTROL_DEFAULT;
2382
2383 memset(buff, 0, sizeof(buff));
2384 if (modese_len <= 6) {
2385 if ((err = scsiModeSense(device, CONTROL_MODE_PAGE, 0, pc,
2386 buff, sizeof(buff)))) {
2387 if (SIMPLE_ERR_BAD_OPCODE == err)
2388 modese_len = 10;
2389 else
2390 return -EINVAL;
2391 } else if (0 == modese_len)
2392 modese_len = 6;
2393 }
2394 if (10 == modese_len) {
2395 err = scsiModeSense10(device, CONTROL_MODE_PAGE, 0, pc,
2396 buff, sizeof(buff));
2397 if (err)
2398 return -EINVAL;
2399 }
2400 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2401 if ((offset >= 0) && (buff[offset + 1] >= 0xa))
2402 return (buff[offset + 2] & 2) ? 1 : 0;
2403 return -EINVAL;
2404 }
2405
2406 /* Returns a negative value on error, 0 if unknown and 1 if SSD,
2407 * otherwise the positive returned value is the speed in rpm. First checks
2408 * the Block Device Characteristics VPD page and if that fails it tries the
2409 * RIGID_DISK_DRIVE_GEOMETRY_PAGE mode page. */
2410
2411 int
2412 scsiGetRPM(scsi_device * device, int modese_len, int * form_factorp,
2413 int * haw_zbcp)
2414 {
2415 int err, offset;
2416 UINT8 buff[64];
2417 int pc = MPAGE_CONTROL_DEFAULT;
2418
2419 memset(buff, 0, sizeof(buff));
2420 if ((0 == scsiInquiryVpd(device, SCSI_VPD_BLOCK_DEVICE_CHARACTERISTICS,
2421 buff, sizeof(buff))) &&
2422 (((buff[2] << 8) + buff[3]) > 2)) {
2423 int speed = (buff[4] << 8) + buff[5];
2424 if (form_factorp)
2425 *form_factorp = buff[7] & 0xf;
2426 if (haw_zbcp)
2427 *haw_zbcp = !!(0x10 & buff[8]);
2428 return speed;
2429 }
2430 if (form_factorp)
2431 *form_factorp = 0;
2432 if (haw_zbcp)
2433 *haw_zbcp = 0;
2434 if (modese_len <= 6) {
2435 if ((err = scsiModeSense(device, RIGID_DISK_DRIVE_GEOMETRY_PAGE, 0, pc,
2436 buff, sizeof(buff)))) {
2437 if (SIMPLE_ERR_BAD_OPCODE == err)
2438 modese_len = 10;
2439 else
2440 return -EINVAL;
2441 } else if (0 == modese_len)
2442 modese_len = 6;
2443 }
2444 if (10 == modese_len) {
2445 err = scsiModeSense10(device, RIGID_DISK_DRIVE_GEOMETRY_PAGE, 0, pc,
2446 buff, sizeof(buff));
2447 if (err)
2448 return -EINVAL;
2449 }
2450 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2451 return (buff[offset + 20] << 8) | buff[offset + 21];
2452 }
2453
2454 /* Returns a non-zero value in case of error, wcep/rcdp == -1 - get value,
2455 0 - clear bit, 1 - set bit */
2456
2457 int
2458 scsiGetSetCache(scsi_device * device, int modese_len, short int * wcep,
2459 short int * rcdp)
2460 {
2461 int err, offset, resp_len, sp;
2462 UINT8 buff[64], ch_buff[64];
2463 short set_wce = *wcep;
2464 short set_rcd = *rcdp;
2465
2466 memset(buff, 0, sizeof(buff));
2467 if (modese_len <= 6) {
2468 if ((err = scsiModeSense(device, CACHING_PAGE, 0, MPAGE_CONTROL_CURRENT,
2469 buff, sizeof(buff)))) {
2470 if (SIMPLE_ERR_BAD_OPCODE == err)
2471 modese_len = 10;
2472 else {
2473 device->set_err(EINVAL, "SCSI MODE SENSE failed");
2474 return -EINVAL;
2475 }
2476 } else if (0 == modese_len)
2477 modese_len = 6;
2478 }
2479
2480 if (10 == modese_len) {
2481 err = scsiModeSense10(device, CACHING_PAGE, 0, MPAGE_CONTROL_CURRENT,
2482 buff, sizeof(buff));
2483 if (err) {
2484 device->set_err(EINVAL, "SCSI MODE SENSE failed");
2485 return -EINVAL;
2486 }
2487 }
2488 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2489 if ((offset < 0) || (buff[offset + 1] < 0xa)) {
2490 device->set_err(EINVAL, "Bad response");
2491 return SIMPLE_ERR_BAD_RESP;
2492 }
2493
2494 *wcep = ((buff[offset + 2] & 0x04) != 0);
2495 *rcdp = ((buff[offset + 2] & 0x01) != 0);
2496
2497 if((*wcep == set_wce || set_wce == -1)
2498 && ((*rcdp == set_rcd) || set_rcd == -1))
2499 return 0; // no changes needed or nothing to set
2500
2501 if (modese_len == 6)
2502 err = scsiModeSense(device, CACHING_PAGE, 0,
2503 MPAGE_CONTROL_CHANGEABLE,
2504 ch_buff, sizeof(ch_buff));
2505 else
2506 err = scsiModeSense10(device, CACHING_PAGE, 0,
2507 MPAGE_CONTROL_CHANGEABLE,
2508 ch_buff, sizeof(ch_buff));
2509 if (err) {
2510 device->set_err(EINVAL, "WCE/RCD bits not changable");
2511 return err;
2512 }
2513
2514 // set WCE bit
2515 if(set_wce >= 0 && *wcep != set_wce) {
2516 if (0 == (ch_buff[offset + 2] & 0x04)) {
2517 device->set_err(EINVAL, "WCE bit not changable");
2518 return 1;
2519 }
2520 if(set_wce)
2521 buff[offset + 2] |= 0x04; // set bit
2522 else
2523 buff[offset + 2] &= 0xfb; // clear bit
2524 }
2525 // set RCD bit
2526 if(set_rcd >= 0 && *rcdp != set_rcd) {
2527 if (0 == (ch_buff[offset + 2] & 0x01)) {
2528 device->set_err(EINVAL, "RCD bit not changable");
2529 return 1;
2530 }
2531 if(set_rcd)
2532 buff[offset + 2] |= 0x01; // set bit
2533 else
2534 buff[offset + 2] &= 0xfe; // clear bit
2535 }
2536
2537 /* mask out DPOFUA device specific (disk) parameter bit */
2538 if (10 == modese_len) {
2539 resp_len = (buff[0] << 8) + buff[1] + 2;
2540 buff[3] &= 0xef;
2541 } else {
2542 resp_len = buff[0] + 1;
2543 buff[2] &= 0xef;
2544 }
2545 sp = 0; /* Do not change saved values */
2546 if (10 == modese_len)
2547 err = scsiModeSelect10(device, sp, buff, resp_len);
2548 else if (6 == modese_len)
2549 err = scsiModeSelect(device, sp, buff, resp_len);
2550 if(err)
2551 device->set_err(EINVAL, "MODE SELECT command failed");
2552 return err;
2553 }
2554
2555
2556 /* Attempts to set or clear GLTSD bit in Control mode page. If enabled is
2557 0 attempts to clear GLTSD otherwise it attempts to set it. Returns 0 if
2558 successful, negative if low level error, > 0 if higher level error (e.g.
2559 SIMPLE_ERR_BAD_PARAM if GLTSD bit is not changeable). */
2560 int
2561 scsiSetControlGLTSD(scsi_device * device, int enabled, int modese_len)
2562 {
2563 int err, offset, resp_len, sp;
2564 UINT8 buff[64];
2565 UINT8 ch_buff[64];
2566
2567 memset(buff, 0, sizeof(buff));
2568 if (modese_len <= 6) {
2569 if ((err = scsiModeSense(device, CONTROL_MODE_PAGE, 0,
2570 MPAGE_CONTROL_CURRENT,
2571 buff, sizeof(buff)))) {
2572 if (SIMPLE_ERR_BAD_OPCODE == err)
2573 modese_len = 10;
2574 else
2575 return err;
2576 } else if (0 == modese_len)
2577 modese_len = 6;
2578 }
2579 if (10 == modese_len) {
2580 err = scsiModeSense10(device, CONTROL_MODE_PAGE, 0,
2581 MPAGE_CONTROL_CURRENT,
2582 buff, sizeof(buff));
2583 if (err)
2584 return err;
2585 }
2586 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2587 if ((offset < 0) || (buff[offset + 1] < 0xa))
2588 return SIMPLE_ERR_BAD_RESP;
2589
2590 if (enabled)
2591 enabled = 2;
2592 if (enabled == (buff[offset + 2] & 2))
2593 return 0; /* GLTSD already in wanted state so nothing to do */
2594
2595 if (modese_len == 6)
2596 err = scsiModeSense(device, CONTROL_MODE_PAGE, 0,
2597 MPAGE_CONTROL_CHANGEABLE,
2598 ch_buff, sizeof(ch_buff));
2599 else
2600 err = scsiModeSense10(device, CONTROL_MODE_PAGE, 0,
2601 MPAGE_CONTROL_CHANGEABLE,
2602 ch_buff, sizeof(ch_buff));
2603 if (err)
2604 return err;
2605 if (0 == (ch_buff[offset + 2] & 2))
2606 return SIMPLE_ERR_BAD_PARAM; /* GLTSD bit not changeable */
2607
2608 /* mask out DPOFUA device specific (disk) parameter bit */
2609 if (10 == modese_len) {
2610 resp_len = (buff[0] << 8) + buff[1] + 2;
2611 buff[3] &= 0xef;
2612 } else {
2613 resp_len = buff[0] + 1;
2614 buff[2] &= 0xef;
2615 }
2616 sp = (buff[offset] & 0x80) ? 1 : 0; /* PS bit becomes 'SELECT's SP bit */
2617 if (enabled)
2618 buff[offset + 2] |= 0x2; /* set GLTSD bit */
2619 else
2620 buff[offset + 2] &= 0xfd; /* clear GLTSD bit */
2621 if (10 == modese_len)
2622 err = scsiModeSelect10(device, sp, buff, resp_len);
2623 else if (6 == modese_len)
2624 err = scsiModeSelect(device, sp, buff, resp_len);
2625 return err;
2626 }
2627
2628 /* Returns a negative value if failed to fetch Protocol specific port mode
2629 page or it was malformed. Returns transport protocol identifier when
2630 value >= 0 . */
2631 int
2632 scsiFetchTransportProtocol(scsi_device * device, int modese_len)
2633 {
2634 int err, offset;
2635 UINT8 buff[64];
2636
2637 memset(buff, 0, sizeof(buff));
2638 if (modese_len <= 6) {
2639 if ((err = scsiModeSense(device, PROTOCOL_SPECIFIC_PORT_PAGE, 0,
2640 MPAGE_CONTROL_CURRENT,
2641 buff, sizeof(buff)))) {
2642 if (SIMPLE_ERR_BAD_OPCODE == err)
2643 modese_len = 10;
2644 else
2645 return -EINVAL;
2646 } else if (0 == modese_len)
2647 modese_len = 6;
2648 }
2649 if (10 == modese_len) {
2650 err = scsiModeSense10(device, PROTOCOL_SPECIFIC_PORT_PAGE, 0,
2651 MPAGE_CONTROL_CURRENT,
2652 buff, sizeof(buff));
2653 if (err)
2654 return -EINVAL;
2655 }
2656 offset = scsiModePageOffset(buff, sizeof(buff), modese_len);
2657 if ((offset >= 0) && (buff[offset + 1] > 1)) {
2658 if ((0 == (buff[offset] & 0x40)) && /* SPF==0 */
2659 (PROTOCOL_SPECIFIC_PORT_PAGE == (buff[offset] & 0x3f)))
2660 return (buff[offset + 2] & 0xf);
2661 }
2662 return -EINVAL;
2663 }
2664
2665 const unsigned char *
2666 sg_scsi_sense_desc_find(const unsigned char * sensep, int sense_len,
2667 int desc_type)
2668 {
2669 int add_sen_len;
2670 const unsigned char * descp;
2671
2672 if ((sense_len < 8) || (0 == (add_sen_len = sensep[7])))
2673 return NULL;
2674 if ((sensep[0] < 0x72) || (sensep[0] > 0x73))
2675 return NULL;
2676 add_sen_len = (add_sen_len < (sense_len - 8)) ?
2677 add_sen_len : (sense_len - 8);
2678 descp = &sensep[8];
2679 for (int desc_len = 0, k = 0; k < add_sen_len; k += desc_len) {
2680 descp += desc_len;
2681 int add_len = (k < (add_sen_len - 1)) ? descp[1]: -1;
2682 desc_len = add_len + 2;
2683 if (descp[0] == desc_type)
2684 return descp;
2685 if (add_len < 0) /* short descriptor ?? */
2686 break;
2687 }
2688 return NULL;
2689 }
2690
2691 // Convenience function for formatting strings from SCSI identify
2692 void
2693 scsi_format_id_string(char * out, const unsigned char * in, int n)
2694 {
2695 char tmp[65];
2696 n = n > 64 ? 64 : n;
2697 strncpy(tmp, (const char *)in, n);
2698 tmp[n] = '\0';
2699
2700 // Find the first non-space character (maybe none).
2701 int first = -1;
2702 int i;
2703 for (i = 0; tmp[i]; i++)
2704 if (!isspace((int)tmp[i])) {
2705 first = i;
2706 break;
2707 }
2708
2709 if (first == -1) {
2710 // There are no non-space characters.
2711 out[0] = '\0';
2712 return;
2713 }
2714
2715 // Find the last non-space character.
2716 for (i = strlen(tmp)-1; i >= first && isspace((int)tmp[i]); i--);
2717 int last = i;
2718
2719 strncpy(out, tmp+first, last-first+1);
2720 out[last-first+1] = '\0';
2721 }