]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - ataprint.cpp
Merge commit 'upstream/5.41+svn3365'
[mirror_smartmontools-debian.git] / ataprint.cpp
1 /*
2 * ataprint.cpp
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2008-11 Christian Franke <smartmontools-support@lists.sourceforge.net>
8 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
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, write to the Free
17 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 *
19 * This code was originally developed as a Senior Thesis by Michael Cornwell
20 * at the Concurrent Systems Laboratory (now part of the Storage Systems
21 * Research Center), Jack Baskin School of Engineering, University of
22 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
23 *
24 */
25
26 #include "config.h"
27
28 #include <ctype.h>
29 #include <errno.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "int64.h"
35 #include "atacmdnames.h"
36 #include "atacmds.h"
37 #include "dev_interface.h"
38 #include "ataprint.h"
39 #include "smartctl.h"
40 #include "utility.h"
41 #include "knowndrives.h"
42
43 const char * ataprint_cpp_cvsid = "$Id: ataprint.cpp 3357 2011-06-06 18:56:55Z chrfranke $"
44 ATAPRINT_H_CVSID;
45
46
47 static const char * infofound(const char *output) {
48 return (*output ? output : "[No Information Found]");
49 }
50
51 // Return true if '-T permissive' is specified,
52 // used to ignore missing capabilities
53 static bool is_permissive()
54 {
55 if (!failuretest_permissive)
56 return false;
57 failuretest_permissive--;
58 return true;
59 }
60
61 /* For the given Command Register (CR) and Features Register (FR), attempts
62 * to construct a string that describes the contents of the Status
63 * Register (ST) and Error Register (ER). The caller passes the string
64 * buffer and the return value is a pointer to this string. If the
65 * meanings of the flags of the error register are not known for the given
66 * command then it returns NULL.
67 *
68 * The meanings of the flags of the error register for all commands are
69 * described in the ATA spec and could all be supported here in theory.
70 * Currently, only a few commands are supported (those that have been seen
71 * to produce errors). If many more are to be added then this function
72 * should probably be redesigned.
73 */
74
75 static const char * construct_st_er_desc(
76 char * s,
77 unsigned char CR, unsigned char FR,
78 unsigned char ST, unsigned char ER,
79 unsigned short SC,
80 const ata_smart_errorlog_error_struct * lba28_regs,
81 const ata_smart_exterrlog_error * lba48_regs
82 )
83 {
84 const char *error_flag[8];
85 int i, print_lba=0, print_sector=0;
86
87 // Set of character strings corresponding to different error codes.
88 // Please keep in alphabetic order if you add more.
89 const char *abrt = "ABRT"; // ABORTED
90 const char *amnf = "AMNF"; // ADDRESS MARK NOT FOUND
91 const char *ccto = "CCTO"; // COMMAND COMPLETION TIMED OUT
92 const char *eom = "EOM"; // END OF MEDIA
93 const char *icrc = "ICRC"; // INTERFACE CRC ERROR
94 const char *idnf = "IDNF"; // ID NOT FOUND
95 const char *ili = "ILI"; // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
96 const char *mc = "MC"; // MEDIA CHANGED
97 const char *mcr = "MCR"; // MEDIA CHANGE REQUEST
98 const char *nm = "NM"; // NO MEDIA
99 const char *obs = "obs"; // OBSOLETE
100 const char *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
101 const char *unc = "UNC"; // UNCORRECTABLE
102 const char *wp = "WP"; // WRITE PROTECTED
103
104 /* If for any command the Device Fault flag of the status register is
105 * not used then used_device_fault should be set to 0 (in the CR switch
106 * below)
107 */
108 int uses_device_fault = 1;
109
110 /* A value of NULL means that the error flag isn't used */
111 for (i = 0; i < 8; i++)
112 error_flag[i] = NULL;
113
114 switch (CR) {
115 case 0x10: // RECALIBRATE
116 error_flag[2] = abrt;
117 error_flag[1] = tk0nf;
118 break;
119 case 0x20: /* READ SECTOR(S) */
120 case 0x21: // READ SECTOR(S)
121 case 0x24: // READ SECTOR(S) EXT
122 case 0xC4: /* READ MULTIPLE */
123 case 0x29: // READ MULTIPLE EXT
124 error_flag[6] = unc;
125 error_flag[5] = mc;
126 error_flag[4] = idnf;
127 error_flag[3] = mcr;
128 error_flag[2] = abrt;
129 error_flag[1] = nm;
130 error_flag[0] = amnf;
131 print_lba=1;
132 break;
133 case 0x22: // READ LONG (with retries)
134 case 0x23: // READ LONG (without retries)
135 error_flag[4] = idnf;
136 error_flag[2] = abrt;
137 error_flag[0] = amnf;
138 print_lba=1;
139 break;
140 case 0x2a: // READ STREAM DMA
141 case 0x2b: // READ STREAM PIO
142 if (CR==0x2a)
143 error_flag[7] = icrc;
144 error_flag[6] = unc;
145 error_flag[5] = mc;
146 error_flag[4] = idnf;
147 error_flag[3] = mcr;
148 error_flag[2] = abrt;
149 error_flag[1] = nm;
150 error_flag[0] = ccto;
151 print_lba=1;
152 print_sector=SC;
153 break;
154 case 0x3A: // WRITE STREAM DMA
155 case 0x3B: // WRITE STREAM PIO
156 if (CR==0x3A)
157 error_flag[7] = icrc;
158 error_flag[6] = wp;
159 error_flag[5] = mc;
160 error_flag[4] = idnf;
161 error_flag[3] = mcr;
162 error_flag[2] = abrt;
163 error_flag[1] = nm;
164 error_flag[0] = ccto;
165 print_lba=1;
166 print_sector=SC;
167 break;
168 case 0x25: // READ DMA EXT
169 case 0x26: // READ DMA QUEUED EXT
170 case 0xC7: // READ DMA QUEUED
171 case 0xC8: // READ DMA (with retries)
172 case 0xC9: // READ DMA (without retries, obsolete since ATA-5)
173 case 0x60: // READ FPDMA QUEUED (NCQ)
174 error_flag[7] = icrc;
175 error_flag[6] = unc;
176 error_flag[5] = mc;
177 error_flag[4] = idnf;
178 error_flag[3] = mcr;
179 error_flag[2] = abrt;
180 error_flag[1] = nm;
181 error_flag[0] = amnf;
182 print_lba=1;
183 if (CR==0x25 || CR==0xC8)
184 print_sector=SC;
185 break;
186 case 0x30: /* WRITE SECTOR(S) */
187 case 0x31: // WRITE SECTOR(S)
188 case 0x34: // WRITE SECTOR(S) EXT
189 case 0xC5: /* WRITE MULTIPLE */
190 case 0x39: // WRITE MULTIPLE EXT
191 case 0xCE: // WRITE MULTIPLE FUA EXT
192 error_flag[6] = wp;
193 error_flag[5] = mc;
194 error_flag[4] = idnf;
195 error_flag[3] = mcr;
196 error_flag[2] = abrt;
197 error_flag[1] = nm;
198 print_lba=1;
199 break;
200 case 0x32: // WRITE LONG (with retries)
201 case 0x33: // WRITE LONG (without retries)
202 error_flag[4] = idnf;
203 error_flag[2] = abrt;
204 print_lba=1;
205 break;
206 case 0x3C: // WRITE VERIFY
207 error_flag[6] = unc;
208 error_flag[4] = idnf;
209 error_flag[2] = abrt;
210 error_flag[0] = amnf;
211 print_lba=1;
212 break;
213 case 0x40: // READ VERIFY SECTOR(S) with retries
214 case 0x41: // READ VERIFY SECTOR(S) without retries
215 case 0x42: // READ VERIFY SECTOR(S) EXT
216 error_flag[6] = unc;
217 error_flag[5] = mc;
218 error_flag[4] = idnf;
219 error_flag[3] = mcr;
220 error_flag[2] = abrt;
221 error_flag[1] = nm;
222 error_flag[0] = amnf;
223 print_lba=1;
224 break;
225 case 0xA0: /* PACKET */
226 /* Bits 4-7 are all used for sense key (a 'command packet set specific error
227 * indication' according to the ATA/ATAPI-7 standard), so "Sense key" will
228 * be repeated in the error description string if more than one of those
229 * bits is set.
230 */
231 error_flag[7] = "Sense key (bit 3)",
232 error_flag[6] = "Sense key (bit 2)",
233 error_flag[5] = "Sense key (bit 1)",
234 error_flag[4] = "Sense key (bit 0)",
235 error_flag[2] = abrt;
236 error_flag[1] = eom;
237 error_flag[0] = ili;
238 break;
239 case 0xA1: /* IDENTIFY PACKET DEVICE */
240 case 0xEF: /* SET FEATURES */
241 case 0x00: /* NOP */
242 case 0xC6: /* SET MULTIPLE MODE */
243 error_flag[2] = abrt;
244 break;
245 case 0x2F: // READ LOG EXT
246 error_flag[6] = unc;
247 error_flag[4] = idnf;
248 error_flag[2] = abrt;
249 error_flag[0] = obs;
250 break;
251 case 0x3F: // WRITE LOG EXT
252 error_flag[4] = idnf;
253 error_flag[2] = abrt;
254 error_flag[0] = obs;
255 break;
256 case 0xB0: /* SMART */
257 switch(FR) {
258 case 0xD0: // SMART READ DATA
259 case 0xD1: // SMART READ ATTRIBUTE THRESHOLDS
260 case 0xD5: /* SMART READ LOG */
261 error_flag[6] = unc;
262 error_flag[4] = idnf;
263 error_flag[2] = abrt;
264 error_flag[0] = obs;
265 break;
266 case 0xD6: /* SMART WRITE LOG */
267 error_flag[4] = idnf;
268 error_flag[2] = abrt;
269 error_flag[0] = obs;
270 break;
271 case 0xD2: // Enable/Disable Attribute Autosave
272 case 0xD3: // SMART SAVE ATTRIBUTE VALUES (ATA-3)
273 case 0xD8: // SMART ENABLE OPERATIONS
274 case 0xD9: /* SMART DISABLE OPERATIONS */
275 case 0xDA: /* SMART RETURN STATUS */
276 case 0xDB: // Enable/Disable Auto Offline (SFF)
277 error_flag[2] = abrt;
278 break;
279 case 0xD4: // SMART EXECUTE IMMEDIATE OFFLINE
280 error_flag[4] = idnf;
281 error_flag[2] = abrt;
282 break;
283 default:
284 return NULL;
285 break;
286 }
287 break;
288 case 0xB1: /* DEVICE CONFIGURATION */
289 switch (FR) {
290 case 0xC0: /* DEVICE CONFIGURATION RESTORE */
291 error_flag[2] = abrt;
292 break;
293 default:
294 return NULL;
295 break;
296 }
297 break;
298 case 0xCA: // WRITE DMA (with retries)
299 case 0xCB: // WRITE DMA (without retries, obsolete since ATA-5)
300 case 0x35: // WRITE DMA EXT
301 case 0x3D: // WRITE DMA FUA EXT
302 case 0xCC: // WRITE DMA QUEUED
303 case 0x36: // WRITE DMA QUEUED EXT
304 case 0x3E: // WRITE DMA QUEUED FUA EXT
305 case 0x61: // WRITE FPDMA QUEUED (NCQ)
306 error_flag[7] = icrc;
307 error_flag[6] = wp;
308 error_flag[5] = mc;
309 error_flag[4] = idnf;
310 error_flag[3] = mcr;
311 error_flag[2] = abrt;
312 error_flag[1] = nm;
313 error_flag[0] = amnf;
314 print_lba=1;
315 if (CR==0x35)
316 print_sector=SC;
317 break;
318 case 0xE4: // READ BUFFER
319 case 0xE8: // WRITE BUFFER
320 error_flag[2] = abrt;
321 break;
322 default:
323 return NULL;
324 }
325
326 s[0] = '\0';
327
328 /* We ignore any status flags other than Device Fault and Error */
329
330 if (uses_device_fault && (ST & (1 << 5))) {
331 strcat(s, "Device Fault");
332 if (ST & 1) // Error flag
333 strcat(s, "; ");
334 }
335 if (ST & 1) { // Error flag
336 int count = 0;
337
338 strcat(s, "Error: ");
339 for (i = 7; i >= 0; i--)
340 if ((ER & (1 << i)) && (error_flag[i])) {
341 if (count++ > 0)
342 strcat(s, ", ");
343 strcat(s, error_flag[i]);
344 }
345 }
346
347 // If the error was a READ or WRITE error, print the Logical Block
348 // Address (LBA) at which the read or write failed.
349 if (print_lba) {
350 char tmp[128];
351 // print number of sectors, if known, and append to print string
352 if (print_sector) {
353 snprintf(tmp, 128, " %d sectors", print_sector);
354 strcat(s, tmp);
355 }
356
357 if (lba28_regs) {
358 unsigned lba;
359 // bits 24-27: bits 0-3 of DH
360 lba = 0xf & lba28_regs->drive_head;
361 lba <<= 8;
362 // bits 16-23: CH
363 lba |= lba28_regs->cylinder_high;
364 lba <<= 8;
365 // bits 8-15: CL
366 lba |= lba28_regs->cylinder_low;
367 lba <<= 8;
368 // bits 0-7: SN
369 lba |= lba28_regs->sector_number;
370 snprintf(tmp, 128, " at LBA = 0x%08x = %u", lba, lba);
371 strcat(s, tmp);
372 }
373 else if (lba48_regs) {
374 // This assumes that upper LBA registers are 0 for 28-bit commands
375 // (TODO: detect 48-bit commands above)
376 uint64_t lba48;
377 lba48 = lba48_regs->lba_high_register_hi;
378 lba48 <<= 8;
379 lba48 |= lba48_regs->lba_mid_register_hi;
380 lba48 <<= 8;
381 lba48 |= lba48_regs->lba_low_register_hi;
382 lba48 |= lba48_regs->device_register & 0xf;
383 lba48 <<= 8;
384 lba48 |= lba48_regs->lba_high_register;
385 lba48 <<= 8;
386 lba48 |= lba48_regs->lba_mid_register;
387 lba48 <<= 8;
388 lba48 |= lba48_regs->lba_low_register;
389 snprintf(tmp, 128, " at LBA = 0x%08"PRIx64" = %"PRIu64, lba48, lba48);
390 strcat(s, tmp);
391 }
392 }
393
394 return s;
395 }
396
397 static inline const char * construct_st_er_desc(char * s,
398 const ata_smart_errorlog_struct * data)
399 {
400 return construct_st_er_desc(s,
401 data->commands[4].commandreg,
402 data->commands[4].featuresreg,
403 data->error_struct.status,
404 data->error_struct.error_register,
405 data->error_struct.sector_count,
406 &data->error_struct, (const ata_smart_exterrlog_error *)0);
407 }
408
409 static inline const char * construct_st_er_desc(char * s,
410 const ata_smart_exterrlog_error_log * data)
411 {
412 return construct_st_er_desc(s,
413 data->commands[4].command_register,
414 data->commands[4].features_register,
415 data->error.status_register,
416 data->error.error_register,
417 data->error.count_register_hi << 8 | data->error.count_register,
418 (const ata_smart_errorlog_error_struct *)0, &data->error);
419 }
420
421 static void print_drive_info(const ata_identify_device * drive,
422 const ata_size_info & sizes,
423 const drive_settings * dbentry)
424 {
425 // format drive information (with byte swapping as needed)
426 char model[40+1], serial[20+1], firmware[8+1];
427 ata_format_id_string(model, drive->model, sizeof(model)-1);
428 ata_format_id_string(serial, drive->serial_no, sizeof(serial)-1);
429 ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware)-1);
430
431 // Print model family if known
432 if (dbentry && *dbentry->modelfamily)
433 pout("Model Family: %s\n", dbentry->modelfamily);
434
435 pout("Device Model: %s\n", infofound(model));
436 if (!dont_print_serial_number) {
437 pout("Serial Number: %s\n", infofound(serial));
438
439 unsigned oui = 0; uint64_t unique_id = 0;
440 int naa = ata_get_wwn(drive, oui, unique_id);
441 if (naa >= 0)
442 pout("LU WWN Device Id: %x %06x %09"PRIx64"\n", naa, oui, unique_id);
443 }
444 pout("Firmware Version: %s\n", infofound(firmware));
445
446 if (sizes.capacity) {
447 // Print capacity
448 char num[64], cap[32];
449 pout("User Capacity: %s bytes [%s]\n",
450 format_with_thousands_sep(num, sizeof(num), sizes.capacity),
451 format_capacity(cap, sizeof(cap), sizes.capacity));
452
453 // Print sector sizes.
454 if (sizes.phy_sector_size == sizes.log_sector_size)
455 pout("Sector Size: %u bytes logical/physical\n", sizes.log_sector_size);
456 else {
457 pout("Sector Sizes: %u bytes logical, %u bytes physical",
458 sizes.log_sector_size, sizes.phy_sector_size);
459 if (sizes.log_sector_offset)
460 pout(" (offset %u bytes)", sizes.log_sector_offset);
461 pout("\n");
462 }
463 }
464
465 // See if drive is recognized
466 pout("Device is: %s\n", !dbentry ?
467 "Not in smartctl database [for details use: -P showall]":
468 "In smartctl database [for details use: -P show]");
469
470 // now get ATA version info
471 const char *description; unsigned short minorrev;
472 int version = ataVersionInfo(&description, drive, &minorrev);
473
474 // SMART Support was first added into the ATA/ATAPI-3 Standard with
475 // Revision 3 of the document, July 25, 1995. Look at the "Document
476 // Status" revision commands at the beginning of
477 // http://www.t13.org/Documents/UploadedDocuments/project/d2008r7b-ATA-3.pdf
478 // to see this. So it's not enough to check if we are ATA-3.
479 // Version=-3 indicates ATA-3 BEFORE Revision 3.
480 // Version=0 indicates that no info is found. This may happen if
481 // the OS provides only part of the IDENTIFY data.
482
483 std::string majorstr, minorstr;
484 if (version) {
485 majorstr = strprintf("%d", abs(version));
486 if (description)
487 minorstr = description;
488 else if (!minorrev)
489 minorstr = "Exact ATA specification draft version not indicated";
490 else
491 minorstr = strprintf("Not recognized. Minor revision code: 0x%04x", minorrev);
492 }
493
494 pout("ATA Version is: %s\n", infofound(majorstr.c_str()));
495 pout("ATA Standard is: %s\n", infofound(minorstr.c_str()));
496
497 // print current time and date and timezone
498 char timedatetz[DATEANDEPOCHLEN]; dateandtimezone(timedatetz);
499 pout("Local Time is: %s\n", timedatetz);
500
501 // Print warning message, if there is one
502 if (dbentry && *dbentry->warningmsg)
503 pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
504
505 if (!version || version >= 3)
506 return;
507
508 pout("SMART is only available in ATA Version 3 Revision 3 or greater.\n");
509 pout("We will try to proceed in spite of this.\n");
510 }
511
512 static const char *OfflineDataCollectionStatus(unsigned char status_byte)
513 {
514 unsigned char stat=status_byte & 0x7f;
515
516 switch(stat){
517 case 0x00:
518 return "was never started";
519 case 0x02:
520 return "was completed without error";
521 case 0x03:
522 if (status_byte == 0x03)
523 return "is in progress";
524 else
525 return "is in a Reserved state";
526 case 0x04:
527 return "was suspended by an interrupting command from host";
528 case 0x05:
529 return "was aborted by an interrupting command from host";
530 case 0x06:
531 return "was aborted by the device with a fatal error";
532 default:
533 if (stat >= 0x40)
534 return "is in a Vendor Specific state";
535 else
536 return "is in a Reserved state";
537 }
538 }
539
540
541 // prints verbose value Off-line data collection status byte
542 static void PrintSmartOfflineStatus(const ata_smart_values * data)
543 {
544 pout("Offline data collection status: (0x%02x)\t",
545 (int)data->offline_data_collection_status);
546
547 // Off-line data collection status byte is not a reserved
548 // or vendor specific value
549 pout("Offline data collection activity\n"
550 "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
551
552 // Report on Automatic Data Collection Status. Only IBM documents
553 // this bit. See SFF 8035i Revision 2 for details.
554 if (data->offline_data_collection_status & 0x80)
555 pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
556 else
557 pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
558
559 return;
560 }
561
562 static void PrintSmartSelfExecStatus(const ata_smart_values * data,
563 unsigned char fix_firmwarebug)
564 {
565 pout("Self-test execution status: ");
566
567 switch (data->self_test_exec_status >> 4)
568 {
569 case 0:
570 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
571 (int)data->self_test_exec_status);
572 pout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
573 break;
574 case 1:
575 pout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t",
576 (int)data->self_test_exec_status);
577 pout("the host.\n");
578 break;
579 case 2:
580 pout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t",
581 (int)data->self_test_exec_status);
582 pout("by the host with a hard or soft reset.\n");
583 break;
584 case 3:
585 pout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t",
586 (int)data->self_test_exec_status);
587 pout("occurred while the device was executing\n\t\t\t\t\t");
588 pout("its self-test routine and the device \n\t\t\t\t\t");
589 pout("was unable to complete the self-test \n\t\t\t\t\t");
590 pout("routine.\n");
591 break;
592 case 4:
593 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
594 (int)data->self_test_exec_status);
595 pout("a test element that failed and the test\n\t\t\t\t\t");
596 pout("element that failed is not known.\n");
597 break;
598 case 5:
599 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
600 (int)data->self_test_exec_status);
601 pout("the electrical element of the test\n\t\t\t\t\t");
602 pout("failed.\n");
603 break;
604 case 6:
605 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
606 (int)data->self_test_exec_status);
607 pout("the servo (and/or seek) element of the \n\t\t\t\t\t");
608 pout("test failed.\n");
609 break;
610 case 7:
611 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
612 (int)data->self_test_exec_status);
613 pout("the read element of the test failed.\n");
614 break;
615 case 8:
616 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
617 (int)data->self_test_exec_status);
618 pout("a test element that failed and the\n\t\t\t\t\t");
619 pout("device is suspected of having handling\n\t\t\t\t\t");
620 pout("damage.\n");
621 break;
622 case 15:
623 if (fix_firmwarebug == FIX_SAMSUNG3 && data->self_test_exec_status == 0xf0) {
624 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
625 (int)data->self_test_exec_status);
626 pout("with unknown result or self-test in\n\t\t\t\t\t");
627 pout("progress with less than 10%% remaining.\n");
628 }
629 else {
630 pout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t",
631 (int)data->self_test_exec_status);
632 pout("%1d0%% of test remaining.\n",
633 (int)(data->self_test_exec_status & 0x0f));
634 }
635 break;
636 default:
637 pout("(%4d)\tReserved.\n",
638 (int)data->self_test_exec_status);
639 break;
640 }
641
642 }
643
644 static void PrintSmartTotalTimeCompleteOffline (const ata_smart_values * data)
645 {
646 pout("Total time to complete Offline \n");
647 pout("data collection: \t\t(%5d) seconds.\n",
648 (int)data->total_time_to_complete_off_line);
649 }
650
651 static void PrintSmartOfflineCollectCap(const ata_smart_values *data)
652 {
653 pout("Offline data collection\n");
654 pout("capabilities: \t\t\t (0x%02x) ",
655 (int)data->offline_data_collection_capability);
656
657 if (data->offline_data_collection_capability == 0x00){
658 pout("\tOffline data collection not supported.\n");
659 }
660 else {
661 pout( "%s\n", isSupportExecuteOfflineImmediate(data)?
662 "SMART execute Offline immediate." :
663 "No SMART execute Offline immediate.");
664
665 pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)?
666 "Auto Offline data collection on/off support.":
667 "No Auto Offline data collection support.");
668
669 pout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)?
670 "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
671 "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
672
673 pout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)?
674 "Offline surface scan supported.":
675 "No Offline surface scan supported.");
676
677 pout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)?
678 "Self-test supported.":
679 "No Self-test supported.");
680
681 pout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)?
682 "Conveyance Self-test supported.":
683 "No Conveyance Self-test supported.");
684
685 pout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)?
686 "Selective Self-test supported.":
687 "No Selective Self-test supported.");
688 }
689 }
690
691 static void PrintSmartCapability(const ata_smart_values *data)
692 {
693 pout("SMART capabilities: ");
694 pout("(0x%04x)\t", (int)data->smart_capability);
695
696 if (data->smart_capability == 0x00)
697 {
698 pout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
699 }
700 else
701 {
702
703 pout( "%s\n", (data->smart_capability & 0x01)?
704 "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
705 "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
706
707 if ( data->smart_capability & 0x02 )
708 {
709 pout("\t\t\t\t\tSupports SMART auto save timer.\n");
710 }
711 }
712 }
713
714 static void PrintSmartErrorLogCapability(const ata_smart_values * data, const ata_identify_device * identity)
715 {
716 pout("Error logging capability: ");
717
718 if ( isSmartErrorLogCapable(data, identity) )
719 {
720 pout(" (0x%02x)\tError logging supported.\n",
721 (int)data->errorlog_capability);
722 }
723 else {
724 pout(" (0x%02x)\tError logging NOT supported.\n",
725 (int)data->errorlog_capability);
726 }
727 }
728
729 static void PrintSmartShortSelfTestPollingTime(const ata_smart_values * data)
730 {
731 pout("Short self-test routine \n");
732 if (isSupportSelfTest(data))
733 pout("recommended polling time: \t (%4d) minutes.\n",
734 (int)data->short_test_completion_time);
735 else
736 pout("recommended polling time: \t Not Supported.\n");
737 }
738
739 static void PrintSmartExtendedSelfTestPollingTime(const ata_smart_values * data)
740 {
741 pout("Extended self-test routine\n");
742 if (isSupportSelfTest(data))
743 pout("recommended polling time: \t (%4d) minutes.\n",
744 (int)data->extend_test_completion_time);
745 else
746 pout("recommended polling time: \t Not Supported.\n");
747 }
748
749 static void PrintSmartConveyanceSelfTestPollingTime(const ata_smart_values * data)
750 {
751 pout("Conveyance self-test routine\n");
752 if (isSupportConveyanceSelfTest(data))
753 pout("recommended polling time: \t (%4d) minutes.\n",
754 (int)data->conveyance_test_completion_time);
755 else
756 pout("recommended polling time: \t Not Supported.\n");
757 }
758
759 // Check SMART attribute table for Threshold failure
760 // onlyfailed=0: are or were any age or prefailure attributes <= threshold
761 // onlyfailed=1: are any prefailure attributes <= threshold now
762 static int find_failed_attr(const ata_smart_values * data,
763 const ata_smart_thresholds_pvt * thresholds,
764 const ata_vendor_attr_defs & defs, int onlyfailed)
765 {
766 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
767 const ata_smart_attribute & attr = data->vendor_attributes[i];
768
769 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs);
770
771 if (!onlyfailed) {
772 if (state >= ATTRSTATE_FAILED_PAST)
773 return attr.id;
774 }
775 else {
776 if (state == ATTRSTATE_FAILED_NOW && ATTRIBUTE_FLAGS_PREFAILURE(attr.flags))
777 return attr.id;
778 }
779 }
780 return 0;
781 }
782
783 // onlyfailed=0 : print all attribute values
784 // onlyfailed=1: just ones that are currently failed and have prefailure bit set
785 // onlyfailed=2: ones that are failed, or have failed with or without prefailure bit set
786 static void PrintSmartAttribWithThres(const ata_smart_values * data,
787 const ata_smart_thresholds_pvt * thresholds,
788 const ata_vendor_attr_defs & defs,
789 int onlyfailed, unsigned char format)
790 {
791 bool needheader = true;
792
793 // step through all vendor attributes
794 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
795 const ata_smart_attribute & attr = data->vendor_attributes[i];
796
797 // Check attribute and threshold
798 unsigned char threshold = 0;
799 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs, &threshold);
800 if (state == ATTRSTATE_NON_EXISTING)
801 continue;
802
803 // These break out of the loop if we are only printing certain entries...
804 if (onlyfailed == 1 && !(ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) && state == ATTRSTATE_FAILED_NOW))
805 continue;
806
807 if (onlyfailed == 2 && state < ATTRSTATE_FAILED_PAST)
808 continue;
809
810 // print header only if needed
811 if (needheader) {
812 if (!onlyfailed) {
813 pout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
814 pout("Vendor Specific SMART Attributes with Thresholds:\n");
815 }
816 if (format == 0)
817 pout("ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE\n");
818 else
819 pout("ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE\n");
820 needheader = false;
821 }
822
823 // Format value, worst, threshold
824 std::string valstr, worstr, threstr;
825 if (state > ATTRSTATE_NO_NORMVAL)
826 valstr = strprintf("%.3d", attr.current);
827 else
828 valstr = "---";
829 if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
830 worstr = strprintf("%.3d", attr.worst);
831 else
832 worstr = "---";
833 if (state > ATTRSTATE_NO_THRESHOLD)
834 threstr = strprintf("%.3d", threshold);
835 else
836 threstr = "---";
837
838 // Print line for each valid attribute
839 std::string attrname = ata_get_smart_attr_name(attr.id, defs);
840 std::string rawstr = ata_format_attr_raw_value(attr, defs);
841
842 if (format == 0)
843 pout("%3d %-24s0x%04x %-3s %-3s %-3s %-10s%-9s%-12s%s\n",
844 attr.id, attrname.c_str(), attr.flags,
845 valstr.c_str(), worstr.c_str(), threstr.c_str(),
846 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? "Pre-fail" : "Old_age"),
847 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? "Always" : "Offline"),
848 (state == ATTRSTATE_FAILED_NOW ? "FAILING_NOW" :
849 state == ATTRSTATE_FAILED_PAST ? "In_the_past"
850 : " -" ) ,
851 rawstr.c_str());
852 else
853 pout("%3d %-24s%c%c%c%c%c%c%c %-3s %-3s %-3s %-5s%s\n",
854 attr.id, attrname.c_str(),
855 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? 'P' : '-'),
856 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? 'O' : '-'),
857 (ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags) ? 'S' : '-'),
858 (ATTRIBUTE_FLAGS_ERRORRATE(attr.flags) ? 'R' : '-'),
859 (ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags) ? 'C' : '-'),
860 (ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags) ? 'K' : '-'),
861 (ATTRIBUTE_FLAGS_OTHER(attr.flags) ? '+' : ' '),
862 valstr.c_str(), worstr.c_str(), threstr.c_str(),
863 (state == ATTRSTATE_FAILED_NOW ? "NOW" :
864 state == ATTRSTATE_FAILED_PAST ? "Past"
865 : "-" ),
866 rawstr.c_str());
867
868 }
869
870 if (!needheader) {
871 if (!onlyfailed && format == 1)
872 pout("%28s||||||_ K auto-keep\n"
873 "%28s|||||__ C event count\n"
874 "%28s||||___ R error rate\n"
875 "%28s|||____ S speed/performance\n"
876 "%28s||_____ O updated online\n"
877 "%28s|______ P prefailure warning\n",
878 "", "", "", "", "", "");
879 pout("\n");
880 }
881 }
882
883 // Print SMART related SCT capabilities
884 static void ataPrintSCTCapability(const ata_identify_device *drive)
885 {
886 unsigned short sctcaps = drive->words088_255[206-88];
887 if (!(sctcaps & 0x01))
888 return;
889 pout("SCT capabilities: \t (0x%04x)\tSCT Status supported.\n", sctcaps);
890 if (sctcaps & 0x08)
891 pout("\t\t\t\t\tSCT Error Recovery Control supported.\n");
892 if (sctcaps & 0x10)
893 pout("\t\t\t\t\tSCT Feature Control supported.\n");
894 if (sctcaps & 0x20)
895 pout("\t\t\t\t\tSCT Data Table supported.\n");
896 }
897
898
899 static void PrintGeneralSmartValues(const ata_smart_values *data, const ata_identify_device *drive,
900 unsigned char fix_firmwarebug)
901 {
902 pout("General SMART Values:\n");
903
904 PrintSmartOfflineStatus(data);
905
906 if (isSupportSelfTest(data)){
907 PrintSmartSelfExecStatus(data, fix_firmwarebug);
908 }
909
910 PrintSmartTotalTimeCompleteOffline(data);
911 PrintSmartOfflineCollectCap(data);
912 PrintSmartCapability(data);
913
914 PrintSmartErrorLogCapability(data, drive);
915
916 pout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
917 "General Purpose Logging supported.":
918 "No General Purpose Logging support.");
919
920 if (isSupportSelfTest(data)){
921 PrintSmartShortSelfTestPollingTime (data);
922 PrintSmartExtendedSelfTestPollingTime (data);
923 }
924 if (isSupportConveyanceSelfTest(data))
925 PrintSmartConveyanceSelfTestPollingTime (data);
926
927 ataPrintSCTCapability(drive);
928
929 pout("\n");
930 }
931
932 // Get # sectors of a log addr, 0 if log does not exist.
933 static unsigned GetNumLogSectors(const ata_smart_log_directory * logdir, unsigned logaddr, bool gpl)
934 {
935 if (!logdir)
936 return 0;
937 if (logaddr > 0xff)
938 return 0;
939 if (logaddr == 0)
940 return 1;
941 unsigned n = logdir->entry[logaddr-1].numsectors;
942 if (gpl)
943 // GP logs may have >255 sectors
944 n |= logdir->entry[logaddr-1].reserved << 8;
945 return n;
946 }
947
948 // Get name of log.
949 // Table A.2 of T13/2015-D Revision 4a (ACS-2), December 9, 2010.
950 static const char * GetLogName(unsigned logaddr)
951 {
952 switch (logaddr) {
953 case 0x00: return "Log Directory";
954 case 0x01: return "Summary SMART error log";
955 case 0x02: return "Comprehensive SMART error log";
956 case 0x03: return "Ext. Comprehensive SMART error log";
957 case 0x04: return "Device Statistics";
958 case 0x05: return "Reserved for the CFA"; // ACS-2
959 case 0x06: return "SMART self-test log";
960 case 0x07: return "Extended self-test log";
961 case 0x08: return "Power Conditions"; // ACS-2
962 case 0x09: return "Selective self-test log";
963 case 0x0d: return "LPS Mis-alignment log"; // ACS-2
964 case 0x10: return "NCQ Command Error";
965 case 0x11: return "SATA Phy Event Counters";
966 case 0x20: return "Streaming performance log"; // Obsolete
967 case 0x21: return "Write stream error log";
968 case 0x22: return "Read stream error log";
969 case 0x23: return "Delayed sector log"; // Obsolete
970 case 0xe0: return "SCT Command/Status";
971 case 0xe1: return "SCT Data Transfer";
972 default:
973 if (0xa0 <= logaddr && logaddr <= 0xdf)
974 return "Device vendor specific log";
975 if (0x80 <= logaddr && logaddr <= 0x9f)
976 return "Host vendor specific log";
977 if (0x12 <= logaddr && logaddr <= 0x17)
978 return "Reserved for Serial ATA";
979 return "Reserved";
980 }
981 /*NOTREACHED*/
982 }
983
984 // Print SMART and/or GP Log Directory
985 static void PrintLogDirectories(const ata_smart_log_directory * gplogdir,
986 const ata_smart_log_directory * smartlogdir)
987 {
988 if (gplogdir)
989 pout("General Purpose Log Directory Version %u\n", gplogdir->logversion);
990 if (smartlogdir)
991 pout("SMART %sLog Directory Version %u%s\n",
992 (gplogdir ? " " : ""), smartlogdir->logversion,
993 (smartlogdir->logversion==1 ? " [multi-sector log support]" : ""));
994
995 for (unsigned i = 0; i <= 0xff; i++) {
996 // Get number of sectors
997 unsigned smart_numsect = GetNumLogSectors(smartlogdir, i, false);
998 unsigned gp_numsect = GetNumLogSectors(gplogdir , i, true );
999
1000 if (!(smart_numsect || gp_numsect))
1001 continue; // Log does not exist
1002
1003 const char * name = GetLogName(i);
1004
1005 // Print name and length of log.
1006 // If both SMART and GP exist, print separate entries if length differ.
1007 if (smart_numsect == gp_numsect)
1008 pout( "GP/S Log at address 0x%02x has %4d sectors [%s]\n", i, smart_numsect, name);
1009 else {
1010 if (gp_numsect)
1011 pout("GP %sLog at address 0x%02x has %4d sectors [%s]\n", (smartlogdir?" ":""),
1012 i, gp_numsect, name);
1013 if (smart_numsect)
1014 pout("SMART Log at address 0x%02x has %4d sectors [%s]\n", i, smart_numsect, name);
1015 }
1016 }
1017 pout("\n");
1018 }
1019
1020 // Print hexdump of log pages.
1021 // Format is compatible with 'xxd -r'.
1022 static void PrintLogPages(const char * type, const unsigned char * data,
1023 unsigned char logaddr, unsigned page,
1024 unsigned num_pages, unsigned max_pages)
1025 {
1026 pout("%s Log 0x%02x [%s], Page %u-%u (of %u)\n",
1027 type, logaddr, GetLogName(logaddr), page, page+num_pages-1, max_pages);
1028 for (unsigned i = 0; i < num_pages * 512; i += 16) {
1029 const unsigned char * p = data+i;
1030 pout("%07x: %02x %02x %02x %02x %02x %02x %02x %02x "
1031 "%02x %02x %02x %02x %02x %02x %02x %02x ",
1032 (page * 512) + i,
1033 p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
1034 p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
1035 #define P(n) (isprint((int)(p[n]))?(int)(p[n]):'.')
1036 pout("|%c%c%c%c%c%c%c%c"
1037 "%c%c%c%c%c%c%c%c|\n",
1038 P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
1039 P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15));
1040 #undef P
1041 if ((i & 0x1ff) == 0x1f0)
1042 pout("\n");
1043 }
1044 }
1045
1046 // Print log 0x11
1047 static void PrintSataPhyEventCounters(const unsigned char * data, bool reset)
1048 {
1049 if (checksum(data))
1050 checksumwarning("SATA Phy Event Counters");
1051 pout("SATA Phy Event Counters (GP Log 0x11)\n");
1052 if (data[0] || data[1] || data[2] || data[3])
1053 pout("[Reserved: 0x%02x 0x%02x 0x%02x 0x%02x]\n",
1054 data[0], data[1], data[2], data[3]);
1055 pout("ID Size Value Description\n");
1056
1057 for (unsigned i = 4; ; ) {
1058 // Get counter id and size (bits 14:12)
1059 unsigned id = data[i] | (data[i+1] << 8);
1060 unsigned size = ((id >> 12) & 0x7) << 1;
1061 id &= 0x8fff;
1062
1063 // End of counter table ?
1064 if (!id)
1065 break;
1066 i += 2;
1067
1068 if (!(2 <= size && size <= 8 && i + size < 512)) {
1069 pout("0x%04x %u: Invalid entry\n", id, size);
1070 break;
1071 }
1072
1073 // Get value
1074 uint64_t val = 0, max_val = 0;
1075 for (unsigned j = 0; j < size; j+=2) {
1076 val |= (uint64_t)(data[i+j] | (data[i+j+1] << 8)) << (j*8);
1077 max_val |= (uint64_t)0xffffU << (j*8);
1078 }
1079 i += size;
1080
1081 // Get name
1082 const char * name;
1083 switch (id) {
1084 case 0x001: name = "Command failed due to ICRC error"; break; // Mandatory
1085 case 0x002: name = "R_ERR response for data FIS"; break;
1086 case 0x003: name = "R_ERR response for device-to-host data FIS"; break;
1087 case 0x004: name = "R_ERR response for host-to-device data FIS"; break;
1088 case 0x005: name = "R_ERR response for non-data FIS"; break;
1089 case 0x006: name = "R_ERR response for device-to-host non-data FIS"; break;
1090 case 0x007: name = "R_ERR response for host-to-device non-data FIS"; break;
1091 case 0x008: name = "Device-to-host non-data FIS retries"; break;
1092 case 0x009: name = "Transition from drive PhyRdy to drive PhyNRdy"; break;
1093 case 0x00A: name = "Device-to-host register FISes sent due to a COMRESET"; break; // Mandatory
1094 case 0x00B: name = "CRC errors within host-to-device FIS"; break;
1095 case 0x00D: name = "Non-CRC errors within host-to-device FIS"; break;
1096 case 0x00F: name = "R_ERR response for host-to-device data FIS, CRC"; break;
1097 case 0x010: name = "R_ERR response for host-to-device data FIS, non-CRC"; break;
1098 case 0x012: name = "R_ERR response for host-to-device non-data FIS, CRC"; break;
1099 case 0x013: name = "R_ERR response for host-to-device non-data FIS, non-CRC"; break;
1100 default: name = (id & 0x8000 ? "Vendor specific" : "Unknown"); break;
1101 }
1102
1103 // Counters stop at max value, add '+' in this case
1104 pout("0x%04x %u %12"PRIu64"%c %s\n", id, size, val,
1105 (val == max_val ? '+' : ' '), name);
1106 }
1107 if (reset)
1108 pout("All counters reset\n");
1109 pout("\n");
1110 }
1111
1112 // Get description for 'state' value from SMART Error Logs
1113 static const char * get_error_log_state_desc(unsigned state)
1114 {
1115 state &= 0x0f;
1116 switch (state){
1117 case 0x0: return "in an unknown state";
1118 case 0x1: return "sleeping";
1119 case 0x2: return "in standby mode";
1120 case 0x3: return "active or idle";
1121 case 0x4: return "doing SMART Offline or Self-test";
1122 default:
1123 return (state < 0xb ? "in a reserved state"
1124 : "in a vendor specific state");
1125 }
1126 }
1127
1128 // returns number of errors
1129 static int PrintSmartErrorlog(const ata_smart_errorlog *data,
1130 unsigned char fix_firmwarebug)
1131 {
1132 pout("SMART Error Log Version: %d\n", (int)data->revnumber);
1133
1134 // if no errors logged, return
1135 if (!data->error_log_pointer){
1136 pout("No Errors Logged\n\n");
1137 return 0;
1138 }
1139 print_on();
1140 // If log pointer out of range, return
1141 if (data->error_log_pointer>5){
1142 pout("Invalid Error Log index = 0x%02x (T13/1321D rev 1c "
1143 "Section 8.41.6.8.2.2 gives valid range from 1 to 5)\n\n",
1144 (int)data->error_log_pointer);
1145 return 0;
1146 }
1147
1148 // Some internal consistency checking of the data structures
1149 if ((data->ata_error_count-data->error_log_pointer)%5 && fix_firmwarebug != FIX_SAMSUNG2) {
1150 pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
1151 data->ata_error_count,data->error_log_pointer);
1152 }
1153
1154 // starting printing error log info
1155 if (data->ata_error_count<=5)
1156 pout( "ATA Error Count: %d\n", (int)data->ata_error_count);
1157 else
1158 pout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
1159 (int)data->ata_error_count);
1160 print_off();
1161 pout("\tCR = Command Register [HEX]\n"
1162 "\tFR = Features Register [HEX]\n"
1163 "\tSC = Sector Count Register [HEX]\n"
1164 "\tSN = Sector Number Register [HEX]\n"
1165 "\tCL = Cylinder Low Register [HEX]\n"
1166 "\tCH = Cylinder High Register [HEX]\n"
1167 "\tDH = Device/Head Register [HEX]\n"
1168 "\tDC = Device Command Register [HEX]\n"
1169 "\tER = Error register [HEX]\n"
1170 "\tST = Status register [HEX]\n"
1171 "Powered_Up_Time is measured from power on, and printed as\n"
1172 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1173 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1174
1175 // now step through the five error log data structures (table 39 of spec)
1176 for (int k = 4; k >= 0; k-- ) {
1177
1178 // The error log data structure entries are a circular buffer
1179 int j, i=(data->error_log_pointer+k)%5;
1180 const ata_smart_errorlog_struct * elog = data->errorlog_struct+i;
1181 const ata_smart_errorlog_error_struct * summary = &(elog->error_struct);
1182
1183 // Spec says: unused error log structures shall be zero filled
1184 if (nonempty(elog, sizeof(*elog))){
1185 // Table 57 of T13/1532D Volume 1 Revision 3
1186 const char *msgstate = get_error_log_state_desc(summary->state);
1187 int days = (int)summary->timestamp/24;
1188
1189 // See table 42 of ATA5 spec
1190 print_on();
1191 pout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
1192 (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
1193 print_off();
1194 pout(" When the command that caused the error occurred, the device was %s.\n\n",msgstate);
1195 pout(" After command completion occurred, registers were:\n"
1196 " ER ST SC SN CL CH DH\n"
1197 " -- -- -- -- -- -- --\n"
1198 " %02x %02x %02x %02x %02x %02x %02x",
1199 (int)summary->error_register,
1200 (int)summary->status,
1201 (int)summary->sector_count,
1202 (int)summary->sector_number,
1203 (int)summary->cylinder_low,
1204 (int)summary->cylinder_high,
1205 (int)summary->drive_head);
1206 // Add a description of the contents of the status and error registers
1207 // if possible
1208 char descbuf[256];
1209 const char * st_er_desc = construct_st_er_desc(descbuf, elog);
1210 if (st_er_desc)
1211 pout(" %s", st_er_desc);
1212 pout("\n\n");
1213 pout(" Commands leading to the command that caused the error were:\n"
1214 " CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name\n"
1215 " -- -- -- -- -- -- -- -- ---------------- --------------------\n");
1216 for ( j = 4; j >= 0; j--){
1217 const ata_smart_errorlog_command_struct * thiscommand = elog->commands+j;
1218
1219 // Spec says: unused data command structures shall be zero filled
1220 if (nonempty(thiscommand, sizeof(*thiscommand))) {
1221 char timestring[32];
1222
1223 // Convert integer milliseconds to a text-format string
1224 MsecToText(thiscommand->timestamp, timestring);
1225
1226 pout(" %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1227 (int)thiscommand->commandreg,
1228 (int)thiscommand->featuresreg,
1229 (int)thiscommand->sector_count,
1230 (int)thiscommand->sector_number,
1231 (int)thiscommand->cylinder_low,
1232 (int)thiscommand->cylinder_high,
1233 (int)thiscommand->drive_head,
1234 (int)thiscommand->devicecontrolreg,
1235 timestring,
1236 look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg));
1237 }
1238 }
1239 pout("\n");
1240 }
1241 }
1242 print_on();
1243 if (printing_is_switchable)
1244 pout("\n");
1245 print_off();
1246 return data->ata_error_count;
1247 }
1248
1249 // Print SMART Extended Comprehensive Error Log (GP Log 0x03)
1250 static int PrintSmartExtErrorLog(const ata_smart_exterrlog * log,
1251 unsigned nsectors, unsigned max_errors)
1252 {
1253 pout("SMART Extended Comprehensive Error Log Version: %u (%u sectors)\n",
1254 log->version, nsectors);
1255
1256 if (!log->device_error_count) {
1257 pout("No Errors Logged\n\n");
1258 return 0;
1259 }
1260 print_on();
1261
1262 // Check index
1263 unsigned nentries = nsectors * 4;
1264 unsigned erridx = log->error_log_index;
1265 if (!(1 <= erridx && erridx <= nentries)){
1266 // Some Samsung disks (at least SP1614C/SW100-25, HD300LJ/ZT100-12) use the
1267 // former index from Summary Error Log (byte 1, now reserved) and set byte 2-3
1268 // to 0.
1269 if (!(erridx == 0 && 1 <= log->reserved1 && log->reserved1 <= nentries)) {
1270 pout("Invalid Error Log index = 0x%04x (reserved = 0x%02x)\n", erridx, log->reserved1);
1271 return 0;
1272 }
1273 pout("Invalid Error Log index = 0x%04x, trying reserved byte (0x%02x) instead\n", erridx, log->reserved1);
1274 erridx = log->reserved1;
1275 }
1276
1277 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1278 // it is 1-based in practice.
1279 erridx--;
1280
1281 // Calculate #errors to print
1282 unsigned errcnt = log->device_error_count;
1283
1284 if (errcnt <= nentries)
1285 pout("Device Error Count: %u\n", log->device_error_count);
1286 else {
1287 errcnt = nentries;
1288 pout("Device Error Count: %u (device log contains only the most recent %u errors)\n",
1289 log->device_error_count, errcnt);
1290 }
1291
1292 if (max_errors < errcnt)
1293 errcnt = max_errors;
1294
1295 print_off();
1296 pout("\tCR = Command Register\n"
1297 "\tFEATR = Features Register\n"
1298 "\tCOUNT = Count (was: Sector Count) Register\n"
1299 "\tLBA_48 = Upper bytes of LBA High/Mid/Low Registers ] ATA-8\n"
1300 "\tLH = LBA High (was: Cylinder High) Register ] LBA\n"
1301 "\tLM = LBA Mid (was: Cylinder Low) Register ] Register\n"
1302 "\tLL = LBA Low (was: Sector Number) Register ]\n"
1303 "\tDV = Device (was: Device/Head) Register\n"
1304 "\tDC = Device Control Register\n"
1305 "\tER = Error register\n"
1306 "\tST = Status register\n"
1307 "Powered_Up_Time is measured from power on, and printed as\n"
1308 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1309 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1310
1311 // Iterate through circular buffer in reverse direction
1312 for (unsigned i = 0, errnum = log->device_error_count;
1313 i < errcnt; i++, errnum--, erridx = (erridx > 0 ? erridx - 1 : nentries - 1)) {
1314
1315 const ata_smart_exterrlog_error_log & entry = log[erridx / 4].error_logs[erridx % 4];
1316
1317 // Skip unused entries
1318 if (!nonempty(&entry, sizeof(entry))) {
1319 pout("Error %u [%u] log entry is empty\n", errnum, erridx);
1320 continue;
1321 }
1322
1323 // Print error information
1324 print_on();
1325 const ata_smart_exterrlog_error & err = entry.error;
1326 pout("Error %u [%u] occurred at disk power-on lifetime: %u hours (%u days + %u hours)\n",
1327 errnum, erridx, err.timestamp, err.timestamp / 24, err.timestamp % 24);
1328 print_off();
1329
1330 pout(" When the command that caused the error occurred, the device was %s.\n\n",
1331 get_error_log_state_desc(err.state));
1332
1333 // Print registers
1334 pout(" After command completion occurred, registers were:\n"
1335 " ER -- ST COUNT LBA_48 LH LM LL DV DC\n"
1336 " -- -- -- == -- == == == -- -- -- -- --\n"
1337 " %02x -- %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1338 err.error_register,
1339 err.status_register,
1340 err.count_register_hi,
1341 err.count_register,
1342 err.lba_high_register_hi,
1343 err.lba_mid_register_hi,
1344 err.lba_low_register_hi,
1345 err.lba_high_register,
1346 err.lba_mid_register,
1347 err.lba_low_register,
1348 err.device_register,
1349 err.device_control_register);
1350
1351 // Add a description of the contents of the status and error registers
1352 // if possible
1353 char descbuf[256];
1354 const char * st_er_desc = construct_st_er_desc(descbuf, &entry);
1355 if (st_er_desc)
1356 pout(" %s", st_er_desc);
1357 pout("\n\n");
1358
1359 // Print command history
1360 pout(" Commands leading to the command that caused the error were:\n"
1361 " CR FEATR COUNT LBA_48 LH LM LL DV DC Powered_Up_Time Command/Feature_Name\n"
1362 " -- == -- == -- == == == -- -- -- -- -- --------------- --------------------\n");
1363 for (int ci = 4; ci >= 0; ci--) {
1364 const ata_smart_exterrlog_command & cmd = entry.commands[ci];
1365
1366 // Skip unused entries
1367 if (!nonempty(&cmd, sizeof(cmd)))
1368 continue;
1369
1370 // Print registers, timestamp and ATA command name
1371 char timestring[32];
1372 MsecToText(cmd.timestamp, timestring);
1373
1374 pout(" %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1375 cmd.command_register,
1376 cmd.features_register_hi,
1377 cmd.features_register,
1378 cmd.count_register_hi,
1379 cmd.count_register,
1380 cmd.lba_high_register_hi,
1381 cmd.lba_mid_register_hi,
1382 cmd.lba_low_register_hi,
1383 cmd.lba_high_register,
1384 cmd.lba_mid_register,
1385 cmd.lba_low_register,
1386 cmd.device_register,
1387 cmd.device_control_register,
1388 timestring,
1389 look_up_ata_command(cmd.command_register, cmd.features_register));
1390 }
1391 pout("\n");
1392 }
1393
1394 print_on();
1395 if (printing_is_switchable)
1396 pout("\n");
1397 print_off();
1398 return log->device_error_count;
1399 }
1400
1401 // Print SMART Extended Self-test Log (GP Log 0x07)
1402 static int PrintSmartExtSelfTestLog(const ata_smart_extselftestlog * log,
1403 unsigned nsectors, unsigned max_entries)
1404 {
1405 pout("SMART Extended Self-test Log Version: %u (%u sectors)\n",
1406 log->version, nsectors);
1407
1408 if (!log->log_desc_index){
1409 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
1410 return 0;
1411 }
1412
1413 // Check index
1414 unsigned nentries = nsectors * 19;
1415 unsigned logidx = log->log_desc_index;
1416 if (logidx > nentries) {
1417 pout("Invalid Self-test Log index = 0x%04x (reserved = 0x%02x)\n", logidx, log->reserved1);
1418 return 0;
1419 }
1420
1421 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1422 // it is 1-based in practice.
1423 logidx--;
1424
1425 bool print_header = true;
1426 int errcnt = 0, igncnt = 0;
1427 int ext_ok_testnum = -1;
1428
1429 // Iterate through circular buffer in reverse direction
1430 for (unsigned i = 0, testnum = 1;
1431 i < nentries && testnum <= max_entries;
1432 i++, logidx = (logidx > 0 ? logidx - 1 : nentries - 1)) {
1433
1434 const ata_smart_extselftestlog_desc & entry = log[logidx / 19].log_descs[logidx % 19];
1435
1436 // Skip unused entries
1437 if (!nonempty(&entry, sizeof(entry)))
1438 continue;
1439
1440 // Get LBA
1441 const unsigned char * b = entry.failing_lba;
1442 uint64_t lba48 = b[0]
1443 | ( b[1] << 8)
1444 | ( b[2] << 16)
1445 | ((uint64_t)b[3] << 24)
1446 | ((uint64_t)b[4] << 32)
1447 | ((uint64_t)b[5] << 40);
1448
1449 // Print entry
1450 int state = ataPrintSmartSelfTestEntry(testnum, entry.self_test_type,
1451 entry.self_test_status, entry.timestamp, lba48,
1452 false /*!print_error_only*/, print_header);
1453
1454 if (state < 0) {
1455 // Self-test showed an error
1456 if (ext_ok_testnum < 0)
1457 errcnt++;
1458 else
1459 // Newer successful extended self-test exits
1460 igncnt++;
1461 }
1462 else if (state > 0 && ext_ok_testnum < 0) {
1463 // Latest successful extended self-test
1464 ext_ok_testnum = testnum;
1465 }
1466 testnum++;
1467 }
1468
1469 if (igncnt)
1470 pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
1471 igncnt, igncnt+errcnt, ext_ok_testnum);
1472
1473 pout("\n");
1474 return errcnt;
1475 }
1476
1477 static void ataPrintSelectiveSelfTestLog(const ata_selective_self_test_log * log, const ata_smart_values * sv)
1478 {
1479 int i,field1,field2;
1480 const char *msg;
1481 char tmp[64];
1482 uint64_t maxl=0,maxr=0;
1483 uint64_t current=log->currentlba;
1484 uint64_t currentend=current+65535;
1485
1486 // print data structure revision number
1487 pout("SMART Selective self-test log data structure revision number %d\n",(int)log->logversion);
1488 if (1 != log->logversion)
1489 pout("Note: revision number not 1 implies that no selective self-test has ever been run\n");
1490
1491 switch((sv->self_test_exec_status)>>4){
1492 case 0:msg="Completed";
1493 break;
1494 case 1:msg="Aborted_by_host";
1495 break;
1496 case 2:msg="Interrupted";
1497 break;
1498 case 3:msg="Fatal_error";
1499 break;
1500 case 4:msg="Completed_unknown_failure";
1501 break;
1502 case 5:msg="Completed_electrical_failure";
1503 break;
1504 case 6:msg="Completed_servo/seek_failure";
1505 break;
1506 case 7:msg="Completed_read_failure";
1507 break;
1508 case 8:msg="Completed_handling_damage??";
1509 break;
1510 case 15:msg="Self_test_in_progress";
1511 break;
1512 default:msg="Unknown_status ";
1513 break;
1514 }
1515
1516 // find the number of columns needed for printing. If in use, the
1517 // start/end of span being read-scanned...
1518 if (log->currentspan>5) {
1519 maxl=current;
1520 maxr=currentend;
1521 }
1522 for (i=0; i<5; i++) {
1523 uint64_t start=log->span[i].start;
1524 uint64_t end =log->span[i].end;
1525 // ... plus max start/end of each of the five test spans.
1526 if (start>maxl)
1527 maxl=start;
1528 if (end > maxr)
1529 maxr=end;
1530 }
1531
1532 // we need at least 7 characters wide fields to accomodate the
1533 // labels
1534 if ((field1=snprintf(tmp,64, "%"PRIu64, maxl))<7)
1535 field1=7;
1536 if ((field2=snprintf(tmp,64, "%"PRIu64, maxr))<7)
1537 field2=7;
1538
1539 // now print the five test spans
1540 pout(" SPAN %*s %*s CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
1541
1542 for (i=0; i<5; i++) {
1543 uint64_t start=log->span[i].start;
1544 uint64_t end=log->span[i].end;
1545
1546 if ((i+1)==(int)log->currentspan)
1547 // this span is currently under test
1548 pout(" %d %*"PRIu64" %*"PRIu64" %s [%01d0%% left] (%"PRIu64"-%"PRIu64")\n",
1549 i+1, field1, start, field2, end, msg,
1550 (int)(sv->self_test_exec_status & 0xf), current, currentend);
1551 else
1552 // this span is not currently under test
1553 pout(" %d %*"PRIu64" %*"PRIu64" Not_testing\n",
1554 i+1, field1, start, field2, end);
1555 }
1556
1557 // if we are currently read-scanning, print LBAs and the status of
1558 // the read scan
1559 if (log->currentspan>5)
1560 pout("%5d %*"PRIu64" %*"PRIu64" Read_scanning %s\n",
1561 (int)log->currentspan, field1, current, field2, currentend,
1562 OfflineDataCollectionStatus(sv->offline_data_collection_status));
1563
1564 /* Print selective self-test flags. Possible flag combinations are
1565 (numbering bits from 0-15):
1566 Bit-1 Bit-3 Bit-4
1567 Scan Pending Active
1568 0 * * Don't scan
1569 1 0 0 Will carry out scan after selective test
1570 1 1 0 Waiting to carry out scan after powerup
1571 1 0 1 Currently scanning
1572 1 1 1 Currently scanning
1573 */
1574
1575 pout("Selective self-test flags (0x%x):\n", (unsigned int)log->flags);
1576 if (log->flags & SELECTIVE_FLAG_DOSCAN) {
1577 if (log->flags & SELECTIVE_FLAG_ACTIVE)
1578 pout(" Currently read-scanning the remainder of the disk.\n");
1579 else if (log->flags & SELECTIVE_FLAG_PENDING)
1580 pout(" Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
1581 (int)log->pendingtime);
1582 else
1583 pout(" After scanning selected spans, read-scan remainder of disk.\n");
1584 }
1585 else
1586 pout(" After scanning selected spans, do NOT read-scan remainder of disk.\n");
1587
1588 // print pending time
1589 pout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
1590 (int)log->pendingtime);
1591
1592 return;
1593 }
1594
1595 // Format SCT Temperature value
1596 static const char * sct_ptemp(signed char x, char * buf)
1597 {
1598 if (x == -128 /*0x80 = unknown*/)
1599 strcpy(buf, " ?");
1600 else
1601 sprintf(buf, "%2d", x);
1602 return buf;
1603 }
1604
1605 static const char * sct_pbar(int x, char * buf)
1606 {
1607 if (x <= 19)
1608 x = 0;
1609 else
1610 x -= 19;
1611 bool ov = false;
1612 if (x > 40) {
1613 x = 40; ov = true;
1614 }
1615 if (x > 0) {
1616 memset(buf, '*', x);
1617 if (ov)
1618 buf[x-1] = '+';
1619 buf[x] = 0;
1620 }
1621 else {
1622 buf[0] = '-'; buf[1] = 0;
1623 }
1624 return buf;
1625 }
1626
1627 static const char * sct_device_state_msg(unsigned char state)
1628 {
1629 switch (state) {
1630 case 0: return "Active";
1631 case 1: return "Stand-by";
1632 case 2: return "Sleep";
1633 case 3: return "DST executing in background";
1634 case 4: return "SMART Off-line Data Collection executing in background";
1635 case 5: return "SCT command executing in background";
1636 default:return "Unknown";
1637 }
1638 }
1639
1640 // Print SCT Status
1641 static int ataPrintSCTStatus(const ata_sct_status_response * sts)
1642 {
1643 pout("SCT Status Version: %u\n", sts->format_version);
1644 pout("SCT Version (vendor specific): %u (0x%04x)\n", sts->sct_version, sts->sct_version);
1645 pout("SCT Support Level: %u\n", sts->sct_spec);
1646 pout("Device State: %s (%u)\n",
1647 sct_device_state_msg(sts->device_state), sts->device_state);
1648 char buf1[20], buf2[20];
1649 if ( !sts->min_temp && !sts->life_min_temp && !sts->byte205
1650 && !sts->under_limit_count && !sts->over_limit_count ) {
1651 // "Reserved" fields not set, assume "old" format version 2
1652 // Table 11 of T13/1701DT Revision 5
1653 // Table 54 of T13/1699-D Revision 3e
1654 pout("Current Temperature: %s Celsius\n",
1655 sct_ptemp(sts->hda_temp, buf1));
1656 pout("Power Cycle Max Temperature: %s Celsius\n",
1657 sct_ptemp(sts->max_temp, buf2));
1658 pout("Lifetime Max Temperature: %s Celsius\n",
1659 sct_ptemp(sts->life_max_temp, buf2));
1660 }
1661 else {
1662 // Assume "new" format version 2 or version 3
1663 // T13/e06152r0-3 (Additional SCT Temperature Statistics)
1664 // Table 60 of T13/1699-D Revision 3f
1665 pout("Current Temperature: %s Celsius\n",
1666 sct_ptemp(sts->hda_temp, buf1));
1667 pout("Power Cycle Min/Max Temperature: %s/%s Celsius\n",
1668 sct_ptemp(sts->min_temp, buf1), sct_ptemp(sts->max_temp, buf2));
1669 pout("Lifetime Min/Max Temperature: %s/%s Celsius\n",
1670 sct_ptemp(sts->life_min_temp, buf1), sct_ptemp(sts->life_max_temp, buf2));
1671 if (sts->byte205) // e06152r0-2, removed in e06152r3
1672 pout("Lifetime Average Temperature: %s Celsius\n",
1673 sct_ptemp((signed char)sts->byte205, buf1));
1674 pout("Under/Over Temperature Limit Count: %2u/%u\n",
1675 sts->under_limit_count, sts->over_limit_count);
1676 }
1677 return 0;
1678 }
1679
1680 // Print SCT Temperature History Table
1681 static int ataPrintSCTTempHist(const ata_sct_temperature_history_table * tmh)
1682 {
1683 char buf1[20], buf2[80];
1684 pout("SCT Temperature History Version: %u\n", tmh->format_version);
1685 pout("Temperature Sampling Period: %u minute%s\n",
1686 tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
1687 pout("Temperature Logging Interval: %u minute%s\n",
1688 tmh->interval, (tmh->interval==1?"":"s"));
1689 pout("Min/Max recommended Temperature: %s/%s Celsius\n",
1690 sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
1691 pout("Min/Max Temperature Limit: %s/%s Celsius\n",
1692 sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
1693 pout("Temperature History Size (Index): %u (%u)\n", tmh->cb_size, tmh->cb_index);
1694 if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
1695 pout("Error invalid Temperature History Size or Index\n");
1696 return 0;
1697 }
1698
1699 // Print table
1700 pout("\nIndex Estimated Time Temperature Celsius\n");
1701 unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
1702 unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
1703 time_t t = time(0) - (tmh->cb_size-1) * interval * 60;
1704 t -= t % (interval * 60);
1705 while (n < tmh->cb_size) {
1706 // Find range of identical temperatures
1707 unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
1708 while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
1709 n2++; i2 = (i2+1) % tmh->cb_size;
1710 }
1711 // Print range
1712 while (n < n2) {
1713 if (n == n1 || n == n2-1 || n2 <= n1+3) {
1714 char date[30];
1715 // TODO: Don't print times < boot time
1716 strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&t));
1717 pout(" %3u %s %s %s\n", i, date,
1718 sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf2));
1719 }
1720 else if (n == n1+1) {
1721 pout(" ... ..(%3u skipped). .. %s\n",
1722 n2-n1-2, sct_pbar(tmh->cb[i], buf2));
1723 }
1724 t += interval * 60; i = (i+1) % tmh->cb_size; n++;
1725 }
1726 }
1727 //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
1728
1729 return 0;
1730 }
1731
1732 // Print SCT Error Recovery Control timers
1733 static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer)
1734 {
1735 pout("SCT Error Recovery Control%s:\n", (set ? " set to" : ""));
1736 if (!read_timer)
1737 pout(" Read: Disabled\n");
1738 else
1739 pout(" Read: %6d (%0.1f seconds)\n", read_timer, read_timer/10.0);
1740 if (!write_timer)
1741 pout(" Write: Disabled\n");
1742 else
1743 pout(" Write: %6d (%0.1f seconds)\n", write_timer, write_timer/10.0);
1744 }
1745
1746
1747 int ataPrintMain (ata_device * device, const ata_print_options & options)
1748 {
1749 // If requested, check power mode first
1750 const char * powername = 0;
1751 bool powerchg = false;
1752 if (options.powermode) {
1753 unsigned char powerlimit = 0xff;
1754 int powermode = ataCheckPowerMode(device);
1755 switch (powermode) {
1756 case -1:
1757 if (device->get_errno() == ENOSYS) {
1758 pout("CHECK POWER MODE not implemented, ignoring -n option\n"); break;
1759 }
1760 powername = "SLEEP"; powerlimit = 2;
1761 break;
1762 case 0:
1763 powername = "STANDBY"; powerlimit = 3; break;
1764 case 0x80:
1765 powername = "IDLE"; powerlimit = 4; break;
1766 case 0xff:
1767 powername = "ACTIVE or IDLE"; break;
1768 default:
1769 pout("CHECK POWER MODE returned unknown value 0x%02x, ignoring -n option\n", powermode);
1770 break;
1771 }
1772 if (powername) {
1773 if (options.powermode >= powerlimit) {
1774 pout("Device is in %s mode, exit(%d)\n", powername, FAILPOWER);
1775 return FAILPOWER;
1776 }
1777 powerchg = (powermode != 0xff); // SMART tests will spin up drives
1778 }
1779 }
1780
1781 // SMART values needed ?
1782 bool need_smart_val = (
1783 options.smart_check_status
1784 || options.smart_general_values
1785 || options.smart_vendor_attrib
1786 || options.smart_error_log
1787 || options.smart_selftest_log
1788 || options.smart_selective_selftest_log
1789 || options.smart_ext_error_log
1790 || options.smart_ext_selftest_log
1791 || options.smart_auto_offl_enable
1792 || options.smart_auto_offl_disable
1793 || options.smart_selftest_type != -1
1794 );
1795
1796 // SMART must be enabled ?
1797 bool need_smart_enabled = (
1798 need_smart_val
1799 || options.smart_auto_save_enable
1800 || options.smart_auto_save_disable
1801 );
1802
1803 // SMART feature set needed ?
1804 bool need_smart_support = (
1805 need_smart_enabled
1806 || options.smart_enable
1807 || options.smart_disable
1808 );
1809
1810 // SMART and GP log directories needed ?
1811 bool need_smart_logdir = options.smart_logdir;
1812
1813 bool need_gp_logdir = (
1814 options.gp_logdir
1815 || options.smart_ext_error_log
1816 || options.smart_ext_selftest_log
1817 || options.sataphy
1818 );
1819
1820 unsigned i;
1821 for (i = 0; i < options.log_requests.size(); i++) {
1822 if (options.log_requests[i].gpl)
1823 need_gp_logdir = true;
1824 else
1825 need_smart_logdir = true;
1826 }
1827
1828 // SCT commands needed ?
1829 bool need_sct_support = (
1830 options.sct_temp_sts
1831 || options.sct_temp_hist
1832 || options.sct_temp_int
1833 || options.sct_erc_get
1834 || options.sct_erc_set
1835 );
1836
1837 // Exit if no further options specified
1838 if (!( options.drive_info || need_smart_support
1839 || need_smart_logdir || need_gp_logdir
1840 || need_sct_support )) {
1841 if (powername)
1842 pout("Device is in %s mode\n", powername);
1843 else
1844 pout("ATA device successfully opened\n\n"
1845 "Use 'smartctl -a' (or '-x') to print SMART (and more) information\n\n");
1846 return 0;
1847 }
1848
1849 // Start by getting Drive ID information. We need this, to know if SMART is supported.
1850 int returnval = 0;
1851 ata_identify_device drive; memset(&drive, 0, sizeof(drive));
1852 device->clear_err();
1853 int retid = ata_read_identity(device, &drive, options.fix_swapped_id);
1854 if (retid < 0) {
1855 pout("Smartctl: Device Read Identity Failed: %s\n\n",
1856 (device->get_errno() ? device->get_errmsg() : "Unknown error"));
1857 failuretest(MANDATORY_CMD, returnval|=FAILID);
1858 }
1859 else if (!nonempty(&drive, sizeof(drive))) {
1860 pout("Smartctl: Device Read Identity Failed: empty IDENTIFY data\n\n");
1861 failuretest(MANDATORY_CMD, returnval|=FAILID);
1862 }
1863
1864 // If requested, show which presets would be used for this drive and exit.
1865 if (options.show_presets) {
1866 show_presets(&drive);
1867 return 0;
1868 }
1869
1870 // Use preset vendor attribute options unless user has requested otherwise.
1871 ata_vendor_attr_defs attribute_defs = options.attribute_defs;
1872 unsigned char fix_firmwarebug = options.fix_firmwarebug;
1873 const drive_settings * dbentry = 0;
1874 if (!options.ignore_presets)
1875 dbentry = lookup_drive_apply_presets(&drive, attribute_defs,
1876 fix_firmwarebug);
1877
1878 // Get capacity and sector sizes
1879 ata_size_info sizes;
1880 ata_get_size_info(&drive, sizes);
1881
1882 // Print most drive identity information if requested
1883 if (options.drive_info) {
1884 pout("=== START OF INFORMATION SECTION ===\n");
1885 print_drive_info(&drive, sizes, dbentry);
1886 }
1887
1888 // Check and print SMART support and state
1889 int smart_supported = -1, smart_enabled = -1;
1890 if (need_smart_support || options.drive_info) {
1891
1892 // Packet device ?
1893 if (retid > 0) {
1894 pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
1895 packetdevicetype(retid-1));
1896 }
1897 else {
1898 // Disk device: SMART supported and enabled ?
1899 smart_supported = ataSmartSupport(&drive);
1900 smart_enabled = ataIsSmartEnabled(&drive);
1901
1902 if (smart_supported < 0)
1903 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
1904 if (smart_supported && smart_enabled < 0) {
1905 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
1906 if (need_smart_support) {
1907 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1908 // check SMART support by trying a command
1909 pout(" Checking to be sure by trying SMART RETURN STATUS command.\n");
1910 if (ataDoesSmartWork(device))
1911 smart_supported = smart_enabled = 1;
1912 }
1913 }
1914 else if (smart_supported < 0 && (smart_enabled > 0 || dbentry))
1915 // Assume supported if enabled or in drive database
1916 smart_supported = 1;
1917
1918 if (smart_supported < 0)
1919 pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
1920 else if (!smart_supported)
1921 pout("SMART support is: Unavailable - device lacks SMART capability.\n");
1922 else {
1923 if (options.drive_info)
1924 pout("SMART support is: Available - device has SMART capability.\n");
1925 if (smart_enabled >= 0) {
1926 if (device->ata_identify_is_cached()) {
1927 if (options.drive_info)
1928 pout(" %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
1929 (smart_enabled?"En":"Dis"));
1930 smart_enabled = ataDoesSmartWork(device);
1931 }
1932 if (options.drive_info)
1933 pout("SMART support is: %s\n",
1934 (smart_enabled ? "Enabled" : "Disabled"));
1935 }
1936 }
1937 }
1938 }
1939
1940 // Print remaining drive info
1941 if (options.drive_info) {
1942 // Print the (now possibly changed) power mode if available
1943 if (powername)
1944 pout("Power mode %s %s\n", (powerchg?"was:":"is: "), powername);
1945 pout("\n");
1946 }
1947
1948 // Exit if SMART is not supported but must be available to proceed
1949 if (smart_supported <= 0 && need_smart_support)
1950 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1951
1952 // START OF THE ENABLE/DISABLE SECTION OF THE CODE
1953 if ( options.smart_disable || options.smart_enable
1954 || options.smart_auto_save_disable || options.smart_auto_save_enable
1955 || options.smart_auto_offl_disable || options.smart_auto_offl_enable)
1956 pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
1957
1958 // Enable/Disable SMART commands
1959 if (options.smart_enable) {
1960 if (ataEnableSmart(device)) {
1961 pout("Smartctl: SMART Enable Failed.\n\n");
1962 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1963 }
1964 else {
1965 pout("SMART Enabled.\n");
1966 smart_enabled = 1;
1967 }
1968 }
1969
1970 // Turn off SMART on device
1971 if (options.smart_disable) {
1972 if (ataDisableSmart(device)) {
1973 pout( "Smartctl: SMART Disable Failed.\n\n");
1974 failuretest(MANDATORY_CMD,returnval|=FAILSMART);
1975 }
1976 }
1977
1978 // Exit if SMART is disabled but must be enabled to proceed
1979 if (options.smart_disable || (smart_enabled <= 0 && need_smart_enabled)) {
1980 pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
1981 return returnval;
1982 }
1983
1984 // Enable/Disable Auto-save attributes
1985 if (options.smart_auto_save_enable) {
1986 if (ataEnableAutoSave(device)){
1987 pout( "Smartctl: SMART Enable Attribute Autosave Failed.\n\n");
1988 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1989 }
1990 else
1991 pout("SMART Attribute Autosave Enabled.\n");
1992 }
1993
1994 if (options.smart_auto_save_disable) {
1995 if (ataDisableAutoSave(device)){
1996 pout( "Smartctl: SMART Disable Attribute Autosave Failed.\n\n");
1997 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1998 }
1999 else
2000 pout("SMART Attribute Autosave Disabled.\n");
2001 }
2002
2003 // Read SMART values and thresholds if necessary
2004 ata_smart_values smartval; memset(&smartval, 0, sizeof(smartval));
2005 ata_smart_thresholds_pvt smartthres; memset(&smartthres, 0, sizeof(smartthres));
2006 bool smart_val_ok = false, smart_thres_ok = false;
2007
2008 if (need_smart_val) {
2009 if (ataReadSmartValues(device, &smartval)) {
2010 pout("Smartctl: SMART Read Values failed.\n\n");
2011 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2012 }
2013 else {
2014 smart_val_ok = true;
2015
2016 if (options.smart_check_status || options.smart_vendor_attrib) {
2017 if (ataReadSmartThresholds(device, &smartthres)){
2018 pout("Smartctl: SMART Read Thresholds failed.\n\n");
2019 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2020 }
2021 else
2022 smart_thres_ok = true;
2023 }
2024 }
2025 }
2026
2027 // Enable/Disable Off-line testing
2028 bool needupdate = false;
2029 if (options.smart_auto_offl_enable) {
2030 if (!isSupportAutomaticTimer(&smartval)){
2031 pout("Warning: device does not support SMART Automatic Timers.\n\n");
2032 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2033 }
2034 needupdate = smart_val_ok;
2035 if (ataEnableAutoOffline(device)){
2036 pout( "Smartctl: SMART Enable Automatic Offline Failed.\n\n");
2037 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2038 }
2039 else
2040 pout("SMART Automatic Offline Testing Enabled every four hours.\n");
2041 }
2042
2043 if (options.smart_auto_offl_disable) {
2044 if (!isSupportAutomaticTimer(&smartval)){
2045 pout("Warning: device does not support SMART Automatic Timers.\n\n");
2046 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2047 }
2048 needupdate = smart_val_ok;
2049 if (ataDisableAutoOffline(device)){
2050 pout("Smartctl: SMART Disable Automatic Offline Failed.\n\n");
2051 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2052 }
2053 else
2054 pout("SMART Automatic Offline Testing Disabled.\n");
2055 }
2056
2057 if (needupdate && ataReadSmartValues(device, &smartval)){
2058 pout("Smartctl: SMART Read Values failed.\n\n");
2059 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2060 smart_val_ok = false;
2061 }
2062
2063 // all this for a newline!
2064 if ( options.smart_disable || options.smart_enable
2065 || options.smart_auto_save_disable || options.smart_auto_save_enable
2066 || options.smart_auto_offl_disable || options.smart_auto_offl_enable)
2067 pout("\n");
2068
2069 // START OF READ-ONLY OPTIONS APART FROM -V and -i
2070 if ( options.smart_check_status || options.smart_general_values
2071 || options.smart_vendor_attrib || options.smart_error_log
2072 || options.smart_selftest_log || options.smart_selective_selftest_log
2073 || options.smart_ext_error_log || options.smart_ext_selftest_log
2074 || options.sct_temp_sts || options.sct_temp_hist )
2075 pout("=== START OF READ SMART DATA SECTION ===\n");
2076
2077 // Check SMART status
2078 if (options.smart_check_status) {
2079
2080 switch (ataSmartStatus2(device)) {
2081
2082 case 0:
2083 // The case where the disk health is OK
2084 pout("SMART overall-health self-assessment test result: PASSED\n");
2085 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2086 if (options.smart_vendor_attrib)
2087 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
2088 else {
2089 print_on();
2090 pout("Please note the following marginal Attributes:\n");
2091 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 2, options.output_format);
2092 }
2093 returnval|=FAILAGE;
2094 }
2095 else
2096 pout("\n");
2097 break;
2098
2099 case 1:
2100 // The case where the disk health is NOT OK
2101 print_on();
2102 pout("SMART overall-health self-assessment test result: FAILED!\n"
2103 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
2104 print_off();
2105 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
2106 returnval|=FAILATTR;
2107 if (options.smart_vendor_attrib)
2108 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
2109 else {
2110 print_on();
2111 pout("Failed Attributes:\n");
2112 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 1, options.output_format);
2113 }
2114 }
2115 else
2116 pout("No failed Attributes found.\n\n");
2117 returnval|=FAILSTATUS;
2118 print_off();
2119 break;
2120
2121 case -1:
2122 default:
2123 // Something went wrong with the SMART STATUS command.
2124 // The ATA SMART RETURN STATUS command provides the result in the ATA output
2125 // registers. Buggy ATA/SATA drivers and SAT Layers often do not properly
2126 // return the registers values.
2127 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2128 if (!(smart_val_ok && smart_thres_ok)) {
2129 print_on();
2130 pout("SMART overall-health self-assessment test result: UNKNOWN!\n"
2131 "SMART Status, Attributes and Thresholds cannot be read.\n\n");
2132 }
2133 else if (find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
2134 print_on();
2135 pout("SMART overall-health self-assessment test result: FAILED!\n"
2136 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
2137 print_off();
2138 returnval|=FAILATTR;
2139 returnval|=FAILSTATUS;
2140 if (options.smart_vendor_attrib)
2141 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
2142 else {
2143 print_on();
2144 pout("Failed Attributes:\n");
2145 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 1, options.output_format);
2146 }
2147 }
2148 else {
2149 pout("SMART overall-health self-assessment test result: PASSED\n");
2150 pout("Warning: This result is based on an Attribute check.\n");
2151 if (find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2152 if (options.smart_vendor_attrib)
2153 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
2154 else {
2155 print_on();
2156 pout("Please note the following marginal Attributes:\n");
2157 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 2, options.output_format);
2158 }
2159 returnval|=FAILAGE;
2160 }
2161 else
2162 pout("\n");
2163 }
2164 print_off();
2165 break;
2166 } // end of switch statement
2167
2168 print_off();
2169 } // end of checking SMART Status
2170
2171 // Print general SMART values
2172 if (smart_val_ok && options.smart_general_values)
2173 PrintGeneralSmartValues(&smartval, &drive, fix_firmwarebug);
2174
2175 // Print vendor-specific attributes
2176 if (smart_val_ok && options.smart_vendor_attrib) {
2177 print_on();
2178 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs,
2179 (printing_is_switchable ? 2 : 0), options.output_format);
2180 print_off();
2181 }
2182
2183 // If GP Log is supported use smart log directory for
2184 // error and selftest log support check.
2185 if ( isGeneralPurposeLoggingCapable(&drive)
2186 && ( options.smart_error_log || options.smart_selftest_log
2187 || options.retry_error_log || options.retry_selftest_log))
2188 need_smart_logdir = true;
2189
2190 ata_smart_log_directory smartlogdir_buf, gplogdir_buf;
2191 const ata_smart_log_directory * smartlogdir = 0, * gplogdir = 0;
2192
2193 // Read SMART Log directory
2194 if (need_smart_logdir) {
2195 if (ataReadLogDirectory(device, &smartlogdir_buf, false)) {
2196 pout("Read SMART Log Directory failed.\n\n");
2197 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2198 }
2199 else
2200 smartlogdir = &smartlogdir_buf;
2201 }
2202
2203 // Read GP Log directory
2204 if (need_gp_logdir) {
2205 if (ataReadLogDirectory(device, &gplogdir_buf, true)) {
2206 pout("Read GP Log Directory failed.\n\n");
2207 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2208 }
2209 else
2210 gplogdir = &gplogdir_buf;
2211 }
2212
2213 // Print log directories
2214 if ((options.gp_logdir && gplogdir) || (options.smart_logdir && smartlogdir))
2215 PrintLogDirectories(gplogdir, smartlogdir);
2216
2217 // Print log pages
2218 for (i = 0; i < options.log_requests.size(); i++) {
2219 const ata_log_request & req = options.log_requests[i];
2220
2221 const char * type;
2222 unsigned max_nsectors;
2223 if (req.gpl) {
2224 type = "General Purpose";
2225 max_nsectors = GetNumLogSectors(gplogdir, req.logaddr, true);
2226 }
2227 else {
2228 type = "SMART";
2229 max_nsectors = GetNumLogSectors(smartlogdir, req.logaddr, false);
2230 }
2231
2232 if (!max_nsectors) {
2233 if (!is_permissive()) {
2234 pout("%s Log 0x%02x does not exist (override with '-T permissive' option)\n", type, req.logaddr);
2235 continue;
2236 }
2237 max_nsectors = req.page+1;
2238 }
2239 if (max_nsectors <= req.page) {
2240 pout("%s Log 0x%02x has only %u sectors, output skipped\n", type, req.logaddr, max_nsectors);
2241 continue;
2242 }
2243
2244 unsigned ns = req.nsectors;
2245 if (ns > max_nsectors - req.page) {
2246 if (req.nsectors != ~0U) // "FIRST-max"
2247 pout("%s Log 0x%02x has only %u sectors, output truncated\n", type, req.logaddr, max_nsectors);
2248 ns = max_nsectors - req.page;
2249 }
2250
2251 // SMART log don't support sector offset, start with first sector
2252 unsigned offs = (req.gpl ? 0 : req.page);
2253
2254 raw_buffer log_buf((offs + ns) * 512);
2255 bool ok;
2256 if (req.gpl)
2257 ok = ataReadLogExt(device, req.logaddr, 0x00, req.page, log_buf.data(), ns);
2258 else
2259 ok = ataReadSmartLog(device, req.logaddr, log_buf.data(), offs + ns);
2260 if (!ok)
2261 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2262 else
2263 PrintLogPages(type, log_buf.data() + offs*512, req.logaddr, req.page, ns, max_nsectors);
2264 }
2265
2266 // Print SMART Extendend Comprehensive Error Log
2267 bool do_smart_error_log = options.smart_error_log;
2268 if (options.smart_ext_error_log) {
2269 bool ok = false;
2270 unsigned nsectors = GetNumLogSectors(gplogdir, 0x03, true);
2271 if (!nsectors)
2272 pout("SMART Extended Comprehensive Error Log (GP Log 0x03) not supported\n");
2273 else if (nsectors >= 256)
2274 pout("SMART Extended Comprehensive Error Log size %u not supported\n", nsectors);
2275 else {
2276 raw_buffer log_03_buf(nsectors * 512);
2277 ata_smart_exterrlog * log_03 = (ata_smart_exterrlog *)log_03_buf.data();
2278 if (!ataReadExtErrorLog(device, log_03, nsectors))
2279 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2280 else {
2281 if (PrintSmartExtErrorLog(log_03, nsectors, options.smart_ext_error_log))
2282 returnval |= FAILERR;
2283 ok = true;
2284 }
2285 }
2286
2287 if (!ok) {
2288 if (options.retry_error_log)
2289 do_smart_error_log = true;
2290 else if (!do_smart_error_log)
2291 pout("Try '-l [xerror,]error' to read traditional SMART Error Log\n");
2292 }
2293 }
2294
2295 // Print SMART error log
2296 if (do_smart_error_log) {
2297 if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x01, false))
2298 || (!smartlogdir && isSmartErrorLogCapable(&smartval, &drive) )
2299 || is_permissive() )) {
2300 pout("SMART Error Log not supported\n");
2301 }
2302 else {
2303 ata_smart_errorlog smarterror; memset(&smarterror, 0, sizeof(smarterror));
2304 if (ataReadErrorLog(device, &smarterror, fix_firmwarebug)) {
2305 pout("Smartctl: SMART Error Log Read Failed\n");
2306 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2307 }
2308 else {
2309 // quiet mode is turned on inside PrintSmartErrorLog()
2310 if (PrintSmartErrorlog(&smarterror, fix_firmwarebug))
2311 returnval|=FAILERR;
2312 print_off();
2313 }
2314 }
2315 }
2316
2317 // Print SMART Extendend Self-test Log
2318 bool do_smart_selftest_log = options.smart_selftest_log;
2319 if (options.smart_ext_selftest_log) {
2320 bool ok = false;
2321 unsigned nsectors = GetNumLogSectors(gplogdir, 0x07, true);
2322 if (!nsectors)
2323 pout("SMART Extended Self-test Log (GP Log 0x07) not supported\n");
2324 else if (nsectors >= 256)
2325 pout("SMART Extended Self-test Log size %u not supported\n", nsectors);
2326 else {
2327 raw_buffer log_07_buf(nsectors * 512);
2328 ata_smart_extselftestlog * log_07 = (ata_smart_extselftestlog *)log_07_buf.data();
2329 if (!ataReadExtSelfTestLog(device, log_07, nsectors))
2330 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2331 else {
2332 if (PrintSmartExtSelfTestLog(log_07, nsectors, options.smart_ext_selftest_log))
2333 returnval |= FAILLOG;
2334 ok = true;
2335 }
2336 }
2337
2338 if (!ok) {
2339 if (options.retry_selftest_log)
2340 do_smart_selftest_log = true;
2341 else if (!do_smart_selftest_log)
2342 pout("Try '-l [xselftest,]selftest' to read traditional SMART Self Test Log\n");
2343 }
2344 }
2345
2346 // Print SMART self-test log
2347 if (do_smart_selftest_log) {
2348 if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x06, false))
2349 || (!smartlogdir && isSmartTestLogCapable(&smartval, &drive) )
2350 || is_permissive() )) {
2351 pout("SMART Self-test Log not supported\n");
2352 }
2353 else {
2354 ata_smart_selftestlog smartselftest; memset(&smartselftest, 0, sizeof(smartselftest));
2355 if (ataReadSelfTestLog(device, &smartselftest, fix_firmwarebug)) {
2356 pout("Smartctl: SMART Self Test Log Read Failed\n");
2357 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2358 }
2359 else {
2360 print_on();
2361 if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, fix_firmwarebug))
2362 returnval |= FAILLOG;
2363 print_off();
2364 pout("\n");
2365 }
2366 }
2367 }
2368
2369 // Print SMART selective self-test log
2370 if (options.smart_selective_selftest_log) {
2371 ata_selective_self_test_log log;
2372
2373 if (!isSupportSelectiveSelfTest(&smartval))
2374 pout("Device does not support Selective Self Tests/Logging\n");
2375 else if(ataReadSelectiveSelfTestLog(device, &log)) {
2376 pout("Smartctl: SMART Selective Self Test Log Read Failed\n");
2377 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2378 }
2379 else {
2380 print_on();
2381 // If any errors were found, they are logged in the SMART Self-test log.
2382 // So there is no need to print the Selective Self Test log in silent
2383 // mode.
2384 if (!printing_is_switchable)
2385 ataPrintSelectiveSelfTestLog(&log, &smartval);
2386 print_off();
2387 pout("\n");
2388 }
2389 }
2390
2391 // SCT commands
2392 bool sct_ok = false;
2393 if (need_sct_support) {
2394 if (!isSCTCapable(&drive)) {
2395 pout("Warning: device does not support SCT Commands\n");
2396 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2397 }
2398 else
2399 sct_ok = true;
2400 }
2401
2402 // Print SCT status and temperature history table
2403 if (sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int)) {
2404 for (;;) {
2405 if (options.sct_temp_sts || options.sct_temp_hist) {
2406 ata_sct_status_response sts;
2407 ata_sct_temperature_history_table tmh;
2408 if (!options.sct_temp_hist) {
2409 // Read SCT status only
2410 if (ataReadSCTStatus(device, &sts)) {
2411 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2412 break;
2413 }
2414 }
2415 else {
2416 if (!isSCTDataTableCapable(&drive)) {
2417 pout("Warning: device does not support SCT Data Table command\n");
2418 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2419 break;
2420 }
2421 // Read SCT status and temperature history
2422 if (ataReadSCTTempHist(device, &tmh, &sts)) {
2423 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2424 break;
2425 }
2426 }
2427 if (options.sct_temp_sts)
2428 ataPrintSCTStatus(&sts);
2429 if (options.sct_temp_hist)
2430 ataPrintSCTTempHist(&tmh);
2431 pout("\n");
2432 }
2433 if (options.sct_temp_int) {
2434 // Set new temperature logging interval
2435 if (!isSCTFeatureControlCapable(&drive)) {
2436 pout("Warning: device does not support SCT Feature Control command\n");
2437 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2438 break;
2439 }
2440 if (ataSetSCTTempInterval(device, options.sct_temp_int, options.sct_temp_int_pers)) {
2441 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2442 break;
2443 }
2444 pout("Temperature Logging Interval set to %u minute%s (%s)\n",
2445 options.sct_temp_int, (options.sct_temp_int == 1 ? "" : "s"),
2446 (options.sct_temp_int_pers ? "persistent" : "volatile"));
2447 }
2448 break;
2449 }
2450 }
2451
2452 // SCT Error Recovery Control
2453 if (sct_ok && (options.sct_erc_get || options.sct_erc_set)) {
2454 if (!isSCTErrorRecoveryControlCapable(&drive)) {
2455 pout("Warning: device does not support SCT Error Recovery Control command\n");
2456 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2457 }
2458 else {
2459 bool sct_erc_get = options.sct_erc_get;
2460 if (options.sct_erc_set) {
2461 // Set SCT Error Recovery Control
2462 if ( ataSetSCTErrorRecoveryControltime(device, 1, options.sct_erc_readtime )
2463 || ataSetSCTErrorRecoveryControltime(device, 2, options.sct_erc_writetime)) {
2464 pout("Warning: device does not support SCT (Set) Error Recovery Control command\n");
2465 if (!( (options.sct_erc_readtime == 70 && options.sct_erc_writetime == 70)
2466 || (options.sct_erc_readtime == 0 && options.sct_erc_writetime == 0)))
2467 pout("Retry with: 'scterc,70,70' to enable ERC or 'scterc,0,0' to disable\n");
2468 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2469 sct_erc_get = false;
2470 }
2471 else if (!sct_erc_get)
2472 ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
2473 options.sct_erc_writetime);
2474 }
2475
2476 if (sct_erc_get) {
2477 // Print SCT Error Recovery Control
2478 unsigned short read_timer, write_timer;
2479 if ( ataGetSCTErrorRecoveryControltime(device, 1, read_timer )
2480 || ataGetSCTErrorRecoveryControltime(device, 2, write_timer)) {
2481 pout("Warning: device does not support SCT (Get) Error Recovery Control command\n");
2482 if (options.sct_erc_set) {
2483 pout("The previous SCT (Set) Error Recovery Control command succeeded\n");
2484 ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
2485 options.sct_erc_writetime);
2486 }
2487 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2488 }
2489 else
2490 ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer);
2491 }
2492 pout("\n");
2493 }
2494 }
2495
2496 // Print SATA Phy Event Counters
2497 if (options.sataphy) {
2498 unsigned nsectors = GetNumLogSectors(gplogdir, 0x11, true);
2499 if (!nsectors)
2500 pout("SATA Phy Event Counters (GP Log 0x11) not supported\n");
2501 else if (nsectors != 1)
2502 pout("SATA Phy Event Counters with %u sectors not supported\n", nsectors);
2503 else {
2504 unsigned char log_11[512] = {0, };
2505 unsigned char features = (options.sataphy_reset ? 0x01 : 0x00);
2506 if (!ataReadLogExt(device, 0x11, features, 0, log_11, 1))
2507 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2508 else
2509 PrintSataPhyEventCounters(log_11, options.sataphy_reset);
2510 }
2511 }
2512
2513 // START OF THE TESTING SECTION OF THE CODE. IF NO TESTING, RETURN
2514 if (!smart_val_ok || options.smart_selftest_type == -1)
2515 return returnval;
2516
2517 pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
2518 // if doing a self-test, be sure it's supported by the hardware
2519 switch (options.smart_selftest_type) {
2520 case OFFLINE_FULL_SCAN:
2521 if (!isSupportExecuteOfflineImmediate(&smartval)){
2522 pout("Warning: device does not support Execute Offline Immediate function.\n\n");
2523 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2524 }
2525 break;
2526 case ABORT_SELF_TEST:
2527 case SHORT_SELF_TEST:
2528 case EXTEND_SELF_TEST:
2529 case SHORT_CAPTIVE_SELF_TEST:
2530 case EXTEND_CAPTIVE_SELF_TEST:
2531 if (!isSupportSelfTest(&smartval)){
2532 pout("Warning: device does not support Self-Test functions.\n\n");
2533 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2534 }
2535 break;
2536 case CONVEYANCE_SELF_TEST:
2537 case CONVEYANCE_CAPTIVE_SELF_TEST:
2538 if (!isSupportConveyanceSelfTest(&smartval)){
2539 pout("Warning: device does not support Conveyance Self-Test functions.\n\n");
2540 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2541 }
2542 break;
2543 case SELECTIVE_SELF_TEST:
2544 case SELECTIVE_CAPTIVE_SELF_TEST:
2545 if (!isSupportSelectiveSelfTest(&smartval)){
2546 pout("Warning: device does not support Selective Self-Test functions.\n\n");
2547 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2548 }
2549 break;
2550 default:
2551 break; // Vendor specific type
2552 }
2553
2554 // Now do the test. Note ataSmartTest prints its own error/success
2555 // messages
2556 if (ataSmartTest(device, options.smart_selftest_type, options.smart_selective_args,
2557 &smartval, sizes.sectors ))
2558 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2559 else {
2560 // Tell user how long test will take to complete. This is tricky
2561 // because in the case of an Offline Full Scan, the completion
2562 // timer is volatile, and needs to be read AFTER the command is
2563 // given. If this will interrupt the Offline Full Scan, we don't
2564 // do it, just warn user.
2565 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
2566 if (isSupportOfflineAbort(&smartval))
2567 pout("Note: giving further SMART commands will abort Offline testing\n");
2568 else if (ataReadSmartValues(device, &smartval)){
2569 pout("Smartctl: SMART Read Values failed.\n");
2570 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2571 }
2572 }
2573
2574 // Now say how long the test will take to complete
2575 int timewait = TestTime(&smartval, options.smart_selftest_type);
2576 if (timewait) {
2577 time_t t=time(NULL);
2578 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
2579 t+=timewait;
2580 pout("Please wait %d seconds for test to complete.\n", (int)timewait);
2581 } else {
2582 t+=timewait*60;
2583 pout("Please wait %d minutes for test to complete.\n", (int)timewait);
2584 }
2585 pout("Test will complete after %s\n", ctime(&t));
2586
2587 if ( options.smart_selftest_type != SHORT_CAPTIVE_SELF_TEST
2588 && options.smart_selftest_type != EXTEND_CAPTIVE_SELF_TEST
2589 && options.smart_selftest_type != CONVEYANCE_CAPTIVE_SELF_TEST
2590 && options.smart_selftest_type != SELECTIVE_CAPTIVE_SELF_TEST )
2591 pout("Use smartctl -X to abort test.\n");
2592 }
2593 }
2594
2595 return returnval;
2596 }