Annotation of embedaddon/smartmontools/ataprint.cpp, revision 1.1.1.4

1.1       misho       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>
1.1.1.3   misho       7:  * Copyright (C) 2008-13 Christian Franke <smartmontools-support@lists.sourceforge.net>
1.1       misho       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
1.1.1.3   misho      16:  * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
1.1       misho      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: 
                     25: #include "config.h"
                     26: 
                     27: #include <ctype.h>
                     28: #include <errno.h>
                     29: #include <stdio.h>
                     30: #include <stdlib.h>
                     31: #include <string.h>
                     32: 
                     33: #include "int64.h"
                     34: #include "atacmdnames.h"
                     35: #include "atacmds.h"
1.1.1.3   misho      36: #include "ataidentify.h"
1.1       misho      37: #include "dev_interface.h"
                     38: #include "ataprint.h"
                     39: #include "smartctl.h"
                     40: #include "utility.h"
                     41: #include "knowndrives.h"
                     42: 
1.1.1.4 ! misho      43: const char * ataprint_cpp_cvsid = "$Id: ataprint.cpp 3831 2013-07-20 14:25:56Z chrfranke $"
1.1       misho      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
1.1.1.3   misho      63:  * Register (ST) and Error Register (ER).  If the meanings of the flags of
                     64:  * the error register are not known for the given command then it returns an
                     65:  * empty string.
1.1       misho      66:  *
                     67:  * The meanings of the flags of the error register for all commands are
                     68:  * described in the ATA spec and could all be supported here in theory.
                     69:  * Currently, only a few commands are supported (those that have been seen
                     70:  * to produce errors).  If many more are to be added then this function
                     71:  * should probably be redesigned.
                     72:  */
                     73: 
1.1.1.3   misho      74: static std::string format_st_er_desc(
1.1       misho      75:   unsigned char CR, unsigned char FR,
                     76:   unsigned char ST, unsigned char ER,
                     77:   unsigned short SC,
                     78:   const ata_smart_errorlog_error_struct * lba28_regs,
                     79:   const ata_smart_exterrlog_error * lba48_regs
                     80: )
                     81: {
                     82:   const char *error_flag[8];
                     83:   int i, print_lba=0, print_sector=0;
                     84: 
                     85:   // Set of character strings corresponding to different error codes.
                     86:   // Please keep in alphabetic order if you add more.
                     87:   const char  *abrt  = "ABRT";  // ABORTED
                     88:  const char   *amnf  = "AMNF";  // ADDRESS MARK NOT FOUND
                     89:  const char   *ccto  = "CCTO";  // COMMAND COMPLETION TIMED OUT
                     90:  const char   *eom   = "EOM";   // END OF MEDIA
                     91:  const char   *icrc  = "ICRC";  // INTERFACE CRC ERROR
                     92:  const char   *idnf  = "IDNF";  // ID NOT FOUND
                     93:  const char   *ili   = "ILI";   // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
                     94:  const char   *mc    = "MC";    // MEDIA CHANGED 
                     95:  const char   *mcr   = "MCR";   // MEDIA CHANGE REQUEST
                     96:  const char   *nm    = "NM";    // NO MEDIA
                     97:  const char   *obs   = "obs";   // OBSOLETE
                     98:  const char   *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
                     99:  const char   *unc   = "UNC";   // UNCORRECTABLE
                    100:  const char   *wp    = "WP";    // WRITE PROTECTED
                    101: 
                    102:   /* If for any command the Device Fault flag of the status register is
                    103:    * not used then used_device_fault should be set to 0 (in the CR switch
                    104:    * below)
                    105:    */
                    106:   int uses_device_fault = 1;
                    107: 
                    108:   /* A value of NULL means that the error flag isn't used */
                    109:   for (i = 0; i < 8; i++)
                    110:     error_flag[i] = NULL;
                    111: 
1.1.1.3   misho     112:   std::string str;
                    113: 
1.1       misho     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:
1.1.1.3   misho     284:       return str; // ""
1.1       misho     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:
1.1.1.3   misho     294:       return str; // ""
1.1       misho     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:
1.1.1.3   misho     323:     return str; // ""
1.1       misho     324:   }
                    325: 
                    326:   /* We ignore any status flags other than Device Fault and Error */
                    327: 
                    328:   if (uses_device_fault && (ST & (1 << 5))) {
1.1.1.3   misho     329:     str = "Device Fault";
1.1       misho     330:     if (ST & 1)  // Error flag
1.1.1.3   misho     331:       str += "; ";
1.1       misho     332:   }
                    333:   if (ST & 1) {  // Error flag
                    334:     int count = 0;
                    335: 
1.1.1.3   misho     336:     str += "Error: ";
1.1       misho     337:     for (i = 7; i >= 0; i--)
                    338:       if ((ER & (1 << i)) && (error_flag[i])) {
                    339:         if (count++ > 0)
1.1.1.3   misho     340:            str += ", ";
                    341:         str += error_flag[i];
1.1       misho     342:       }
                    343:   }
                    344: 
                    345:   // If the error was a READ or WRITE error, print the Logical Block
                    346:   // Address (LBA) at which the read or write failed.
                    347:   if (print_lba) {
                    348:     // print number of sectors, if known, and append to print string
1.1.1.3   misho     349:     if (print_sector)
                    350:       str += strprintf(" %d sectors", print_sector);
1.1       misho     351: 
                    352:     if (lba28_regs) {
                    353:       unsigned lba;
                    354:       // bits 24-27: bits 0-3 of DH
                    355:       lba   = 0xf & lba28_regs->drive_head;
                    356:       lba <<= 8;
                    357:       // bits 16-23: CH
                    358:       lba  |= lba28_regs->cylinder_high;
                    359:       lba <<= 8;
                    360:       // bits 8-15:  CL
                    361:       lba  |= lba28_regs->cylinder_low;
                    362:       lba <<= 8;
                    363:       // bits 0-7:   SN
                    364:       lba  |= lba28_regs->sector_number;
1.1.1.3   misho     365:       str += strprintf(" at LBA = 0x%08x = %u", lba, lba);
1.1       misho     366:     }
                    367:     else if (lba48_regs) {
                    368:       // This assumes that upper LBA registers are 0 for 28-bit commands
                    369:       // (TODO: detect 48-bit commands above)
                    370:       uint64_t lba48;
                    371:       lba48   = lba48_regs->lba_high_register_hi;
                    372:       lba48 <<= 8;
                    373:       lba48  |= lba48_regs->lba_mid_register_hi;
                    374:       lba48 <<= 8;
                    375:       lba48  |= lba48_regs->lba_low_register_hi;
                    376:       lba48  |= lba48_regs->device_register & 0xf;
                    377:       lba48 <<= 8;
                    378:       lba48  |= lba48_regs->lba_high_register;
                    379:       lba48 <<= 8;
                    380:       lba48  |= lba48_regs->lba_mid_register;
                    381:       lba48 <<= 8;
                    382:       lba48  |= lba48_regs->lba_low_register;
1.1.1.3   misho     383:       str += strprintf(" at LBA = 0x%08"PRIx64" = %"PRIu64, lba48, lba48);
1.1       misho     384:     }
                    385:   }
                    386: 
1.1.1.3   misho     387:   return str;
1.1       misho     388: }
                    389: 
1.1.1.3   misho     390: static inline std::string format_st_er_desc(
1.1       misho     391:   const ata_smart_errorlog_struct * data)
                    392: {
1.1.1.3   misho     393:   return format_st_er_desc(
1.1       misho     394:     data->commands[4].commandreg,
                    395:     data->commands[4].featuresreg,
                    396:     data->error_struct.status,
                    397:     data->error_struct.error_register,
                    398:     data->error_struct.sector_count,
                    399:     &data->error_struct, (const ata_smart_exterrlog_error *)0);
                    400: }
                    401: 
1.1.1.3   misho     402: static inline std::string format_st_er_desc(
1.1       misho     403:   const ata_smart_exterrlog_error_log * data)
                    404: {
1.1.1.3   misho     405:   return format_st_er_desc(
1.1       misho     406:     data->commands[4].command_register,
                    407:     data->commands[4].features_register,
                    408:     data->error.status_register,
                    409:     data->error.error_register,
                    410:     data->error.count_register_hi << 8 | data->error.count_register,
                    411:     (const ata_smart_errorlog_error_struct *)0, &data->error);
                    412: }
                    413: 
1.1.1.3   misho     414: 
                    415: static int find_msb(unsigned short word)
                    416: {
                    417:   for (int bit = 15; bit >= 0; bit--)
                    418:     if (word & (1 << bit))
                    419:       return bit;
                    420:   return -1;
                    421: }
                    422: 
                    423: static const char * get_ata_major_version(const ata_identify_device * drive)
                    424: {
                    425:   switch (find_msb(drive->major_rev_num)) {
                    426:     case 10: return "ACS-3";
                    427:     case  9: return "ACS-2";
                    428:     case  8: return "ATA8-ACS";
                    429:     case  7: return "ATA/ATAPI-7";
                    430:     case  6: return "ATA/ATAPI-6";
                    431:     case  5: return "ATA/ATAPI-5";
                    432:     case  4: return "ATA/ATAPI-4";
                    433:     case  3: return "ATA-3";
                    434:     case  2: return "ATA-2";
                    435:     case  1: return "ATA-1";
                    436:     default: return 0;
                    437:   }
                    438: }
                    439: 
                    440: static const char * get_ata_minor_version(const ata_identify_device * drive)
                    441: {
                    442:   switch (drive->minor_rev_num) {
                    443:     case 0x0001: return "ATA-1 X3T9.2/781D prior to revision 4";
                    444:     case 0x0002: return "ATA-1 published, ANSI X3.221-1994";
                    445:     case 0x0003: return "ATA-1 X3T9.2/781D revision 4";
                    446:     case 0x0004: return "ATA-2 published, ANSI X3.279-1996";
                    447:     case 0x0005: return "ATA-2 X3T10/948D prior to revision 2k";
                    448:     case 0x0006: return "ATA-3 X3T10/2008D revision 1";
                    449:     case 0x0007: return "ATA-2 X3T10/948D revision 2k";
                    450:     case 0x0008: return "ATA-3 X3T10/2008D revision 0";
                    451:     case 0x0009: return "ATA-2 X3T10/948D revision 3";
                    452:     case 0x000a: return "ATA-3 published, ANSI X3.298-1997";
                    453:     case 0x000b: return "ATA-3 X3T10/2008D revision 6"; // 1st ATA-3 revision with SMART
                    454:     case 0x000c: return "ATA-3 X3T13/2008D revision 7 and 7a";
                    455:     case 0x000d: return "ATA/ATAPI-4 X3T13/1153D revision 6";
                    456:     case 0x000e: return "ATA/ATAPI-4 T13/1153D revision 13";
                    457:     case 0x000f: return "ATA/ATAPI-4 X3T13/1153D revision 7";
                    458:     case 0x0010: return "ATA/ATAPI-4 T13/1153D revision 18";
                    459:     case 0x0011: return "ATA/ATAPI-4 T13/1153D revision 15";
                    460:     case 0x0012: return "ATA/ATAPI-4 published, ANSI NCITS 317-1998";
                    461:     case 0x0013: return "ATA/ATAPI-5 T13/1321D revision 3";
                    462:     case 0x0014: return "ATA/ATAPI-4 T13/1153D revision 14";
                    463:     case 0x0015: return "ATA/ATAPI-5 T13/1321D revision 1";
                    464:     case 0x0016: return "ATA/ATAPI-5 published, ANSI NCITS 340-2000";
                    465:     case 0x0017: return "ATA/ATAPI-4 T13/1153D revision 17";
                    466:     case 0x0018: return "ATA/ATAPI-6 T13/1410D revision 0";
                    467:     case 0x0019: return "ATA/ATAPI-6 T13/1410D revision 3a";
                    468:     case 0x001a: return "ATA/ATAPI-7 T13/1532D revision 1";
                    469:     case 0x001b: return "ATA/ATAPI-6 T13/1410D revision 2";
                    470:     case 0x001c: return "ATA/ATAPI-6 T13/1410D revision 1";
                    471:     case 0x001d: return "ATA/ATAPI-7 published, ANSI INCITS 397-2005";
                    472:     case 0x001e: return "ATA/ATAPI-7 T13/1532D revision 0";
                    473:     case 0x001f: return "ACS-3 T13/2161-D revision 3b";
                    474: 
                    475:     case 0x0021: return "ATA/ATAPI-7 T13/1532D revision 4a";
                    476:     case 0x0022: return "ATA/ATAPI-6 published, ANSI INCITS 361-2002";
                    477: 
                    478:     case 0x0027: return "ATA8-ACS T13/1699-D revision 3c";
                    479:     case 0x0028: return "ATA8-ACS T13/1699-D revision 6";
                    480:     case 0x0029: return "ATA8-ACS T13/1699-D revision 4";
                    481: 
                    482:     case 0x0031: return "ACS-2 T13/2015-D revision 2";
                    483: 
                    484:     case 0x0033: return "ATA8-ACS T13/1699-D revision 3e";
                    485: 
                    486:     case 0x0039: return "ATA8-ACS T13/1699-D revision 4c";
                    487: 
                    488:     case 0x0042: return "ATA8-ACS T13/1699-D revision 3f";
                    489: 
                    490:     case 0x0052: return "ATA8-ACS T13/1699-D revision 3b";
                    491: 
                    492:     case 0x0107: return "ATA8-ACS T13/1699-D revision 2d";
                    493: 
                    494:     case 0x0110: return "ACS-2 T13/2015-D revision 3";
                    495: 
                    496:     default:     return 0;
                    497:   }
                    498: }
                    499: 
                    500: static const char * get_sata_version(const ata_identify_device * drive)
                    501: {
                    502:   unsigned short word222 = drive->words088_255[222-88];
                    503:   if ((word222 & 0xf000) != 0x1000)
                    504:     return 0;
                    505:   switch (find_msb(word222 & 0x0fff)) {
                    506:     default: return "SATA >3.1";
                    507:     case 6:  return "SATA 3.1";
                    508:     case 5:  return "SATA 3.0";
                    509:     case 4:  return "SATA 2.6";
                    510:     case 3:  return "SATA 2.5";
                    511:     case 2:  return "SATA II Ext";
                    512:     case 1:  return "SATA 1.0a";
                    513:     case 0:  return "ATA8-AST";
                    514:     case -1: return 0;
                    515:   }
                    516: }
                    517: 
                    518: static const char * get_sata_speed(int level)
                    519: {
                    520:   if (level <= 0)
                    521:     return 0;
                    522:   switch (level) {
                    523:     default: return ">6.0 Gb/s";
                    524:     case 3:  return "6.0 Gb/s";
                    525:     case 2:  return "3.0 Gb/s";
                    526:     case 1:  return "1.5 Gb/s";
                    527:   }
                    528: }
                    529: 
                    530: static const char * get_sata_maxspeed(const ata_identify_device * drive)
                    531: {
                    532:   unsigned short word076 = drive->words047_079[76-47];
                    533:   if (word076 & 0x0001)
                    534:     return 0;
                    535:   return get_sata_speed(find_msb(word076 & 0x00fe));
                    536: }
                    537: 
                    538: static const char * get_sata_curspeed(const ata_identify_device * drive)
                    539: {
                    540:   unsigned short word077 = drive->words047_079[77-47];
                    541:   if (word077 & 0x0001)
                    542:     return 0;
                    543:   return get_sata_speed((word077 >> 1) & 0x7);
                    544: }
                    545: 
                    546: 
1.1       misho     547: static void print_drive_info(const ata_identify_device * drive,
1.1.1.3   misho     548:                              const ata_size_info & sizes, int rpm,
1.1       misho     549:                              const drive_settings * dbentry)
                    550: {
                    551:   // format drive information (with byte swapping as needed)
                    552:   char model[40+1], serial[20+1], firmware[8+1];
                    553:   ata_format_id_string(model, drive->model, sizeof(model)-1);
                    554:   ata_format_id_string(serial, drive->serial_no, sizeof(serial)-1);
                    555:   ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware)-1);
                    556: 
                    557:   // Print model family if known
                    558:   if (dbentry && *dbentry->modelfamily)
                    559:     pout("Model Family:     %s\n", dbentry->modelfamily);
                    560: 
                    561:   pout("Device Model:     %s\n", infofound(model));
                    562:   if (!dont_print_serial_number) {
                    563:     pout("Serial Number:    %s\n", infofound(serial));
                    564: 
                    565:     unsigned oui = 0; uint64_t unique_id = 0;
                    566:     int naa = ata_get_wwn(drive, oui, unique_id);
                    567:     if (naa >= 0)
                    568:       pout("LU WWN Device Id: %x %06x %09"PRIx64"\n", naa, oui, unique_id);
1.1.1.3   misho     569: 
                    570:     // Additional Product Identifier (OEM Id) string in words 170-173
                    571:     // (e08130r1, added in ACS-2 Revision 1, December 17, 2008)
                    572:     if (0x2020 <= drive->words088_255[170-88] && drive->words088_255[170-88] <= 0x7e7e) {
                    573:       char add[8+1];
                    574:       ata_format_id_string(add, (const unsigned char *)(drive->words088_255+170-88), sizeof(add)-1);
                    575:       if (add[0])
                    576:         pout("Add. Product Id:  %s\n", add);
                    577:     }
1.1       misho     578:   }
                    579:   pout("Firmware Version: %s\n", infofound(firmware));
                    580: 
                    581:   if (sizes.capacity) {
                    582:     // Print capacity
                    583:     char num[64], cap[32];
                    584:     pout("User Capacity:    %s bytes [%s]\n",
                    585:       format_with_thousands_sep(num, sizeof(num), sizes.capacity),
                    586:       format_capacity(cap, sizeof(cap), sizes.capacity));
                    587: 
                    588:     // Print sector sizes.
                    589:     if (sizes.phy_sector_size == sizes.log_sector_size)
                    590:       pout("Sector Size:      %u bytes logical/physical\n", sizes.log_sector_size);
                    591:     else {
                    592:       pout("Sector Sizes:     %u bytes logical, %u bytes physical",
                    593:          sizes.log_sector_size, sizes.phy_sector_size);
                    594:       if (sizes.log_sector_offset)
                    595:         pout(" (offset %u bytes)", sizes.log_sector_offset);
                    596:       pout("\n");
                    597:     }
                    598:   }
                    599: 
1.1.1.3   misho     600:   // Print nominal media rotation rate if reported
                    601:   if (rpm) {
                    602:     if (rpm == 1)
                    603:       pout("Rotation Rate:    Solid State Device\n");
                    604:     else if (rpm > 1)
                    605:       pout("Rotation Rate:    %d rpm\n", rpm);
                    606:     else
                    607:       pout("Rotation Rate:    Unknown (0x%04x)\n", -rpm);
                    608:   }
                    609: 
1.1       misho     610:   // See if drive is recognized
                    611:   pout("Device is:        %s\n", !dbentry ?
                    612:        "Not in smartctl database [for details use: -P showall]":
                    613:        "In smartctl database [for details use: -P show]");
                    614: 
1.1.1.3   misho     615:   // Print ATA version
                    616:   std::string ataver;
                    617:   if (   (drive->major_rev_num != 0x0000 && drive->major_rev_num != 0xffff)
                    618:       || (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)) {
                    619:     const char * majorver = get_ata_major_version(drive);
                    620:     const char * minorver = get_ata_minor_version(drive);
                    621: 
                    622:     if (majorver && minorver && str_starts_with(minorver, majorver)) {
                    623:       // Major and minor strings match, print minor string only
                    624:       ataver = minorver;
1.1       misho     625:     }
                    626:     else {
1.1.1.3   misho     627:       if (majorver)
                    628:         ataver = majorver;
                    629:       else
                    630:         ataver = strprintf("Unknown(0x%04x)", drive->major_rev_num);
                    631: 
                    632:       if (minorver)
                    633:         ataver += strprintf(", %s", minorver);
                    634:       else if (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)
                    635:         ataver += strprintf(" (unknown minor revision code: 0x%04x)", drive->minor_rev_num);
1.1       misho     636:       else
1.1.1.3   misho     637:         ataver += " (minor revision not indicated)";
1.1       misho     638:     }
                    639:   }
1.1.1.3   misho     640:   pout("ATA Version is:   %s\n", infofound(ataver.c_str()));
1.1       misho     641: 
1.1.1.3   misho     642:   // If SATA drive print SATA version and speed
                    643:   const char * sataver = get_sata_version(drive);
                    644:   if (sataver) {
                    645:     const char * maxspeed = get_sata_maxspeed(drive);
                    646:     const char * curspeed = get_sata_curspeed(drive);
                    647:     pout("SATA Version is:  %s%s%s%s%s%s\n", sataver,
                    648:          (maxspeed ? ", " : ""), (maxspeed ? maxspeed : ""),
                    649:          (curspeed ? " (current: " : ""), (curspeed ? curspeed : ""),
                    650:          (curspeed ? ")" : ""));
                    651:   }
1.1       misho     652: 
                    653:   // print current time and date and timezone
                    654:   char timedatetz[DATEANDEPOCHLEN]; dateandtimezone(timedatetz);
                    655:   pout("Local Time is:    %s\n", timedatetz);
                    656: 
                    657:   // Print warning message, if there is one
                    658:   if (dbentry && *dbentry->warningmsg)
                    659:     pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
                    660: }
                    661: 
                    662: static const char *OfflineDataCollectionStatus(unsigned char status_byte)
                    663: {
                    664:   unsigned char stat=status_byte & 0x7f;
                    665:   
                    666:   switch(stat){
                    667:   case 0x00:
                    668:     return "was never started";
                    669:   case 0x02:
                    670:     return "was completed without error";
                    671:   case 0x03:
                    672:     if (status_byte == 0x03)
                    673:       return "is in progress";
                    674:     else
                    675:       return "is in a Reserved state";
                    676:   case 0x04:
                    677:     return "was suspended by an interrupting command from host";
                    678:   case 0x05:
                    679:     return "was aborted by an interrupting command from host";
                    680:   case 0x06:
                    681:     return "was aborted by the device with a fatal error";
                    682:   default:
                    683:     if (stat >= 0x40)
                    684:       return "is in a Vendor Specific state";
                    685:     else
                    686:       return "is in a Reserved state";
                    687:   }
                    688: }
                    689:   
                    690:   
                    691: //  prints verbose value Off-line data collection status byte
                    692: static void PrintSmartOfflineStatus(const ata_smart_values * data)
                    693: {
                    694:   pout("Offline data collection status:  (0x%02x)\t",
                    695:        (int)data->offline_data_collection_status);
                    696:     
                    697:   // Off-line data collection status byte is not a reserved
                    698:   // or vendor specific value
                    699:   pout("Offline data collection activity\n"
                    700:        "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
                    701:   
                    702:   // Report on Automatic Data Collection Status.  Only IBM documents
                    703:   // this bit.  See SFF 8035i Revision 2 for details.
                    704:   if (data->offline_data_collection_status & 0x80)
                    705:     pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
                    706:   else
                    707:     pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
                    708:   
                    709:   return;
                    710: }
                    711: 
                    712: static void PrintSmartSelfExecStatus(const ata_smart_values * data,
1.1.1.3   misho     713:                                      firmwarebug_defs firmwarebugs)
1.1       misho     714: {
                    715:    pout("Self-test execution status:      ");
                    716:    
                    717:    switch (data->self_test_exec_status >> 4)
                    718:    {
                    719:       case 0:
                    720:         pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
                    721:                 (int)data->self_test_exec_status);
                    722:         pout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
                    723:         break;
                    724:        case 1:
                    725:          pout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t",
                    726:                  (int)data->self_test_exec_status);
                    727:          pout("the host.\n");
                    728:          break;
                    729:        case 2:
                    730:          pout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t",
                    731:                  (int)data->self_test_exec_status);
                    732:          pout("by the host with a hard or soft reset.\n");
                    733:          break;
                    734:        case 3:
                    735:           pout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t",
                    736:                   (int)data->self_test_exec_status);
                    737:           pout("occurred while the device was executing\n\t\t\t\t\t");
                    738:           pout("its self-test routine and the device \n\t\t\t\t\t");
                    739:           pout("was unable to complete the self-test \n\t\t\t\t\t");
                    740:           pout("routine.\n");
                    741:           break;
                    742:        case 4:
                    743:           pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
                    744:                   (int)data->self_test_exec_status);
                    745:           pout("a test element that failed and the test\n\t\t\t\t\t");
                    746:           pout("element that failed is not known.\n");
                    747:           break;
                    748:        case 5:
                    749:           pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
                    750:                   (int)data->self_test_exec_status);
                    751:           pout("the electrical element of the test\n\t\t\t\t\t");
                    752:           pout("failed.\n");
                    753:           break;
                    754:        case 6:
                    755:           pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
                    756:                   (int)data->self_test_exec_status);
                    757:           pout("the servo (and/or seek) element of the \n\t\t\t\t\t");
                    758:           pout("test failed.\n");
                    759:           break;
                    760:        case 7:
                    761:           pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
                    762:                   (int)data->self_test_exec_status);
                    763:           pout("the read element of the test failed.\n");
                    764:           break;
                    765:        case 8:
                    766:           pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
                    767:                   (int)data->self_test_exec_status);
                    768:           pout("a test element that failed and the\n\t\t\t\t\t");
                    769:           pout("device is suspected of having handling\n\t\t\t\t\t");
                    770:           pout("damage.\n");
                    771:           break;
                    772:        case 15:
1.1.1.3   misho     773:           if (firmwarebugs.is_set(BUG_SAMSUNG3) && data->self_test_exec_status == 0xf0) {
1.1       misho     774:             pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
                    775:                     (int)data->self_test_exec_status);
                    776:             pout("with unknown result or self-test in\n\t\t\t\t\t");
                    777:             pout("progress with less than 10%% remaining.\n");
                    778:           }
                    779:           else {
                    780:             pout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t",
                    781:                     (int)data->self_test_exec_status);
                    782:             pout("%1d0%% of test remaining.\n", 
                    783:                   (int)(data->self_test_exec_status & 0x0f));
                    784:           }
                    785:           break;
                    786:        default:
                    787:           pout("(%4d)\tReserved.\n",
                    788:                   (int)data->self_test_exec_status);
                    789:           break;
                    790:    }
                    791:         
                    792: }
                    793: 
                    794: static void PrintSmartTotalTimeCompleteOffline (const ata_smart_values * data)
                    795: {
                    796:   pout("Total time to complete Offline \n");
                    797:   pout("data collection: \t\t(%5d) seconds.\n", 
                    798:        (int)data->total_time_to_complete_off_line);
                    799: }
                    800: 
                    801: static void PrintSmartOfflineCollectCap(const ata_smart_values *data)
                    802: {
                    803:   pout("Offline data collection\n");
                    804:   pout("capabilities: \t\t\t (0x%02x) ",
                    805:        (int)data->offline_data_collection_capability);
                    806:   
                    807:   if (data->offline_data_collection_capability == 0x00){
                    808:     pout("\tOffline data collection not supported.\n");
                    809:   } 
                    810:   else {
                    811:     pout( "%s\n", isSupportExecuteOfflineImmediate(data)?
                    812:           "SMART execute Offline immediate." :
                    813:           "No SMART execute Offline immediate.");
                    814:     
                    815:     pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)? 
                    816:           "Auto Offline data collection on/off support.":
                    817:           "No Auto Offline data collection support.");
                    818:     
                    819:     pout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)? 
                    820:           "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
                    821:           "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
                    822:     
                    823:     pout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)? 
                    824:           "Offline surface scan supported.":
                    825:           "No Offline surface scan supported.");
                    826:     
                    827:     pout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)? 
                    828:           "Self-test supported.":
                    829:           "No Self-test supported.");
                    830: 
                    831:     pout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)? 
                    832:           "Conveyance Self-test supported.":
                    833:           "No Conveyance Self-test supported.");
                    834: 
                    835:     pout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)? 
                    836:           "Selective Self-test supported.":
                    837:           "No Selective Self-test supported.");
                    838:   }
                    839: }
                    840: 
                    841: static void PrintSmartCapability(const ata_smart_values *data)
                    842: {
                    843:    pout("SMART capabilities:            ");
                    844:    pout("(0x%04x)\t", (int)data->smart_capability);
                    845:    
                    846:    if (data->smart_capability == 0x00)
                    847:    {
                    848:        pout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
                    849:    } 
                    850:    else 
                    851:    {
                    852:         
                    853:       pout( "%s\n", (data->smart_capability & 0x01)? 
                    854:               "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
                    855:               "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
                    856:                 
                    857:       if ( data->smart_capability & 0x02 )
                    858:       {
                    859:           pout("\t\t\t\t\tSupports SMART auto save timer.\n");
                    860:       }
                    861:    }
                    862: }
                    863: 
                    864: static void PrintSmartErrorLogCapability(const ata_smart_values * data, const ata_identify_device * identity)
                    865: {
                    866:    pout("Error logging capability:       ");
                    867:     
                    868:    if ( isSmartErrorLogCapable(data, identity) )
                    869:    {
                    870:       pout(" (0x%02x)\tError logging supported.\n",
                    871:                (int)data->errorlog_capability);
                    872:    }
                    873:    else {
                    874:        pout(" (0x%02x)\tError logging NOT supported.\n",
                    875:                 (int)data->errorlog_capability);
                    876:    }
                    877: }
                    878: 
                    879: static void PrintSmartShortSelfTestPollingTime(const ata_smart_values * data)
                    880: {
                    881:   pout("Short self-test routine \n");
                    882:   if (isSupportSelfTest(data))
                    883:     pout("recommended polling time: \t (%4d) minutes.\n", 
                    884:          (int)data->short_test_completion_time);
                    885:   else
                    886:     pout("recommended polling time: \t        Not Supported.\n");
                    887: }
                    888: 
                    889: static void PrintSmartExtendedSelfTestPollingTime(const ata_smart_values * data)
                    890: {
                    891:   pout("Extended self-test routine\n");
                    892:   if (isSupportSelfTest(data))
                    893:     pout("recommended polling time: \t (%4d) minutes.\n", 
1.1.1.2   misho     894:          TestTime(data, EXTEND_SELF_TEST));
1.1       misho     895:   else
                    896:     pout("recommended polling time: \t        Not Supported.\n");
                    897: }
                    898: 
                    899: static void PrintSmartConveyanceSelfTestPollingTime(const ata_smart_values * data)
                    900: {
                    901:   pout("Conveyance self-test routine\n");
                    902:   if (isSupportConveyanceSelfTest(data))
                    903:     pout("recommended polling time: \t (%4d) minutes.\n", 
                    904:          (int)data->conveyance_test_completion_time);
                    905:   else
                    906:     pout("recommended polling time: \t        Not Supported.\n");
                    907: }
                    908: 
                    909: // Check SMART attribute table for Threshold failure
                    910: // onlyfailed=0: are or were any age or prefailure attributes <= threshold
                    911: // onlyfailed=1: are any prefailure attributes <= threshold now
                    912: static int find_failed_attr(const ata_smart_values * data,
                    913:                             const ata_smart_thresholds_pvt * thresholds,
                    914:                             const ata_vendor_attr_defs & defs, int onlyfailed)
                    915: {
                    916:   for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
                    917:     const ata_smart_attribute & attr = data->vendor_attributes[i];
                    918: 
                    919:     ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs);
                    920: 
                    921:     if (!onlyfailed) {
                    922:       if (state >= ATTRSTATE_FAILED_PAST)
                    923:         return attr.id;
                    924:     }
                    925:     else {
                    926:       if (state == ATTRSTATE_FAILED_NOW && ATTRIBUTE_FLAGS_PREFAILURE(attr.flags))
                    927:         return attr.id;
                    928:     }
                    929:   }
                    930:   return 0;
                    931: }
                    932: 
                    933: // onlyfailed=0 : print all attribute values
                    934: // onlyfailed=1:  just ones that are currently failed and have prefailure bit set
                    935: // onlyfailed=2:  ones that are failed, or have failed with or without prefailure bit set
                    936: static void PrintSmartAttribWithThres(const ata_smart_values * data,
                    937:                                       const ata_smart_thresholds_pvt * thresholds,
1.1.1.3   misho     938:                                       const ata_vendor_attr_defs & defs, int rpm,
1.1       misho     939:                                       int onlyfailed, unsigned char format)
                    940: {
1.1.1.2   misho     941:   bool brief  = !!(format & ata_print_options::FMT_BRIEF);
                    942:   bool hexid  = !!(format & ata_print_options::FMT_HEX_ID);
                    943:   bool hexval = !!(format & ata_print_options::FMT_HEX_VAL);
1.1       misho     944:   bool needheader = true;
                    945: 
                    946:   // step through all vendor attributes
                    947:   for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
                    948:     const ata_smart_attribute & attr = data->vendor_attributes[i];
                    949: 
                    950:     // Check attribute and threshold
                    951:     unsigned char threshold = 0;
                    952:     ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs, &threshold);
                    953:     if (state == ATTRSTATE_NON_EXISTING)
                    954:       continue;
                    955: 
                    956:     // These break out of the loop if we are only printing certain entries...
                    957:     if (onlyfailed == 1 && !(ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) && state == ATTRSTATE_FAILED_NOW))
                    958:       continue;
                    959: 
                    960:     if (onlyfailed == 2 && state < ATTRSTATE_FAILED_PAST)
                    961:       continue;
                    962: 
                    963:     // print header only if needed
                    964:     if (needheader) {
                    965:       if (!onlyfailed) {
                    966:         pout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
                    967:         pout("Vendor Specific SMART Attributes with Thresholds:\n");
                    968:       }
1.1.1.2   misho     969:       if (!brief)
                    970:         pout("ID#%s ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE\n",
                    971:              (!hexid ? "" : " "));
1.1       misho     972:       else
1.1.1.2   misho     973:         pout("ID#%s ATTRIBUTE_NAME          FLAGS    VALUE WORST THRESH FAIL RAW_VALUE\n",
                    974:              (!hexid ? "" : " "));
1.1       misho     975:       needheader = false;
                    976:     }
                    977: 
                    978:     // Format value, worst, threshold
                    979:     std::string valstr, worstr, threstr;
                    980:     if (state > ATTRSTATE_NO_NORMVAL)
1.1.1.2   misho     981:       valstr = (!hexval ? strprintf("%.3d",   attr.current)
                    982:                         : strprintf("0x%02x", attr.current));
1.1       misho     983:     else
1.1.1.2   misho     984:       valstr = (!hexval ? "---" : "----");
1.1       misho     985:     if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
1.1.1.2   misho     986:       worstr = (!hexval ? strprintf("%.3d",   attr.worst)
                    987:                         : strprintf("0x%02x", attr.worst));
1.1       misho     988:     else
1.1.1.2   misho     989:       worstr = (!hexval ? "---" : "----");
1.1       misho     990:     if (state > ATTRSTATE_NO_THRESHOLD)
1.1.1.2   misho     991:       threstr = (!hexval ? strprintf("%.3d",   threshold)
                    992:                          : strprintf("0x%02x", threshold));
1.1       misho     993:     else
1.1.1.2   misho     994:       threstr = (!hexval ? "---" : "----");
1.1       misho     995: 
                    996:     // Print line for each valid attribute
1.1.1.2   misho     997:     std::string idstr = (!hexid ? strprintf("%3d",    attr.id)
                    998:                                 : strprintf("0x%02x", attr.id));
1.1.1.3   misho     999:     std::string attrname = ata_get_smart_attr_name(attr.id, defs, rpm);
1.1       misho    1000:     std::string rawstr = ata_format_attr_raw_value(attr, defs);
                   1001: 
1.1.1.2   misho    1002:     if (!brief)
                   1003:       pout("%s %-24s0x%04x   %-4s  %-4s  %-4s   %-10s%-9s%-12s%s\n",
                   1004:            idstr.c_str(), attrname.c_str(), attr.flags,
1.1       misho    1005:            valstr.c_str(), worstr.c_str(), threstr.c_str(),
                   1006:            (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? "Pre-fail" : "Old_age"),
                   1007:            (ATTRIBUTE_FLAGS_ONLINE(attr.flags)     ? "Always"   : "Offline"),
                   1008:            (state == ATTRSTATE_FAILED_NOW  ? "FAILING_NOW" :
                   1009:             state == ATTRSTATE_FAILED_PAST ? "In_the_past"
                   1010:                                            : "    -"        ) ,
                   1011:             rawstr.c_str());
                   1012:     else
1.1.1.2   misho    1013:       pout("%s %-24s%c%c%c%c%c%c%c  %-4s  %-4s  %-4s   %-5s%s\n",
                   1014:            idstr.c_str(), attrname.c_str(),
1.1       misho    1015:            (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags)     ? 'P' : '-'),
                   1016:            (ATTRIBUTE_FLAGS_ONLINE(attr.flags)         ? 'O' : '-'),
                   1017:            (ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags)    ? 'S' : '-'),
                   1018:            (ATTRIBUTE_FLAGS_ERRORRATE(attr.flags)      ? 'R' : '-'),
                   1019:            (ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags)     ? 'C' : '-'),
                   1020:            (ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags) ? 'K' : '-'),
                   1021:            (ATTRIBUTE_FLAGS_OTHER(attr.flags)          ? '+' : ' '),
                   1022:            valstr.c_str(), worstr.c_str(), threstr.c_str(),
                   1023:            (state == ATTRSTATE_FAILED_NOW  ? "NOW"  :
                   1024:             state == ATTRSTATE_FAILED_PAST ? "Past"
                   1025:                                            : "-"     ),
                   1026:             rawstr.c_str());
                   1027: 
                   1028:   }
                   1029: 
                   1030:   if (!needheader) {
1.1.1.2   misho    1031:     if (!onlyfailed && brief) {
                   1032:         int n = (!hexid ? 28 : 29);
                   1033:         pout("%*s||||||_ K auto-keep\n"
                   1034:              "%*s|||||__ C event count\n"
                   1035:              "%*s||||___ R error rate\n"
                   1036:              "%*s|||____ S speed/performance\n"
                   1037:              "%*s||_____ O updated online\n"
                   1038:              "%*s|______ P prefailure warning\n",
                   1039:              n, "", n, "", n, "", n, "", n, "", n, "");
                   1040:     }
1.1       misho    1041:     pout("\n");
                   1042:   }
                   1043: }
                   1044: 
                   1045: // Print SMART related SCT capabilities
                   1046: static void ataPrintSCTCapability(const ata_identify_device *drive)
                   1047: {
                   1048:   unsigned short sctcaps = drive->words088_255[206-88];
                   1049:   if (!(sctcaps & 0x01))
                   1050:     return;
                   1051:   pout("SCT capabilities: \t       (0x%04x)\tSCT Status supported.\n", sctcaps);
                   1052:   if (sctcaps & 0x08)
                   1053:     pout("\t\t\t\t\tSCT Error Recovery Control supported.\n");
                   1054:   if (sctcaps & 0x10)
                   1055:     pout("\t\t\t\t\tSCT Feature Control supported.\n");
                   1056:   if (sctcaps & 0x20)
                   1057:     pout("\t\t\t\t\tSCT Data Table supported.\n");
                   1058: }
                   1059: 
                   1060: 
                   1061: static void PrintGeneralSmartValues(const ata_smart_values *data, const ata_identify_device *drive,
1.1.1.3   misho    1062:                                     firmwarebug_defs firmwarebugs)
1.1       misho    1063: {
                   1064:   pout("General SMART Values:\n");
                   1065:   
                   1066:   PrintSmartOfflineStatus(data); 
                   1067:   
                   1068:   if (isSupportSelfTest(data)){
1.1.1.3   misho    1069:     PrintSmartSelfExecStatus(data, firmwarebugs);
1.1       misho    1070:   }
                   1071:   
                   1072:   PrintSmartTotalTimeCompleteOffline(data);
                   1073:   PrintSmartOfflineCollectCap(data);
                   1074:   PrintSmartCapability(data);
                   1075:   
                   1076:   PrintSmartErrorLogCapability(data, drive);
                   1077: 
                   1078:   pout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
                   1079:         "General Purpose Logging supported.":
                   1080:         "No General Purpose Logging support.");
                   1081: 
                   1082:   if (isSupportSelfTest(data)){
                   1083:     PrintSmartShortSelfTestPollingTime (data);
                   1084:     PrintSmartExtendedSelfTestPollingTime (data);
                   1085:   }
                   1086:   if (isSupportConveyanceSelfTest(data))
                   1087:     PrintSmartConveyanceSelfTestPollingTime (data);
                   1088: 
                   1089:   ataPrintSCTCapability(drive);
                   1090: 
                   1091:   pout("\n");
                   1092: }
                   1093: 
                   1094: // Get # sectors of a log addr, 0 if log does not exist.
                   1095: static unsigned GetNumLogSectors(const ata_smart_log_directory * logdir, unsigned logaddr, bool gpl)
                   1096: {
                   1097:   if (!logdir)
                   1098:     return 0;
                   1099:   if (logaddr > 0xff)
                   1100:     return 0;
                   1101:   if (logaddr == 0)
                   1102:     return 1;
                   1103:   unsigned n = logdir->entry[logaddr-1].numsectors;
                   1104:   if (gpl)
                   1105:     // GP logs may have >255 sectors
                   1106:     n |= logdir->entry[logaddr-1].reserved << 8;
                   1107:   return n;
                   1108: }
                   1109: 
                   1110: // Get name of log.
1.1.1.3   misho    1111: // Table A.2 of T13/2161-D (ACS-3) Revision 4, September 4, 2012
1.1       misho    1112: static const char * GetLogName(unsigned logaddr)
                   1113: {
                   1114:     switch (logaddr) {
                   1115:       case 0x00: return "Log Directory";
                   1116:       case 0x01: return "Summary SMART error log";
                   1117:       case 0x02: return "Comprehensive SMART error log";
                   1118:       case 0x03: return "Ext. Comprehensive SMART error log";
                   1119:       case 0x04: return "Device Statistics log";
1.1.1.3   misho    1120:       case 0x05: return "Reserved for CFA"; // ACS-2
1.1       misho    1121:       case 0x06: return "SMART self-test log";
                   1122:       case 0x07: return "Extended self-test log";
                   1123:       case 0x08: return "Power Conditions log"; // ACS-2
                   1124:       case 0x09: return "Selective self-test log";
1.1.1.3   misho    1125:       case 0x0a: return "Device Statistics Notification"; // ACS-3
                   1126:       case 0x0b: return "Reserved for CFA"; // ACS-3
                   1127: 
1.1       misho    1128:       case 0x0d: return "LPS Mis-alignment log"; // ACS-2
1.1.1.3   misho    1129: 
1.1       misho    1130:       case 0x10: return "NCQ Command Error log";
                   1131:       case 0x11: return "SATA Phy Event Counters";
1.1.1.2   misho    1132:       case 0x12: return "SATA NCQ Queue Management log"; // ACS-3
                   1133:       case 0x13: return "SATA NCQ Send and Receive log"; // ACS-3
                   1134:       case 0x14:
                   1135:       case 0x15:
                   1136:       case 0x16: return "Reserved for Serial ATA";
1.1.1.3   misho    1137: 
1.1       misho    1138:       case 0x19: return "LBA Status log"; // ACS-3
1.1.1.3   misho    1139: 
                   1140:       case 0x20: return "Streaming performance log [OBS-8]";
1.1       misho    1141:       case 0x21: return "Write stream error log";
                   1142:       case 0x22: return "Read stream error log";
1.1.1.3   misho    1143:       case 0x23: return "Delayed sector log [OBS-8]";
1.1.1.2   misho    1144:       case 0x24: return "Current Device Internal Status Data log"; // ACS-3
                   1145:       case 0x25: return "Saved Device Internal Status Data log"; // ACS-3
1.1.1.3   misho    1146: 
1.1       misho    1147:       case 0x30: return "IDENTIFY DEVICE data log"; // ACS-3
1.1.1.3   misho    1148: 
1.1       misho    1149:       case 0xe0: return "SCT Command/Status";
                   1150:       case 0xe1: return "SCT Data Transfer";
                   1151:       default:
                   1152:         if (0xa0 <= logaddr && logaddr <= 0xdf)
                   1153:           return "Device vendor specific log";
                   1154:         if (0x80 <= logaddr && logaddr <= 0x9f)
                   1155:           return "Host vendor specific log";
                   1156:         return "Reserved";
                   1157:     }
                   1158:     /*NOTREACHED*/
                   1159: }
                   1160: 
1.1.1.3   misho    1161: // Get log access permissions
                   1162: static const char * get_log_rw(unsigned logaddr)
                   1163: {
                   1164:    if (   (                   logaddr <= 0x08)
                   1165:        || (0x0d == logaddr)
                   1166:        || (0x10 <= logaddr && logaddr <= 0x13)
                   1167:        || (0x19 == logaddr)
                   1168:        || (0x20 <= logaddr && logaddr <= 0x25)
                   1169:        || (0x30 == logaddr))
                   1170:       return "R/O";
                   1171: 
                   1172:    if (   (0x09 <= logaddr && logaddr <= 0x0a)
                   1173:        || (0x80 <= logaddr && logaddr <= 0x9f)
                   1174:        || (0xe0 <= logaddr && logaddr <= 0xe1))
                   1175:       return "R/W";
                   1176: 
                   1177:    if (0xa0 <= logaddr && logaddr <= 0xdf)
                   1178:       return "VS"; // Vendor specific
                   1179: 
                   1180:    return "-"; // Unknown/Reserved
                   1181: }
                   1182: 
                   1183: // Init a fake log directory, assume that standard logs are supported
                   1184: const ata_smart_log_directory * fake_logdir(ata_smart_log_directory * logdir,
                   1185:   const ata_print_options & options)
                   1186: {
                   1187:   memset(logdir, 0, sizeof(*logdir));
                   1188:   logdir->logversion = 255;
                   1189:   logdir->entry[0x01-1].numsectors = 1;
                   1190:   logdir->entry[0x03-1].numsectors = (options.smart_ext_error_log + (4-1)) / 4;
                   1191:   logdir->entry[0x04-1].numsectors = 8;
                   1192:   logdir->entry[0x06-1].numsectors = 1;
                   1193:   logdir->entry[0x07-1].numsectors = (options.smart_ext_selftest_log + (19-1)) / 19;
                   1194:   logdir->entry[0x09-1].numsectors = 1;
                   1195:   logdir->entry[0x11-1].numsectors = 1;
                   1196:   return logdir;
                   1197: }
                   1198: 
1.1       misho    1199: // Print SMART and/or GP Log Directory
                   1200: static void PrintLogDirectories(const ata_smart_log_directory * gplogdir,
                   1201:                                 const ata_smart_log_directory * smartlogdir)
                   1202: {
                   1203:   if (gplogdir)
                   1204:     pout("General Purpose Log Directory Version %u\n", gplogdir->logversion);
                   1205:   if (smartlogdir)
                   1206:     pout("SMART %sLog Directory Version %u%s\n",
                   1207:          (gplogdir ? "          " : ""), smartlogdir->logversion,
                   1208:          (smartlogdir->logversion==1 ? " [multi-sector log support]" : ""));
                   1209: 
1.1.1.3   misho    1210:   pout("Address    Access  R/W   Size  Description\n");
                   1211: 
1.1       misho    1212:   for (unsigned i = 0; i <= 0xff; i++) {
                   1213:     // Get number of sectors
                   1214:     unsigned smart_numsect = GetNumLogSectors(smartlogdir, i, false);
                   1215:     unsigned gp_numsect    = GetNumLogSectors(gplogdir   , i, true );
                   1216: 
                   1217:     if (!(smart_numsect || gp_numsect))
                   1218:       continue; // Log does not exist
                   1219: 
1.1.1.3   misho    1220:     const char * acc; unsigned size;
                   1221:     if (smart_numsect == gp_numsect) {
                   1222:       acc = "GPL,SL"; size = gp_numsect;
                   1223:     }
                   1224:     else if (!smart_numsect) {
                   1225:       acc = "GPL"; size = gp_numsect;
                   1226:     }
                   1227:     else if (!gp_numsect) {
                   1228:       acc = "    SL"; size = smart_numsect;
                   1229:     }
                   1230:     else {
                   1231:       acc = 0; size = 0;
                   1232:     }
                   1233: 
                   1234:     unsigned i2 = i;
                   1235:     if (acc && ((0x80 <= i && i < 0x9f) || (0xa0 <= i && i < 0xdf))) {
                   1236:       // Find range of Host/Device vendor specific logs with same size
                   1237:       unsigned imax = (i < 0x9f ? 0x9f : 0xdf);
                   1238:       for (unsigned j = i+1; j <= imax; j++) {
                   1239:           unsigned sn = GetNumLogSectors(smartlogdir, j, false);
                   1240:           unsigned gn = GetNumLogSectors(gplogdir   , j, true );
                   1241: 
                   1242:           if (!(sn == smart_numsect && gn == gp_numsect))
                   1243:             break;
                   1244:           i2 = j;
                   1245:       }
                   1246:     }
                   1247: 
1.1       misho    1248:     const char * name = GetLogName(i);
1.1.1.3   misho    1249:     const char * rw = get_log_rw(i);
1.1       misho    1250: 
1.1.1.3   misho    1251:     if (i2 > i) {
                   1252:       pout("0x%02x-0x%02x  %-6s  %-3s  %5u  %s\n", i, i2, acc, rw, size, name);
                   1253:       i = i2;
                   1254:     }
                   1255:     else if (acc)
                   1256:       pout(  "0x%02x       %-6s  %-3s  %5u  %s\n", i, acc, rw, size, name);
1.1       misho    1257:     else {
1.1.1.3   misho    1258:       // GPL and SL support different sizes
                   1259:       pout(  "0x%02x       %-6s  %-3s  %5u  %s\n", i, "GPL", rw, gp_numsect, name);
                   1260:       pout(  "0x%02x       %-6s  %-3s  %5u  %s\n", i, "SL", rw, smart_numsect, name);
1.1       misho    1261:     }
                   1262:   }
                   1263:   pout("\n");
                   1264: }
                   1265: 
                   1266: // Print hexdump of log pages.
                   1267: // Format is compatible with 'xxd -r'.
                   1268: static void PrintLogPages(const char * type, const unsigned char * data,
                   1269:                           unsigned char logaddr, unsigned page,
                   1270:                           unsigned num_pages, unsigned max_pages)
                   1271: {
                   1272:   pout("%s Log 0x%02x [%s], Page %u-%u (of %u)\n",
                   1273:     type, logaddr, GetLogName(logaddr), page, page+num_pages-1, max_pages);
                   1274:   for (unsigned i = 0; i < num_pages * 512; i += 16) {
                   1275:     const unsigned char * p = data+i;
                   1276:     pout("%07x: %02x %02x %02x %02x %02x %02x %02x %02x "
                   1277:                "%02x %02x %02x %02x %02x %02x %02x %02x ",
                   1278:          (page * 512) + i,
                   1279:          p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
                   1280:          p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
                   1281: #define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
                   1282:     pout("|%c%c%c%c%c%c%c%c"
                   1283:           "%c%c%c%c%c%c%c%c|\n",
                   1284:          P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
                   1285:          P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15));
                   1286: #undef P
                   1287:     if ((i & 0x1ff) == 0x1f0)
                   1288:       pout("\n");
                   1289:   }
                   1290: }
                   1291: 
                   1292: ///////////////////////////////////////////////////////////////////////
                   1293: // Device statistics (Log 0x04)
                   1294: 
                   1295: // See Section A.5 of
                   1296: //   ATA/ATAPI Command Set - 3 (ACS-3)
1.1.1.2   misho    1297: //   T13/2161-D Revision 2, February 21, 2012.
1.1       misho    1298: 
                   1299: struct devstat_entry_info
                   1300: {
                   1301:   short size; // #bytes of value, -1 for signed char
                   1302:   const char * name;
                   1303: };
                   1304: 
                   1305: const devstat_entry_info devstat_info_0x00[] = {
                   1306:   {  2, "List of supported log pages" },
                   1307:   {  0, 0 }
                   1308: };
                   1309: 
                   1310: const devstat_entry_info devstat_info_0x01[] = {
                   1311:   {  2, "General Statistics" },
                   1312:   {  4, "Lifetime Power-On Resets" },
                   1313:   {  4, "Power-on Hours" }, // spec says no flags(?)
                   1314:   {  6, "Logical Sectors Written" },
                   1315:   {  6, "Number of Write Commands" },
                   1316:   {  6, "Logical Sectors Read" },
                   1317:   {  6, "Number of Read Commands" },
1.1.1.2   misho    1318:   {  6, "Date and Time TimeStamp" }, // ACS-3
1.1       misho    1319:   {  0, 0 }
                   1320: };
                   1321: 
                   1322: const devstat_entry_info devstat_info_0x02[] = {
1.1.1.2   misho    1323:   {  2, "Free-Fall Statistics" },
1.1       misho    1324:   {  4, "Number of Free-Fall Events Detected" },
                   1325:   {  4, "Overlimit Shock Events" },
                   1326:   {  0, 0 }
                   1327: };
                   1328: 
                   1329: const devstat_entry_info devstat_info_0x03[] = {
                   1330:   {  2, "Rotating Media Statistics" },
                   1331:   {  4, "Spindle Motor Power-on Hours" },
                   1332:   {  4, "Head Flying Hours" },
                   1333:   {  4, "Head Load Events" },
                   1334:   {  4, "Number of Reallocated Logical Sectors" },
                   1335:   {  4, "Read Recovery Attempts" },
                   1336:   {  4, "Number of Mechanical Start Failures" },
                   1337:   {  4, "Number of Realloc. Candidate Logical Sectors" }, // ACS-3
                   1338:   {  0, 0 }
                   1339: };
                   1340: 
                   1341: const devstat_entry_info devstat_info_0x04[] = {
                   1342:   {  2, "General Errors Statistics" },
                   1343:   {  4, "Number of Reported Uncorrectable Errors" },
                   1344: //{  4, "Number of Resets Between Command Acceptance and Command Completion" },
                   1345:   {  4, "Resets Between Cmd Acceptance and Completion" },
                   1346:   {  0, 0 }
                   1347: };
                   1348: 
                   1349: const devstat_entry_info devstat_info_0x05[] = {
                   1350:   {  2, "Temperature Statistics" },
                   1351:   { -1, "Current Temperature" },
                   1352:   { -1, "Average Short Term Temperature" },
                   1353:   { -1, "Average Long Term Temperature" },
                   1354:   { -1, "Highest Temperature" },
                   1355:   { -1, "Lowest Temperature" },
                   1356:   { -1, "Highest Average Short Term Temperature" },
                   1357:   { -1, "Lowest Average Short Term Temperature" },
                   1358:   { -1, "Highest Average Long Term Temperature" },
                   1359:   { -1, "Lowest Average Long Term Temperature" },
                   1360:   {  4, "Time in Over-Temperature" },
                   1361:   { -1, "Specified Maximum Operating Temperature" },
                   1362:   {  4, "Time in Under-Temperature" },
                   1363:   { -1, "Specified Minimum Operating Temperature" },
                   1364:   {  0, 0 }
                   1365: };
                   1366: 
                   1367: const devstat_entry_info devstat_info_0x06[] = {
                   1368:   {  2, "Transport Statistics" },
                   1369:   {  4, "Number of Hardware Resets" },
                   1370:   {  4, "Number of ASR Events" },
                   1371:   {  4, "Number of Interface CRC Errors" },
                   1372:   {  0, 0 }
                   1373: };
                   1374: 
                   1375: const devstat_entry_info devstat_info_0x07[] = {
                   1376:   {  2, "Solid State Device Statistics" },
                   1377:   {  1, "Percentage Used Endurance Indicator" },
                   1378:   {  0, 0 }
                   1379: };
                   1380: 
                   1381: const devstat_entry_info * devstat_infos[] = {
                   1382:   devstat_info_0x00,
                   1383:   devstat_info_0x01,
                   1384:   devstat_info_0x02,
                   1385:   devstat_info_0x03,
                   1386:   devstat_info_0x04,
                   1387:   devstat_info_0x05,
                   1388:   devstat_info_0x06,
                   1389:   devstat_info_0x07
                   1390: };
                   1391: 
                   1392: const int num_devstat_infos = sizeof(devstat_infos)/sizeof(devstat_infos[0]);
                   1393: 
                   1394: static void print_device_statistics_page(const unsigned char * data, int page,
                   1395:   bool & need_trailer)
                   1396: {
                   1397:   const devstat_entry_info * info = (page < num_devstat_infos ? devstat_infos[page] : 0);
                   1398:   const char * name = (info ? info[0].name : "Unknown Statistics");
                   1399: 
                   1400:   // Check page number in header
                   1401:   static const char line[] = "  =====  =                =  == ";
                   1402:   if (!data[2]) {
                   1403:     pout("%3d%s%s (empty) ==\n", page, line, name);
                   1404:     return;
                   1405:   }
                   1406:   if (data[2] != page) {
                   1407:     pout("%3d%s%s (invalid page %d in header) ==\n", page, line, name, data[2]);
                   1408:     return;
                   1409:   }
                   1410: 
                   1411:   pout("%3d%s%s (rev %d) ==\n", page, line, name, data[0]);
                   1412: 
                   1413:   // Print entries
                   1414:   for (int i = 1, offset = 8; offset < 512-7; i++, offset+=8) {
                   1415:     // Check for last known entry
                   1416:     if (info && !info[i].size)
                   1417:       info = 0;
                   1418: 
                   1419:     // Skip unsupported entries
                   1420:     unsigned char flags = data[offset+7];
                   1421:     if (!(flags & 0x80))
                   1422:       continue;
                   1423: 
                   1424:     // Get value size, default to max if unknown
                   1425:     int size = (info ? info[i].size : 7);
                   1426: 
                   1427:     // Format value
                   1428:     char valstr[32];
                   1429:     if (flags & 0x40) { // valid flag
                   1430:       // Get value
                   1431:       int64_t val;
                   1432:       if (size < 0) {
                   1433:         val = (signed char)data[offset];
                   1434:       }
                   1435:       else {
                   1436:         val = 0;
                   1437:         for (int j = 0; j < size; j++)
                   1438:           val |= (int64_t)data[offset+j] << (j*8);
                   1439:       }
                   1440:       snprintf(valstr, sizeof(valstr), "%"PRId64, val);
                   1441:     }
                   1442:     else {
                   1443:       // Value not known (yet)
1.1.1.3   misho    1444:       valstr[0] = '-'; valstr[1] = 0;
1.1       misho    1445:     }
                   1446: 
                   1447:     pout("%3d  0x%03x  %d%c %15s%c %s\n",
                   1448:       page, offset,
                   1449:       abs(size),
                   1450:       (flags & 0x1f ? '+' : ' '), // unknown flags
                   1451:       valstr,
                   1452:       (flags & 0x20 ? '~' : ' '), // normalized flag
                   1453:       (info ? info[i].name : "Unknown"));
                   1454:     if (flags & 0x20)
                   1455:       need_trailer = true;
                   1456:   }
                   1457: }
                   1458: 
                   1459: static bool print_device_statistics(ata_device * device, unsigned nsectors,
                   1460:   const std::vector<int> & single_pages, bool all_pages, bool ssd_page)
                   1461: {
                   1462:   // Read list of supported pages from page 0
                   1463:   unsigned char page_0[512] = {0, };
1.1.1.3   misho    1464:   if (!ataReadLogExt(device, 0x04, 0, 0, page_0, 1)) {
                   1465:     pout("Read Device Statistics page 0 failed\n\n");
1.1       misho    1466:     return false;
1.1.1.3   misho    1467:   }
1.1       misho    1468: 
                   1469:   unsigned char nentries = page_0[8];
                   1470:   if (!(page_0[2] == 0 && nentries > 0)) {
1.1.1.3   misho    1471:     pout("Device Statistics page 0 is invalid (page=%d, nentries=%d)\n\n", page_0[2], nentries);
1.1       misho    1472:     return false;
                   1473:   }
                   1474: 
                   1475:   // Prepare list of pages to print
                   1476:   std::vector<int> pages;
                   1477:   unsigned i;
                   1478:   if (all_pages) {
                   1479:     // Add all supported pages
                   1480:     for (i = 0; i < nentries; i++) {
                   1481:       int page = page_0[8+1+i];
                   1482:       if (page)
                   1483:         pages.push_back(page);
                   1484:     }
                   1485:     ssd_page = false;
                   1486:   }
                   1487:   // Add manually specified pages
                   1488:   bool print_page_0 = false;
                   1489:   for (i = 0; i < single_pages.size() || ssd_page; i++) {
                   1490:     int page = (i < single_pages.size() ? single_pages[i] : 7);
                   1491:     if (!page)
                   1492:       print_page_0 = true;
                   1493:     else if (page >= (int)nsectors)
                   1494:       pout("Device Statistics Log has only %u pages\n", nsectors);
                   1495:     else
                   1496:       pages.push_back(page);
                   1497:     if (page == 7)
                   1498:       ssd_page = false;
                   1499:   }
                   1500: 
                   1501:   // Print list of supported pages if requested
                   1502:   if (print_page_0) {
                   1503:     pout("Device Statistics (GP Log 0x04) supported pages\n");
                   1504:     pout("Page Description\n");
                   1505:     for (i = 0; i < nentries; i++) {
                   1506:       int page = page_0[8+1+i];
                   1507:       pout("%3d  %s\n", page,
                   1508:         (page < num_devstat_infos ? devstat_infos[page][0].name : "Unknown Statistics"));
                   1509:     }
                   1510:     pout("\n");
                   1511:   }
                   1512: 
                   1513:   // Read & print pages
                   1514:   if (!pages.empty()) {
                   1515:     pout("Device Statistics (GP Log 0x04)\n");
                   1516:     pout("Page Offset Size         Value  Description\n");
                   1517:     bool need_trailer = false;
                   1518: 
                   1519:     for (i = 0; i <  pages.size(); i++) {
                   1520:       int page = pages[i];
                   1521:       unsigned char page_n[512] = {0, };
1.1.1.3   misho    1522:       if (!ataReadLogExt(device, 0x04, 0, page, page_n, 1)) {
                   1523:         pout("Read Device Statistics page %d failed\n\n", page);
1.1       misho    1524:         return false;
1.1.1.3   misho    1525:       }
1.1       misho    1526:       print_device_statistics_page(page_n, page, need_trailer);
                   1527:     }
                   1528: 
                   1529:     if (need_trailer)
                   1530:       pout("%30s|_ ~ normalized value\n", "");
                   1531:     pout("\n");
                   1532:   }
                   1533: 
                   1534:   return true;
                   1535: }
                   1536: 
                   1537: 
                   1538: ///////////////////////////////////////////////////////////////////////
                   1539: 
                   1540: // Print log 0x11
                   1541: static void PrintSataPhyEventCounters(const unsigned char * data, bool reset)
                   1542: {
                   1543:   if (checksum(data))
                   1544:     checksumwarning("SATA Phy Event Counters");
                   1545:   pout("SATA Phy Event Counters (GP Log 0x11)\n");
                   1546:   if (data[0] || data[1] || data[2] || data[3])
                   1547:     pout("[Reserved: 0x%02x 0x%02x 0x%02x 0x%02x]\n",
                   1548:     data[0], data[1], data[2], data[3]);
                   1549:   pout("ID      Size     Value  Description\n");
                   1550: 
                   1551:   for (unsigned i = 4; ; ) {
                   1552:     // Get counter id and size (bits 14:12)
                   1553:     unsigned id = data[i] | (data[i+1] << 8);
                   1554:     unsigned size = ((id >> 12) & 0x7) << 1;
                   1555:     id &= 0x8fff;
                   1556: 
                   1557:     // End of counter table ?
                   1558:     if (!id)
                   1559:       break;
                   1560:     i += 2;
                   1561: 
                   1562:     if (!(2 <= size && size <= 8 && i + size < 512)) {
                   1563:       pout("0x%04x  %u: Invalid entry\n", id, size);
                   1564:       break;
                   1565:     }
                   1566: 
                   1567:     // Get value
                   1568:     uint64_t val = 0, max_val = 0;
                   1569:     for (unsigned j = 0; j < size; j+=2) {
                   1570:         val |= (uint64_t)(data[i+j] | (data[i+j+1] << 8)) << (j*8);
                   1571:         max_val |= (uint64_t)0xffffU << (j*8);
                   1572:     }
                   1573:     i += size;
                   1574: 
                   1575:     // Get name
                   1576:     const char * name;
                   1577:     switch (id) {
                   1578:       case 0x001: name = "Command failed due to ICRC error"; break; // Mandatory
                   1579:       case 0x002: name = "R_ERR response for data FIS"; break;
                   1580:       case 0x003: name = "R_ERR response for device-to-host data FIS"; break;
                   1581:       case 0x004: name = "R_ERR response for host-to-device data FIS"; break;
                   1582:       case 0x005: name = "R_ERR response for non-data FIS"; break;
                   1583:       case 0x006: name = "R_ERR response for device-to-host non-data FIS"; break;
                   1584:       case 0x007: name = "R_ERR response for host-to-device non-data FIS"; break;
                   1585:       case 0x008: name = "Device-to-host non-data FIS retries"; break;
                   1586:       case 0x009: name = "Transition from drive PhyRdy to drive PhyNRdy"; break;
                   1587:       case 0x00A: name = "Device-to-host register FISes sent due to a COMRESET"; break; // Mandatory
                   1588:       case 0x00B: name = "CRC errors within host-to-device FIS"; break;
                   1589:       case 0x00D: name = "Non-CRC errors within host-to-device FIS"; break;
                   1590:       case 0x00F: name = "R_ERR response for host-to-device data FIS, CRC"; break;
                   1591:       case 0x010: name = "R_ERR response for host-to-device data FIS, non-CRC"; break;
                   1592:       case 0x012: name = "R_ERR response for host-to-device non-data FIS, CRC"; break;
                   1593:       case 0x013: name = "R_ERR response for host-to-device non-data FIS, non-CRC"; break;
                   1594:       default:    name = (id & 0x8000 ? "Vendor specific" : "Unknown"); break;
                   1595:     }
                   1596: 
                   1597:     // Counters stop at max value, add '+' in this case
                   1598:     pout("0x%04x  %u %12"PRIu64"%c %s\n", id, size, val,
                   1599:       (val == max_val ? '+' : ' '), name);
                   1600:   }
                   1601:   if (reset)
                   1602:     pout("All counters reset\n");
                   1603:   pout("\n");
                   1604: }
                   1605: 
1.1.1.3   misho    1606: // Format milliseconds from error log entry as "DAYS+H:M:S.MSEC"
                   1607: static std::string format_milliseconds(unsigned msec)
                   1608: {
                   1609:   unsigned days  = msec  / 86400000U;
                   1610:   msec          -= days  * 86400000U;
                   1611:   unsigned hours = msec  / 3600000U;
                   1612:   msec          -= hours * 3600000U;
                   1613:   unsigned min   = msec  / 60000U;
                   1614:   msec          -= min   * 60000U;
                   1615:   unsigned sec   = msec  / 1000U;
                   1616:   msec          -= sec   * 1000U;
                   1617: 
                   1618:   std::string str;
                   1619:   if (days)
                   1620:     str = strprintf("%2ud+", days);
                   1621:   str += strprintf("%02u:%02u:%02u.%03u", hours, min, sec, msec);
                   1622:   return str;
                   1623: }
                   1624: 
1.1       misho    1625: // Get description for 'state' value from SMART Error Logs
                   1626: static const char * get_error_log_state_desc(unsigned state)
                   1627: {
                   1628:   state &= 0x0f;
                   1629:   switch (state){
                   1630:     case 0x0: return "in an unknown state";
                   1631:     case 0x1: return "sleeping";
                   1632:     case 0x2: return "in standby mode";
                   1633:     case 0x3: return "active or idle";
                   1634:     case 0x4: return "doing SMART Offline or Self-test";
                   1635:   default:
                   1636:     return (state < 0xb ? "in a reserved state"
                   1637:                         : "in a vendor specific state");
                   1638:   }
                   1639: }
                   1640: 
                   1641: // returns number of errors
                   1642: static int PrintSmartErrorlog(const ata_smart_errorlog *data,
1.1.1.3   misho    1643:                               firmwarebug_defs firmwarebugs)
1.1       misho    1644: {
                   1645:   pout("SMART Error Log Version: %d\n", (int)data->revnumber);
                   1646:   
                   1647:   // if no errors logged, return
                   1648:   if (!data->error_log_pointer){
                   1649:     pout("No Errors Logged\n\n");
                   1650:     return 0;
                   1651:   }
                   1652:   print_on();
                   1653:   // If log pointer out of range, return
                   1654:   if (data->error_log_pointer>5){
                   1655:     pout("Invalid Error Log index = 0x%02x (T13/1321D rev 1c "
                   1656:          "Section 8.41.6.8.2.2 gives valid range from 1 to 5)\n\n",
                   1657:          (int)data->error_log_pointer);
                   1658:     return 0;
                   1659:   }
                   1660: 
                   1661:   // Some internal consistency checking of the data structures
1.1.1.3   misho    1662:   if ((data->ata_error_count-data->error_log_pointer) % 5 && !firmwarebugs.is_set(BUG_SAMSUNG2)) {
1.1       misho    1663:     pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
                   1664:          data->ata_error_count,data->error_log_pointer);
                   1665:   }
                   1666:   
                   1667:   // starting printing error log info
                   1668:   if (data->ata_error_count<=5)
                   1669:     pout( "ATA Error Count: %d\n", (int)data->ata_error_count);
                   1670:   else
                   1671:     pout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
                   1672:            (int)data->ata_error_count);
                   1673:   print_off();
                   1674:   pout("\tCR = Command Register [HEX]\n"
                   1675:        "\tFR = Features Register [HEX]\n"
                   1676:        "\tSC = Sector Count Register [HEX]\n"
                   1677:        "\tSN = Sector Number Register [HEX]\n"
                   1678:        "\tCL = Cylinder Low Register [HEX]\n"
                   1679:        "\tCH = Cylinder High Register [HEX]\n"
                   1680:        "\tDH = Device/Head Register [HEX]\n"
                   1681:        "\tDC = Device Command Register [HEX]\n"
                   1682:        "\tER = Error register [HEX]\n"
                   1683:        "\tST = Status register [HEX]\n"
                   1684:        "Powered_Up_Time is measured from power on, and printed as\n"
                   1685:        "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
                   1686:        "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
                   1687:   
                   1688:   // now step through the five error log data structures (table 39 of spec)
                   1689:   for (int k = 4; k >= 0; k-- ) {
                   1690: 
                   1691:     // The error log data structure entries are a circular buffer
                   1692:     int j, i=(data->error_log_pointer+k)%5;
                   1693:     const ata_smart_errorlog_struct * elog = data->errorlog_struct+i;
                   1694:     const ata_smart_errorlog_error_struct * summary = &(elog->error_struct);
                   1695: 
                   1696:     // Spec says: unused error log structures shall be zero filled
                   1697:     if (nonempty(elog, sizeof(*elog))){
                   1698:       // Table 57 of T13/1532D Volume 1 Revision 3
                   1699:       const char *msgstate = get_error_log_state_desc(summary->state);
                   1700:       int days = (int)summary->timestamp/24;
                   1701: 
                   1702:       // See table 42 of ATA5 spec
                   1703:       print_on();
                   1704:       pout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
                   1705:              (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
                   1706:       print_off();
                   1707:       pout("  When the command that caused the error occurred, the device was %s.\n\n",msgstate);
                   1708:       pout("  After command completion occurred, registers were:\n"
                   1709:            "  ER ST SC SN CL CH DH\n"
                   1710:            "  -- -- -- -- -- -- --\n"
                   1711:            "  %02x %02x %02x %02x %02x %02x %02x",
                   1712:            (int)summary->error_register,
                   1713:            (int)summary->status,
                   1714:            (int)summary->sector_count,
                   1715:            (int)summary->sector_number,
                   1716:            (int)summary->cylinder_low,
                   1717:            (int)summary->cylinder_high,
                   1718:            (int)summary->drive_head);
                   1719:       // Add a description of the contents of the status and error registers
                   1720:       // if possible
1.1.1.3   misho    1721:       std::string st_er_desc = format_st_er_desc(elog);
                   1722:       if (!st_er_desc.empty())
                   1723:         pout("  %s", st_er_desc.c_str());
1.1       misho    1724:       pout("\n\n");
                   1725:       pout("  Commands leading to the command that caused the error were:\n"
                   1726:            "  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name\n"
                   1727:            "  -- -- -- -- -- -- -- --  ----------------  --------------------\n");
                   1728:       for ( j = 4; j >= 0; j--){
                   1729:         const ata_smart_errorlog_command_struct * thiscommand = elog->commands+j;
                   1730: 
                   1731:         // Spec says: unused data command structures shall be zero filled
                   1732:         if (nonempty(thiscommand, sizeof(*thiscommand))) {
                   1733:           pout("  %02x %02x %02x %02x %02x %02x %02x %02x  %16s  %s\n",
                   1734:                (int)thiscommand->commandreg,
                   1735:                (int)thiscommand->featuresreg,
                   1736:                (int)thiscommand->sector_count,
                   1737:                (int)thiscommand->sector_number,
                   1738:                (int)thiscommand->cylinder_low,
                   1739:                (int)thiscommand->cylinder_high,
                   1740:                (int)thiscommand->drive_head,
                   1741:                (int)thiscommand->devicecontrolreg,
1.1.1.3   misho    1742:                format_milliseconds(thiscommand->timestamp).c_str(),
1.1       misho    1743:                look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg));
                   1744:        }
                   1745:       }
                   1746:       pout("\n");
                   1747:     }
                   1748:   }
                   1749:   print_on();
                   1750:   if (printing_is_switchable)
                   1751:     pout("\n");
                   1752:   print_off();
                   1753:   return data->ata_error_count;  
                   1754: }
                   1755: 
                   1756: // Print SMART Extended Comprehensive Error Log (GP Log 0x03)
                   1757: static int PrintSmartExtErrorLog(const ata_smart_exterrlog * log,
                   1758:                                  unsigned nsectors, unsigned max_errors)
                   1759: {
                   1760:   pout("SMART Extended Comprehensive Error Log Version: %u (%u sectors)\n",
                   1761:        log->version, nsectors);
                   1762: 
                   1763:   if (!log->device_error_count) {
                   1764:     pout("No Errors Logged\n\n");
                   1765:     return 0;
                   1766:   }
                   1767:   print_on();
                   1768: 
                   1769:   // Check index
                   1770:   unsigned nentries = nsectors * 4;
                   1771:   unsigned erridx = log->error_log_index;
                   1772:   if (!(1 <= erridx && erridx <= nentries)){
                   1773:     // Some Samsung disks (at least SP1614C/SW100-25, HD300LJ/ZT100-12) use the
                   1774:     // former index from Summary Error Log (byte 1, now reserved) and set byte 2-3
                   1775:     // to 0.
                   1776:     if (!(erridx == 0 && 1 <= log->reserved1 && log->reserved1 <= nentries)) {
                   1777:       pout("Invalid Error Log index = 0x%04x (reserved = 0x%02x)\n", erridx, log->reserved1);
                   1778:       return 0;
                   1779:     }
                   1780:     pout("Invalid Error Log index = 0x%04x, trying reserved byte (0x%02x) instead\n", erridx, log->reserved1);
                   1781:     erridx = log->reserved1;
                   1782:   }
                   1783: 
                   1784:   // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
                   1785:   // it is 1-based in practice.
                   1786:   erridx--;
                   1787: 
                   1788:   // Calculate #errors to print
                   1789:   unsigned errcnt = log->device_error_count;
                   1790: 
                   1791:   if (errcnt <= nentries)
                   1792:     pout("Device Error Count: %u\n", log->device_error_count);
                   1793:   else {
                   1794:     errcnt = nentries;
                   1795:     pout("Device Error Count: %u (device log contains only the most recent %u errors)\n",
                   1796:          log->device_error_count, errcnt);
                   1797:   }
                   1798: 
                   1799:   if (max_errors < errcnt)
                   1800:     errcnt = max_errors;
                   1801: 
                   1802:   print_off();
                   1803:   pout("\tCR     = Command Register\n"
                   1804:        "\tFEATR  = Features Register\n"
                   1805:        "\tCOUNT  = Count (was: Sector Count) Register\n"
                   1806:        "\tLBA_48 = Upper bytes of LBA High/Mid/Low Registers ]  ATA-8\n"
                   1807:        "\tLH     = LBA High (was: Cylinder High) Register    ]   LBA\n"
                   1808:        "\tLM     = LBA Mid (was: Cylinder Low) Register      ] Register\n"
                   1809:        "\tLL     = LBA Low (was: Sector Number) Register     ]\n"
                   1810:        "\tDV     = Device (was: Device/Head) Register\n"
                   1811:        "\tDC     = Device Control Register\n"
                   1812:        "\tER     = Error register\n"
                   1813:        "\tST     = Status register\n"
                   1814:        "Powered_Up_Time is measured from power on, and printed as\n"
                   1815:        "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
                   1816:        "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
                   1817: 
                   1818:   // Iterate through circular buffer in reverse direction
                   1819:   for (unsigned i = 0, errnum = log->device_error_count;
                   1820:        i < errcnt; i++, errnum--, erridx = (erridx > 0 ? erridx - 1 : nentries - 1)) {
                   1821: 
                   1822:     const ata_smart_exterrlog_error_log & entry = log[erridx / 4].error_logs[erridx % 4];
                   1823: 
                   1824:     // Skip unused entries
                   1825:     if (!nonempty(&entry, sizeof(entry))) {
                   1826:       pout("Error %u [%u] log entry is empty\n", errnum, erridx);
                   1827:       continue;
                   1828:     }
                   1829: 
                   1830:     // Print error information
                   1831:     print_on();
                   1832:     const ata_smart_exterrlog_error & err = entry.error;
                   1833:     pout("Error %u [%u] occurred at disk power-on lifetime: %u hours (%u days + %u hours)\n",
                   1834:          errnum, erridx, err.timestamp, err.timestamp / 24, err.timestamp % 24);
                   1835:     print_off();
                   1836: 
                   1837:     pout("  When the command that caused the error occurred, the device was %s.\n\n",
                   1838:       get_error_log_state_desc(err.state));
                   1839: 
                   1840:     // Print registers
                   1841:     pout("  After command completion occurred, registers were:\n"
                   1842:          "  ER -- ST COUNT  LBA_48  LH LM LL DV DC\n"
                   1843:          "  -- -- -- == -- == == == -- -- -- -- --\n"
                   1844:          "  %02x -- %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
                   1845:          err.error_register,
                   1846:          err.status_register,
                   1847:          err.count_register_hi,
                   1848:          err.count_register,
                   1849:          err.lba_high_register_hi,
                   1850:          err.lba_mid_register_hi,
                   1851:          err.lba_low_register_hi,
                   1852:          err.lba_high_register,
                   1853:          err.lba_mid_register,
                   1854:          err.lba_low_register,
                   1855:          err.device_register,
                   1856:          err.device_control_register);
                   1857: 
                   1858:     // Add a description of the contents of the status and error registers
                   1859:     // if possible
1.1.1.3   misho    1860:     std::string st_er_desc = format_st_er_desc(&entry);
                   1861:     if (!st_er_desc.empty())
                   1862:       pout("  %s", st_er_desc.c_str());
1.1       misho    1863:     pout("\n\n");
                   1864: 
                   1865:     // Print command history
                   1866:     pout("  Commands leading to the command that caused the error were:\n"
                   1867:          "  CR FEATR COUNT  LBA_48  LH LM LL DV DC  Powered_Up_Time  Command/Feature_Name\n"
                   1868:          "  -- == -- == -- == == == -- -- -- -- --  ---------------  --------------------\n");
                   1869:     for (int ci = 4; ci >= 0; ci--) {
                   1870:       const ata_smart_exterrlog_command & cmd = entry.commands[ci];
                   1871: 
                   1872:       // Skip unused entries
                   1873:       if (!nonempty(&cmd, sizeof(cmd)))
                   1874:         continue;
                   1875: 
                   1876:       // Print registers, timestamp and ATA command name
                   1877:       pout("  %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %16s  %s\n",
                   1878:            cmd.command_register,
                   1879:            cmd.features_register_hi,
                   1880:            cmd.features_register,
                   1881:            cmd.count_register_hi,
                   1882:            cmd.count_register,
                   1883:            cmd.lba_high_register_hi,
                   1884:            cmd.lba_mid_register_hi,
                   1885:            cmd.lba_low_register_hi,
                   1886:            cmd.lba_high_register,
                   1887:            cmd.lba_mid_register,
                   1888:            cmd.lba_low_register,
                   1889:            cmd.device_register,
                   1890:            cmd.device_control_register,
1.1.1.3   misho    1891:            format_milliseconds(cmd.timestamp).c_str(),
1.1       misho    1892:            look_up_ata_command(cmd.command_register, cmd.features_register));
                   1893:     }
                   1894:     pout("\n");
                   1895:   }
                   1896: 
                   1897:   print_on();
                   1898:   if (printing_is_switchable)
                   1899:     pout("\n");
                   1900:   print_off();
                   1901:   return log->device_error_count;
                   1902: }
                   1903: 
                   1904: // Print SMART Extended Self-test Log (GP Log 0x07)
                   1905: static int PrintSmartExtSelfTestLog(const ata_smart_extselftestlog * log,
                   1906:                                     unsigned nsectors, unsigned max_entries)
                   1907: {
                   1908:   pout("SMART Extended Self-test Log Version: %u (%u sectors)\n",
                   1909:        log->version, nsectors);
                   1910: 
                   1911:   if (!log->log_desc_index){
                   1912:     pout("No self-tests have been logged.  [To run self-tests, use: smartctl -t]\n\n");
                   1913:     return 0;
                   1914:   }
                   1915: 
                   1916:   // Check index
                   1917:   unsigned nentries = nsectors * 19;
                   1918:   unsigned logidx = log->log_desc_index;
                   1919:   if (logidx > nentries) {
                   1920:     pout("Invalid Self-test Log index = 0x%04x (reserved = 0x%02x)\n", logidx, log->reserved1);
                   1921:     return 0;
                   1922:   }
                   1923: 
                   1924:   // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
                   1925:   // it is 1-based in practice.
                   1926:   logidx--;
                   1927: 
                   1928:   bool print_header = true;
                   1929:   int errcnt = 0, igncnt = 0;
                   1930:   int ext_ok_testnum = -1;
                   1931: 
                   1932:   // Iterate through circular buffer in reverse direction
                   1933:   for (unsigned i = 0, testnum = 1;
                   1934:        i < nentries && testnum <= max_entries;
                   1935:        i++, logidx = (logidx > 0 ? logidx - 1 : nentries - 1)) {
                   1936: 
                   1937:     const ata_smart_extselftestlog_desc & entry = log[logidx / 19].log_descs[logidx % 19];
                   1938: 
                   1939:     // Skip unused entries
                   1940:     if (!nonempty(&entry, sizeof(entry)))
                   1941:       continue;
                   1942: 
                   1943:     // Get LBA
                   1944:     const unsigned char * b = entry.failing_lba;
                   1945:     uint64_t lba48 = b[0]
                   1946:         | (          b[1] <<  8)
                   1947:         | (          b[2] << 16)
                   1948:         | ((uint64_t)b[3] << 24)
                   1949:         | ((uint64_t)b[4] << 32)
                   1950:         | ((uint64_t)b[5] << 40);
                   1951: 
                   1952:     // Print entry
                   1953:     int state = ataPrintSmartSelfTestEntry(testnum, entry.self_test_type,
                   1954:       entry.self_test_status, entry.timestamp, lba48,
                   1955:       false /*!print_error_only*/, print_header);
                   1956: 
                   1957:     if (state < 0) {
                   1958:       // Self-test showed an error
                   1959:       if (ext_ok_testnum < 0)
                   1960:         errcnt++;
                   1961:       else
                   1962:         // Newer successful extended self-test exits
                   1963:         igncnt++;
                   1964:     }
                   1965:     else if (state > 0 && ext_ok_testnum < 0) {
                   1966:       // Latest successful extended self-test
                   1967:       ext_ok_testnum = testnum;
                   1968:     }
                   1969:     testnum++;
                   1970:   }
                   1971: 
                   1972:   if (igncnt)
                   1973:     pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
                   1974:       igncnt, igncnt+errcnt, ext_ok_testnum);
                   1975: 
                   1976:   pout("\n");
                   1977:   return errcnt;
                   1978: }
                   1979: 
                   1980: static void ataPrintSelectiveSelfTestLog(const ata_selective_self_test_log * log, const ata_smart_values * sv)
                   1981: {
                   1982:   int i,field1,field2;
                   1983:   const char *msg;
                   1984:   char tmp[64];
                   1985:   uint64_t maxl=0,maxr=0;
                   1986:   uint64_t current=log->currentlba;
                   1987:   uint64_t currentend=current+65535;
                   1988: 
                   1989:   // print data structure revision number
                   1990:   pout("SMART Selective self-test log data structure revision number %d\n",(int)log->logversion);
                   1991:   if (1 != log->logversion)
                   1992:     pout("Note: revision number not 1 implies that no selective self-test has ever been run\n");
                   1993:   
                   1994:   switch((sv->self_test_exec_status)>>4){
                   1995:   case  0:msg="Completed";
                   1996:     break;
                   1997:   case  1:msg="Aborted_by_host";
                   1998:     break;
                   1999:   case  2:msg="Interrupted";
                   2000:     break;
                   2001:   case  3:msg="Fatal_error";
                   2002:     break;
                   2003:   case  4:msg="Completed_unknown_failure";
                   2004:     break;
                   2005:   case  5:msg="Completed_electrical_failure";
                   2006:     break;
                   2007:   case  6:msg="Completed_servo/seek_failure";
                   2008:     break;
                   2009:   case  7:msg="Completed_read_failure";
                   2010:     break;
                   2011:   case  8:msg="Completed_handling_damage??";
                   2012:     break;
                   2013:   case 15:msg="Self_test_in_progress";
                   2014:     break;
                   2015:   default:msg="Unknown_status ";
                   2016:     break;
                   2017:   }
                   2018: 
                   2019:   // find the number of columns needed for printing. If in use, the
                   2020:   // start/end of span being read-scanned...
                   2021:   if (log->currentspan>5) {
                   2022:     maxl=current;
                   2023:     maxr=currentend;
                   2024:   }
                   2025:   for (i=0; i<5; i++) {
                   2026:     uint64_t start=log->span[i].start;
                   2027:     uint64_t end  =log->span[i].end; 
                   2028:     // ... plus max start/end of each of the five test spans.
                   2029:     if (start>maxl)
                   2030:       maxl=start;
                   2031:     if (end > maxr)
                   2032:       maxr=end;
                   2033:   }
                   2034:   
                   2035:   // we need at least 7 characters wide fields to accomodate the
                   2036:   // labels
                   2037:   if ((field1=snprintf(tmp,64, "%"PRIu64, maxl))<7)
                   2038:     field1=7;
                   2039:   if ((field2=snprintf(tmp,64, "%"PRIu64, maxr))<7)
                   2040:     field2=7;
                   2041: 
                   2042:   // now print the five test spans
                   2043:   pout(" SPAN  %*s  %*s  CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
                   2044: 
                   2045:   for (i=0; i<5; i++) {
                   2046:     uint64_t start=log->span[i].start;
                   2047:     uint64_t end=log->span[i].end;
                   2048:     
                   2049:     if ((i+1)==(int)log->currentspan)
                   2050:       // this span is currently under test
                   2051:       pout("    %d  %*"PRIu64"  %*"PRIu64"  %s [%01d0%% left] (%"PRIu64"-%"PRIu64")\n",
                   2052:           i+1, field1, start, field2, end, msg,
                   2053:           (int)(sv->self_test_exec_status & 0xf), current, currentend);
                   2054:     else
                   2055:       // this span is not currently under test
                   2056:       pout("    %d  %*"PRIu64"  %*"PRIu64"  Not_testing\n",
                   2057:           i+1, field1, start, field2, end);
                   2058:   }  
                   2059:   
                   2060:   // if we are currently read-scanning, print LBAs and the status of
                   2061:   // the read scan
                   2062:   if (log->currentspan>5)
                   2063:     pout("%5d  %*"PRIu64"  %*"PRIu64"  Read_scanning %s\n",
                   2064:         (int)log->currentspan, field1, current, field2, currentend,
                   2065:         OfflineDataCollectionStatus(sv->offline_data_collection_status));
                   2066:   
                   2067:   /* Print selective self-test flags.  Possible flag combinations are
                   2068:      (numbering bits from 0-15):
                   2069:      Bit-1 Bit-3   Bit-4
                   2070:      Scan  Pending Active
                   2071:      0     *       *       Don't scan
                   2072:      1     0       0       Will carry out scan after selective test
                   2073:      1     1       0       Waiting to carry out scan after powerup
                   2074:      1     0       1       Currently scanning       
                   2075:      1     1       1       Currently scanning
                   2076:   */
                   2077:   
                   2078:   pout("Selective self-test flags (0x%x):\n", (unsigned int)log->flags);
                   2079:   if (log->flags & SELECTIVE_FLAG_DOSCAN) {
                   2080:     if (log->flags & SELECTIVE_FLAG_ACTIVE)
                   2081:       pout("  Currently read-scanning the remainder of the disk.\n");
                   2082:     else if (log->flags & SELECTIVE_FLAG_PENDING)
                   2083:       pout("  Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
                   2084:           (int)log->pendingtime);
                   2085:     else
                   2086:       pout("  After scanning selected spans, read-scan remainder of disk.\n");
                   2087:   }
                   2088:   else
                   2089:     pout("  After scanning selected spans, do NOT read-scan remainder of disk.\n");
                   2090:   
                   2091:   // print pending time
                   2092:   pout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
                   2093:        (int)log->pendingtime);
                   2094: 
                   2095:   return; 
                   2096: }
                   2097: 
                   2098: // Format SCT Temperature value
1.1.1.3   misho    2099: static const char * sct_ptemp(signed char x, char (& buf)[20])
1.1       misho    2100: {
                   2101:   if (x == -128 /*0x80 = unknown*/)
1.1.1.3   misho    2102:     return " ?";
                   2103:   snprintf(buf, sizeof(buf), "%2d", x);
1.1       misho    2104:   return buf;
                   2105: }
                   2106: 
1.1.1.3   misho    2107: static const char * sct_pbar(int x, char (& buf)[64])
1.1       misho    2108: {
                   2109:   if (x <= 19)
                   2110:     x = 0;
                   2111:   else
                   2112:     x -= 19;
                   2113:   bool ov = false;
                   2114:   if (x > 40) {
                   2115:     x = 40; ov = true;
                   2116:   }
                   2117:   if (x > 0) {
                   2118:     memset(buf, '*', x);
                   2119:     if (ov)
                   2120:       buf[x-1] = '+';
                   2121:     buf[x] = 0;
                   2122:   }
                   2123:   else {
                   2124:     buf[0] = '-'; buf[1] = 0;
                   2125:   }
                   2126:   return buf;
                   2127: }
                   2128: 
                   2129: static const char * sct_device_state_msg(unsigned char state)
                   2130: {
                   2131:   switch (state) {
                   2132:     case 0: return "Active";
                   2133:     case 1: return "Stand-by";
                   2134:     case 2: return "Sleep";
                   2135:     case 3: return "DST executing in background";
                   2136:     case 4: return "SMART Off-line Data Collection executing in background";
                   2137:     case 5: return "SCT command executing in background";
                   2138:     default:return "Unknown";
                   2139:   }
                   2140: }
                   2141: 
                   2142: // Print SCT Status
                   2143: static int ataPrintSCTStatus(const ata_sct_status_response * sts)
                   2144: {
                   2145:   pout("SCT Status Version:                  %u\n", sts->format_version);
                   2146:   pout("SCT Version (vendor specific):       %u (0x%04x)\n", sts->sct_version, sts->sct_version);
                   2147:   pout("SCT Support Level:                   %u\n", sts->sct_spec);
                   2148:   pout("Device State:                        %s (%u)\n",
                   2149:     sct_device_state_msg(sts->device_state), sts->device_state);
                   2150:   char buf1[20], buf2[20];
1.1.1.2   misho    2151:   if (   !sts->min_temp && !sts->life_min_temp
                   2152:       && !sts->under_limit_count && !sts->over_limit_count) {
1.1       misho    2153:     // "Reserved" fields not set, assume "old" format version 2
1.1.1.2   misho    2154:     // Table 11 of T13/1701DT-N (SMART Command Transport) Revision 5, February 2005
                   2155:     // Table 54 of T13/1699-D (ATA8-ACS) Revision 3e, July 2006
1.1       misho    2156:     pout("Current Temperature:                 %s Celsius\n",
                   2157:       sct_ptemp(sts->hda_temp, buf1));
                   2158:     pout("Power Cycle Max Temperature:         %s Celsius\n",
                   2159:       sct_ptemp(sts->max_temp, buf2));
                   2160:     pout("Lifetime    Max Temperature:         %s Celsius\n",
                   2161:       sct_ptemp(sts->life_max_temp, buf2));
                   2162:   }
                   2163:   else {
                   2164:     // Assume "new" format version 2 or version 3
1.1.1.2   misho    2165:     // T13/e06152r0-3 (Additional SCT Temperature Statistics), August - October 2006
                   2166:     // Table 60 of T13/1699-D (ATA8-ACS) Revision 3f, December 2006  (format version 2)
                   2167:     // Table 80 of T13/1699-D (ATA8-ACS) Revision 6a, September 2008 (format version 3)
1.1       misho    2168:     pout("Current Temperature:                    %s Celsius\n",
                   2169:       sct_ptemp(sts->hda_temp, buf1));
                   2170:     pout("Power Cycle Min/Max Temperature:     %s/%s Celsius\n",
                   2171:       sct_ptemp(sts->min_temp, buf1), sct_ptemp(sts->max_temp, buf2));
                   2172:     pout("Lifetime    Min/Max Temperature:     %s/%s Celsius\n",
                   2173:       sct_ptemp(sts->life_min_temp, buf1), sct_ptemp(sts->life_max_temp, buf2));
1.1.1.2   misho    2174:     signed char avg = sts->byte205; // Average Temperature from e06152r0-2, removed in e06152r3
                   2175:     if (0 < avg && sts->life_min_temp <= avg && avg <= sts->life_max_temp)
                   2176:       pout("Lifetime    Average Temperature:        %2d Celsius\n", avg);
1.1       misho    2177:     pout("Under/Over Temperature Limit Count:  %2u/%u\n",
                   2178:       sts->under_limit_count, sts->over_limit_count);
                   2179:   }
                   2180:   return 0;
                   2181: }
                   2182: 
                   2183: // Print SCT Temperature History Table
                   2184: static int ataPrintSCTTempHist(const ata_sct_temperature_history_table * tmh)
                   2185: {
1.1.1.3   misho    2186:   char buf1[20], buf2[20], buf3[64];
                   2187:   pout("SCT Temperature History Version:     %u%s\n", tmh->format_version,
                   2188:        (tmh->format_version != 2 ? " (Unknown, should be 2)" : ""));
1.1       misho    2189:   pout("Temperature Sampling Period:         %u minute%s\n",
                   2190:     tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
                   2191:   pout("Temperature Logging Interval:        %u minute%s\n",
                   2192:     tmh->interval,        (tmh->interval==1?"":"s"));
                   2193:   pout("Min/Max recommended Temperature:     %s/%s Celsius\n",
                   2194:     sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
                   2195:   pout("Min/Max Temperature Limit:           %s/%s Celsius\n",
                   2196:     sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
                   2197:   pout("Temperature History Size (Index):    %u (%u)\n", tmh->cb_size, tmh->cb_index);
1.1.1.3   misho    2198: 
1.1       misho    2199:   if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
1.1.1.3   misho    2200:     if (!tmh->cb_size)
                   2201:       pout("Temperature History is empty\n");
                   2202:     else
                   2203:       pout("Invalid Temperature History Size or Index\n");
1.1       misho    2204:     return 0;
                   2205:   }
                   2206: 
                   2207:   // Print table
                   2208:   pout("\nIndex    Estimated Time   Temperature Celsius\n");
                   2209:   unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
                   2210:   unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
                   2211:   time_t t = time(0) - (tmh->cb_size-1) * interval * 60;
                   2212:   t -= t % (interval * 60);
                   2213:   while (n < tmh->cb_size) {
                   2214:     // Find range of identical temperatures
                   2215:     unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
                   2216:     while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
                   2217:       n2++; i2 = (i2+1) % tmh->cb_size;
                   2218:     }
                   2219:     // Print range
                   2220:     while (n < n2) {
                   2221:       if (n == n1 || n == n2-1 || n2 <= n1+3) {
                   2222:         char date[30];
                   2223:         // TODO: Don't print times < boot time
                   2224:         strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&t));
                   2225:         pout(" %3u    %s    %s  %s\n", i, date,
1.1.1.3   misho    2226:           sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf3));
1.1       misho    2227:       }
                   2228:       else if (n == n1+1) {
                   2229:         pout(" ...    ..(%3u skipped).    ..  %s\n",
1.1.1.3   misho    2230:           n2-n1-2, sct_pbar(tmh->cb[i], buf3));
1.1       misho    2231:       }
                   2232:       t += interval * 60; i = (i+1) % tmh->cb_size; n++;
                   2233:     }
                   2234:   }
                   2235:   //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
                   2236: 
                   2237:   return 0;
                   2238: }
                   2239: 
                   2240: // Print SCT Error Recovery Control timers
                   2241: static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer)
                   2242: {
                   2243:   pout("SCT Error Recovery Control%s:\n", (set ? " set to" : ""));
                   2244:   if (!read_timer)
                   2245:     pout("           Read: Disabled\n");
                   2246:   else
                   2247:     pout("           Read: %6d (%0.1f seconds)\n", read_timer, read_timer/10.0);
                   2248:   if (!write_timer)
                   2249:     pout("          Write: Disabled\n");
                   2250:   else
                   2251:     pout("          Write: %6d (%0.1f seconds)\n", write_timer, write_timer/10.0);
                   2252: }
                   2253: 
1.1.1.2   misho    2254: static void print_aam_level(const char * msg, int level, int recommended = -1)
                   2255: {
                   2256:   // Table 56 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
                   2257:   // Obsolete since T13/2015-D (ACS-2) Revision 4a, December 9, 2010
                   2258:   const char * s;
                   2259:   if (level == 0)
                   2260:     s = "vendor specific";
                   2261:   else if (level < 128)
                   2262:     s = "unknown/retired";
                   2263:   else if (level == 128)
                   2264:     s = "quiet";
                   2265:   else if (level < 254)
                   2266:     s = "intermediate";
                   2267:   else if (level == 254)
                   2268:     s = "maximum performance";
                   2269:   else
                   2270:     s = "reserved";
                   2271: 
                   2272:   if (recommended >= 0)
                   2273:     pout("%s%d (%s), recommended: %d\n", msg, level, s, recommended);
                   2274:   else
                   2275:     pout("%s%d (%s)\n", msg, level, s);
                   2276: }
                   2277: 
                   2278: static void print_apm_level(const char * msg, int level)
                   2279: {
                   2280:   // Table 120 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
                   2281:   const char * s;
                   2282:   if (!(1 <= level && level <= 254))
                   2283:     s = "reserved";
                   2284:   else if (level == 1)
                   2285:     s = "minimum power consumption with standby";
                   2286:   else if (level < 128)
                   2287:     s = "intermediate level with standby";
                   2288:   else if (level == 128)
                   2289:     s = "minimum power consumption without standby";
                   2290:   else if (level < 254)
                   2291:     s = "intermediate level without standby";
                   2292:   else
                   2293:     s = "maximum performance";
                   2294: 
                   2295:   pout("%s%d (%s)\n", msg, level, s);
                   2296: }
                   2297: 
                   2298: static void print_ata_security_status(const char * msg, unsigned short state)
                   2299: {
                   2300:     const char * s1, * s2 = "", * s3 = "", * s4 = "";
                   2301: 
                   2302:     // Table 6 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
                   2303:     if (!(state & 0x0001))
                   2304:       s1 = "Unavailable";
                   2305:     else if (!(state & 0x0002)) {
                   2306:       s1 = "Disabled, ";
                   2307:       if (!(state & 0x0008))
                   2308:         s2 = "NOT FROZEN [SEC1]";
                   2309:       else
                   2310:         s2 = "frozen [SEC2]";
                   2311:     }
                   2312:     else {
                   2313:       s1 = "ENABLED, PW level ";
                   2314:       if (!(state & 0x0020))
                   2315:         s2 = "HIGH";
                   2316:       else
                   2317:         s2 = "MAX";
                   2318: 
                   2319:       if (!(state & 0x0004)) {
                   2320:          s3 = ", not locked, ";
                   2321:         if (!(state & 0x0008))
                   2322:           s4 = "not frozen [SEC5]";
                   2323:         else
                   2324:           s4 = "frozen [SEC6]";
                   2325:       }
                   2326:       else {
                   2327:         s3 = ", **LOCKED** [SEC4]";
                   2328:         if (state & 0x0010)
                   2329:           s4 = ", PW ATTEMPTS EXCEEDED";
                   2330:       }
                   2331:     }
                   2332: 
                   2333:     pout("%s%s%s%s%s\n", msg, s1, s2, s3, s4);
                   2334: }
                   2335: 
                   2336: static void print_standby_timer(const char * msg, int timer, const ata_identify_device & drive)
                   2337: {
                   2338:   const char * s1 = 0;
                   2339:   int hours = 0, minutes = 0 , seconds = 0;
                   2340: 
                   2341:   // Table 63 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
                   2342:   if (timer == 0)
                   2343:     s1 = "disabled";
                   2344:   else if (timer <= 240)
                   2345:     seconds = timer * 5, minutes = seconds / 60, seconds %= 60;
                   2346:   else if (timer <= 251)
                   2347:     minutes = (timer - 240) * 30, hours = minutes / 60, minutes %= 60;
                   2348:   else if (timer == 252)
                   2349:     minutes = 21;
                   2350:   else if (timer == 253)
                   2351:     s1 = "between 8 hours and 12 hours";
                   2352:   else if (timer == 255)
                   2353:     minutes = 21, seconds = 15;
                   2354:   else
                   2355:     s1 = "reserved";
                   2356: 
                   2357:   const char * s2 = "", * s3 = "";
                   2358:   if (!(drive.words047_079[49-47] & 0x2000))
                   2359:     s2 = " or vendor-specific";
                   2360:   if (timer > 0 && (drive.words047_079[50-47] & 0xc001) == 0x4001)
                   2361:     s3 = ", a vendor-specific minimum applies";
                   2362: 
                   2363:   if (s1)
                   2364:     pout("%s%d (%s%s%s)\n", msg, timer, s1, s2, s3);
                   2365:   else
                   2366:     pout("%s%d (%02d:%02d:%02d%s%s)\n", msg, timer, hours, minutes, seconds, s2, s3);
                   2367: }
                   2368: 
1.1       misho    2369: 
                   2370: int ataPrintMain (ata_device * device, const ata_print_options & options)
                   2371: {
                   2372:   // If requested, check power mode first
                   2373:   const char * powername = 0;
                   2374:   bool powerchg = false;
                   2375:   if (options.powermode) {
                   2376:     unsigned char powerlimit = 0xff;
                   2377:     int powermode = ataCheckPowerMode(device);
                   2378:     switch (powermode) {
                   2379:       case -1:
1.1.1.2   misho    2380:         if (device->is_syscall_unsup()) {
1.1       misho    2381:           pout("CHECK POWER MODE not implemented, ignoring -n option\n"); break;
                   2382:         }
                   2383:         powername = "SLEEP";   powerlimit = 2;
                   2384:         break;
                   2385:       case 0:
                   2386:         powername = "STANDBY"; powerlimit = 3; break;
                   2387:       case 0x80:
                   2388:         powername = "IDLE";    powerlimit = 4; break;
                   2389:       case 0xff:
                   2390:         powername = "ACTIVE or IDLE"; break;
                   2391:       default:
                   2392:         pout("CHECK POWER MODE returned unknown value 0x%02x, ignoring -n option\n", powermode);
                   2393:         break;
                   2394:     }
                   2395:     if (powername) {
                   2396:       if (options.powermode >= powerlimit) {
                   2397:         pout("Device is in %s mode, exit(%d)\n", powername, FAILPOWER);
                   2398:         return FAILPOWER;
                   2399:       }
                   2400:       powerchg = (powermode != 0xff); // SMART tests will spin up drives
                   2401:     }
                   2402:   }
                   2403: 
                   2404:   // SMART values needed ?
                   2405:   bool need_smart_val = (
                   2406:           options.smart_check_status
                   2407:        || options.smart_general_values
                   2408:        || options.smart_vendor_attrib
                   2409:        || options.smart_error_log
                   2410:        || options.smart_selftest_log
                   2411:        || options.smart_selective_selftest_log
                   2412:        || options.smart_ext_error_log
                   2413:        || options.smart_ext_selftest_log
                   2414:        || options.smart_auto_offl_enable
                   2415:        || options.smart_auto_offl_disable
                   2416:        || options.smart_selftest_type != -1
                   2417:   );
                   2418: 
                   2419:   // SMART must be enabled ?
                   2420:   bool need_smart_enabled = (
                   2421:           need_smart_val
                   2422:        || options.smart_auto_save_enable
                   2423:        || options.smart_auto_save_disable
                   2424:   );
                   2425: 
                   2426:   // SMART feature set needed ?
                   2427:   bool need_smart_support = (
                   2428:           need_smart_enabled
                   2429:        || options.smart_enable
                   2430:        || options.smart_disable
                   2431:   );
                   2432: 
                   2433:   // SMART and GP log directories needed ?
                   2434:   bool need_smart_logdir = options.smart_logdir;
                   2435: 
                   2436:   bool need_gp_logdir  = (
                   2437:           options.gp_logdir
                   2438:        || options.smart_ext_error_log
                   2439:        || options.smart_ext_selftest_log
                   2440:        || options.devstat_all_pages
                   2441:        || options.devstat_ssd_page
                   2442:        || !options.devstat_pages.empty()
                   2443:   );
                   2444: 
                   2445:   unsigned i;
                   2446:   for (i = 0; i < options.log_requests.size(); i++) {
                   2447:     if (options.log_requests[i].gpl)
                   2448:       need_gp_logdir = true;
                   2449:     else
                   2450:       need_smart_logdir = true;
                   2451:   }
                   2452: 
                   2453:   // SCT commands needed ?
                   2454:   bool need_sct_support = (
                   2455:           options.sct_temp_sts
                   2456:        || options.sct_temp_hist
                   2457:        || options.sct_temp_int
                   2458:        || options.sct_erc_get
                   2459:        || options.sct_erc_set
1.1.1.4 ! misho    2460:        || options.sct_wcache_reorder_get
        !          2461:        || options.sct_wcache_reorder_set
1.1       misho    2462:   );
                   2463: 
                   2464:   // Exit if no further options specified
1.1.1.3   misho    2465:   if (!(   options.drive_info || options.show_presets
                   2466:         || need_smart_support || need_smart_logdir
                   2467:         || need_gp_logdir     || need_sct_support
                   2468:         || options.sataphy
                   2469:         || options.identify_word_level >= 0
                   2470:         || options.get_set_used                      )) {
1.1       misho    2471:     if (powername)
                   2472:       pout("Device is in %s mode\n", powername);
                   2473:     else
                   2474:       pout("ATA device successfully opened\n\n"
                   2475:            "Use 'smartctl -a' (or '-x') to print SMART (and more) information\n\n");
                   2476:     return 0;
                   2477:   }
                   2478: 
                   2479:   // Start by getting Drive ID information.  We need this, to know if SMART is supported.
                   2480:   int returnval = 0;
                   2481:   ata_identify_device drive; memset(&drive, 0, sizeof(drive));
1.1.1.3   misho    2482:   unsigned char raw_drive[sizeof(drive)]; memset(&raw_drive, 0, sizeof(raw_drive));
                   2483: 
1.1       misho    2484:   device->clear_err();
1.1.1.3   misho    2485:   int retid = ata_read_identity(device, &drive, options.fix_swapped_id, raw_drive);
1.1       misho    2486:   if (retid < 0) {
1.1.1.3   misho    2487:     pout("Read Device Identity failed: %s\n\n",
1.1       misho    2488:          (device->get_errno() ? device->get_errmsg() : "Unknown error"));
                   2489:     failuretest(MANDATORY_CMD, returnval|=FAILID);
                   2490:   }
                   2491:   else if (!nonempty(&drive, sizeof(drive))) {
1.1.1.3   misho    2492:     pout("Read Device Identity failed: empty IDENTIFY data\n\n");
1.1       misho    2493:     failuretest(MANDATORY_CMD, returnval|=FAILID);
                   2494:   }
                   2495: 
                   2496:   // If requested, show which presets would be used for this drive and exit.
                   2497:   if (options.show_presets) {
                   2498:     show_presets(&drive);
                   2499:     return 0;
                   2500:   }
                   2501: 
                   2502:   // Use preset vendor attribute options unless user has requested otherwise.
                   2503:   ata_vendor_attr_defs attribute_defs = options.attribute_defs;
1.1.1.3   misho    2504:   firmwarebug_defs firmwarebugs = options.firmwarebugs;
1.1       misho    2505:   const drive_settings * dbentry = 0;
                   2506:   if (!options.ignore_presets)
                   2507:     dbentry = lookup_drive_apply_presets(&drive, attribute_defs,
1.1.1.3   misho    2508:       firmwarebugs);
1.1       misho    2509: 
1.1.1.3   misho    2510:   // Get capacity, sector sizes and rotation rate
1.1       misho    2511:   ata_size_info sizes;
                   2512:   ata_get_size_info(&drive, sizes);
1.1.1.3   misho    2513:   int rpm = ata_get_rotation_rate(&drive);
                   2514: 
                   2515:   // Print ATA IDENTIFY info if requested
                   2516:   if (options.identify_word_level >= 0) {
                   2517:     pout("=== ATA IDENTIFY DATA ===\n");
                   2518:     // Pass raw data without endianness adjustments
                   2519:     ata_print_identify_data(raw_drive, (options.identify_word_level > 0), options.identify_bit_level);
                   2520:   }
1.1       misho    2521: 
                   2522:   // Print most drive identity information if requested
                   2523:   if (options.drive_info) {
                   2524:     pout("=== START OF INFORMATION SECTION ===\n");
1.1.1.3   misho    2525:     print_drive_info(&drive, sizes, rpm, dbentry);
1.1       misho    2526:   }
                   2527: 
                   2528:   // Check and print SMART support and state
                   2529:   int smart_supported = -1, smart_enabled = -1;
                   2530:   if (need_smart_support || options.drive_info) {
                   2531: 
                   2532:     // Packet device ?
                   2533:     if (retid > 0) {
                   2534:       pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
                   2535:            packetdevicetype(retid-1));
                   2536:     }
                   2537:     else {
                   2538:       // Disk device: SMART supported and enabled ?
                   2539:       smart_supported = ataSmartSupport(&drive);
                   2540:       smart_enabled = ataIsSmartEnabled(&drive);
                   2541: 
                   2542:       if (smart_supported < 0)
                   2543:         pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
                   2544:       if (smart_supported && smart_enabled < 0) {
                   2545:         pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
                   2546:         if (need_smart_support) {
                   2547:           failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   2548:           // check SMART support by trying a command
                   2549:           pout("                  Checking to be sure by trying SMART RETURN STATUS command.\n");
                   2550:           if (ataDoesSmartWork(device))
                   2551:             smart_supported = smart_enabled = 1;
                   2552:         }
                   2553:       }
                   2554:       else if (smart_supported < 0 && (smart_enabled > 0 || dbentry))
                   2555:         // Assume supported if enabled or in drive database
                   2556:         smart_supported = 1;
                   2557: 
                   2558:       if (smart_supported < 0)
                   2559:         pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
                   2560:       else if (!smart_supported)
                   2561:         pout("SMART support is: Unavailable - device lacks SMART capability.\n");
                   2562:       else {
                   2563:         if (options.drive_info)
                   2564:           pout("SMART support is: Available - device has SMART capability.\n");
                   2565:         if (smart_enabled >= 0) {
                   2566:           if (device->ata_identify_is_cached()) {
                   2567:             if (options.drive_info)
                   2568:               pout("                  %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
                   2569:                       (smart_enabled?"En":"Dis"));
                   2570:             smart_enabled = ataDoesSmartWork(device);
                   2571:           }
                   2572:           if (options.drive_info)
                   2573:             pout("SMART support is: %s\n",
                   2574:                   (smart_enabled ? "Enabled" : "Disabled"));
                   2575:         }
                   2576:       }
                   2577:     }
                   2578:   }
                   2579: 
1.1.1.2   misho    2580:   // Print AAM status
                   2581:   if (options.get_aam) {
                   2582:     if ((drive.command_set_2 & 0xc200) != 0x4200) // word083
                   2583:       pout("AAM feature is:   Unavailable\n");
                   2584:     else if (!(drive.word086 & 0x0200))
                   2585:       pout("AAM feature is:   Disabled\n");
                   2586:     else
                   2587:       print_aam_level("AAM level is:     ", drive.words088_255[94-88] & 0xff,
                   2588:         drive.words088_255[94-88] >> 8);
                   2589:   }
                   2590: 
                   2591:   // Print APM status
                   2592:   if (options.get_apm) {
                   2593:     if ((drive.command_set_2 & 0xc008) != 0x4008) // word083
                   2594:       pout("APM feature is:   Unavailable\n");
                   2595:     else if (!(drive.word086 & 0x0008))
                   2596:       pout("APM feature is:   Disabled\n");
                   2597:     else
                   2598:       print_apm_level("APM level is:     ", drive.words088_255[91-88] & 0xff);
                   2599:   }
                   2600: 
                   2601:   // Print read look-ahead status
                   2602:   if (options.get_lookahead) {
                   2603:     pout("Rd look-ahead is: %s\n",
                   2604:       (   (drive.command_set_2 & 0xc000) != 0x4000 // word083
                   2605:        || !(drive.command_set_1 & 0x0040)) ? "Unavailable" : // word082
                   2606:        !(drive.cfs_enable_1 & 0x0040) ? "Disabled" : "Enabled"); // word085
                   2607:   }
                   2608: 
                   2609:   // Print write cache status
                   2610:   if (options.get_wcache) {
                   2611:     pout("Write cache is:   %s\n",
                   2612:       (   (drive.command_set_2 & 0xc000) != 0x4000 // word083
                   2613:        || !(drive.command_set_1 & 0x0020)) ? "Unavailable" : // word082
                   2614:        !(drive.cfs_enable_1 & 0x0020) ? "Disabled" : "Enabled"); // word085
                   2615:   }
                   2616: 
                   2617:   // Print ATA security status
                   2618:   if (options.get_security)
                   2619:     print_ata_security_status("ATA Security is:  ", drive.words088_255[128-88]);
                   2620: 
1.1.1.4 ! misho    2621:   // Check if SCT commands available
        !          2622:   bool sct_ok = false;
        !          2623:   if (need_sct_support) {
        !          2624:     if (!isSCTCapable(&drive)) {
        !          2625:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
        !          2626:     }
        !          2627:     else
        !          2628:       sct_ok = true;
        !          2629:   }
        !          2630: 
        !          2631:   // Print write cache reordering status
        !          2632:   if (sct_ok && options.sct_wcache_reorder_get) {
        !          2633:     int wcache_reorder=ataGetSetSCTWriteCacheReordering(device,
        !          2634:       false /* enable */, false /* persistent */, false /*set*/);
        !          2635:       pout("Wt Cache Reorder: ");
        !          2636:       switch(wcache_reorder) {
        !          2637:         case 0: /* not defined in standard but returned on some drives if not set */
        !          2638:         pout("Unknown"); break;
        !          2639:         case 1:
        !          2640:         pout("Enabled"); break;
        !          2641:         case 2:
        !          2642:         pout("Disabled"); break;
        !          2643:         default: /* error? */
        !          2644:         pout("N/A"); break;
        !          2645:       }
        !          2646:       pout("\n");
        !          2647:   }
        !          2648:   if (!sct_ok && options.sct_wcache_reorder_get) {
        !          2649:     pout("Wt Cache Reorder: Unavailable\n");
        !          2650:   }
        !          2651: 
1.1       misho    2652:   // Print remaining drive info
                   2653:   if (options.drive_info) {
                   2654:     // Print the (now possibly changed) power mode if available
                   2655:     if (powername)
                   2656:       pout("Power mode %s   %s\n", (powerchg?"was:":"is: "), powername);
                   2657:     pout("\n");
                   2658:   }
                   2659: 
                   2660:   // Exit if SMART is not supported but must be available to proceed
                   2661:   if (smart_supported <= 0 && need_smart_support)
                   2662:     failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   2663: 
                   2664:   // START OF THE ENABLE/DISABLE SECTION OF THE CODE
                   2665:   if (   options.smart_disable           || options.smart_enable
                   2666:       || options.smart_auto_save_disable || options.smart_auto_save_enable
1.1.1.4 ! misho    2667:       || options.smart_auto_offl_disable || options.smart_auto_offl_enable
        !          2668:       || options.set_aam || options.set_apm || options.set_lookahead
        !          2669:       || options.set_wcache || options.set_security_freeze || options.set_standby
        !          2670:       || options.sct_wcache_reorder_set)
1.1       misho    2671:     pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
                   2672:   
1.1.1.2   misho    2673:   // Enable/Disable AAM
                   2674:   if (options.set_aam) {
                   2675:     if (options.set_aam > 0) {
                   2676:       if (!ata_set_features(device, ATA_ENABLE_AAM, options.set_aam-1)) {
                   2677:         pout("AAM enable failed: %s\n", device->get_errmsg());
                   2678:         returnval |= FAILSMART;
                   2679:       }
                   2680:       else
                   2681:         print_aam_level("AAM set to level ", options.set_aam-1);
                   2682:     }
                   2683:     else {
                   2684:       if (!ata_set_features(device, ATA_DISABLE_AAM)) {
                   2685:         pout("AAM disable failed: %s\n", device->get_errmsg());
                   2686:         returnval |= FAILSMART;
                   2687:       }
                   2688:       else
                   2689:         pout("AAM disabled\n");
                   2690:     }
                   2691:   }
                   2692: 
                   2693:   // Enable/Disable APM
                   2694:   if (options.set_apm) {
                   2695:     if (options.set_apm > 0) {
                   2696:       if (!ata_set_features(device, ATA_ENABLE_APM, options.set_apm-1)) {
                   2697:         pout("APM enable failed: %s\n", device->get_errmsg());
                   2698:         returnval |= FAILSMART;
                   2699:       }
                   2700:       else
                   2701:         print_apm_level("APM set to level ", options.set_apm-1);
                   2702:     }
                   2703:     else {
                   2704:       if (!ata_set_features(device, ATA_DISABLE_APM)) {
                   2705:         pout("APM disable failed: %s\n", device->get_errmsg());
                   2706:         returnval |= FAILSMART;
                   2707:       }
                   2708:       else
                   2709:         pout("APM disabled\n");
                   2710:     }
                   2711:   }
                   2712: 
                   2713:   // Enable/Disable read look-ahead
                   2714:   if (options.set_lookahead) {
                   2715:     bool enable = (options.set_lookahead > 0);
                   2716:     if (!ata_set_features(device, (enable ? ATA_ENABLE_READ_LOOK_AHEAD : ATA_DISABLE_READ_LOOK_AHEAD))) {
                   2717:         pout("Read look-ahead %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
                   2718:         returnval |= FAILSMART;
                   2719:     }
                   2720:     else
                   2721:       pout("Read look-ahead %sabled\n", (enable ? "en" : "dis"));
                   2722:   }
                   2723: 
                   2724:   // Enable/Disable write cache
                   2725:   if (options.set_wcache) {
                   2726:     bool enable = (options.set_wcache > 0);
                   2727:     if (!ata_set_features(device, (enable ? ATA_ENABLE_WRITE_CACHE : ATA_DISABLE_WRITE_CACHE))) {
                   2728:         pout("Write cache %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
                   2729:         returnval |= FAILSMART;
                   2730:     }
                   2731:     else
                   2732:       pout("Write cache %sabled\n", (enable ? "en" : "dis"));
                   2733:   }
                   2734: 
1.1.1.4 ! misho    2735:   // Enable/Disable write cache reordering
        !          2736:   if (sct_ok && options.sct_wcache_reorder_set) {
        !          2737:     bool enable = (options.sct_wcache_reorder_set > 0);
        !          2738: 
        !          2739:     int wcache_reorder=ataGetSetSCTWriteCacheReordering(device,
        !          2740:       enable, false /* persistent */, true /*set*/);
        !          2741: 
        !          2742:     if (wcache_reorder < 0) {
        !          2743:         pout("Write cache reordering %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
        !          2744:         returnval |= FAILSMART;
        !          2745:     }
        !          2746:     else
        !          2747:       pout("Write cache reordering %sabled\n", (enable ? "en" : "dis"));
        !          2748:   }
        !          2749: 
1.1.1.2   misho    2750:   // Freeze ATA security
                   2751:   if (options.set_security_freeze) {
                   2752:     if (!ata_nodata_command(device, ATA_SECURITY_FREEZE_LOCK)) {
                   2753:         pout("ATA SECURITY FREEZE LOCK failed: %s\n", device->get_errmsg());
                   2754:         returnval |= FAILSMART;
                   2755:     }
                   2756:     else
                   2757:       pout("ATA Security set to frozen mode\n");
                   2758:   }
                   2759: 
                   2760:   // Set standby timer
                   2761:   if (options.set_standby) {
                   2762:     if (!ata_nodata_command(device, ATA_IDLE, options.set_standby-1)) {
                   2763:         pout("ATA IDLE command failed: %s\n", device->get_errmsg());
                   2764:         returnval |= FAILSMART;
                   2765:     }
                   2766:     else
                   2767:       print_standby_timer("Standby timer set to ", options.set_standby-1, drive);
                   2768:   }
                   2769: 
1.1       misho    2770:   // Enable/Disable SMART commands
                   2771:   if (options.smart_enable) {
                   2772:     if (ataEnableSmart(device)) {
1.1.1.3   misho    2773:       pout("SMART Enable failed: %s\n\n", device->get_errmsg());
1.1       misho    2774:       failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   2775:     }
                   2776:     else {
                   2777:       pout("SMART Enabled.\n");
                   2778:       smart_enabled = 1;
                   2779:     }
                   2780:   }
                   2781: 
                   2782:   // Turn off SMART on device
                   2783:   if (options.smart_disable) {
                   2784:     if (ataDisableSmart(device)) {
1.1.1.3   misho    2785:       pout("SMART Disable failed: %s\n\n", device->get_errmsg());
1.1       misho    2786:       failuretest(MANDATORY_CMD,returnval|=FAILSMART);
                   2787:     }
                   2788:   }
                   2789: 
                   2790:   // Exit if SMART is disabled but must be enabled to proceed
1.1.1.3   misho    2791:   if (options.smart_disable || (smart_enabled <= 0 && need_smart_enabled && !is_permissive())) {
1.1       misho    2792:     pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
1.1.1.3   misho    2793:     if (!options.smart_disable)
                   2794:       pout("(override with '-T permissive' option)\n");
1.1       misho    2795:     return returnval;
                   2796:   }
                   2797: 
                   2798:   // Enable/Disable Auto-save attributes
                   2799:   if (options.smart_auto_save_enable) {
                   2800:     if (ataEnableAutoSave(device)){
1.1.1.3   misho    2801:       pout("SMART Enable Attribute Autosave failed: %s\n\n", device->get_errmsg());
1.1       misho    2802:       failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   2803:     }
                   2804:     else
                   2805:       pout("SMART Attribute Autosave Enabled.\n");
                   2806:   }
                   2807: 
                   2808:   if (options.smart_auto_save_disable) {
                   2809:     if (ataDisableAutoSave(device)){
1.1.1.3   misho    2810:       pout("SMART Disable Attribute Autosave failed: %s\n\n", device->get_errmsg());
1.1       misho    2811:       failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   2812:     }
                   2813:     else
                   2814:       pout("SMART Attribute Autosave Disabled.\n");
                   2815:   }
                   2816: 
                   2817:   // Read SMART values and thresholds if necessary
                   2818:   ata_smart_values smartval; memset(&smartval, 0, sizeof(smartval));
                   2819:   ata_smart_thresholds_pvt smartthres; memset(&smartthres, 0, sizeof(smartthres));
                   2820:   bool smart_val_ok = false, smart_thres_ok = false;
                   2821: 
                   2822:   if (need_smart_val) {
                   2823:     if (ataReadSmartValues(device, &smartval)) {
1.1.1.3   misho    2824:       pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
1.1       misho    2825:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2826:     }
                   2827:     else {
                   2828:       smart_val_ok = true;
                   2829: 
                   2830:       if (options.smart_check_status || options.smart_vendor_attrib) {
                   2831:         if (ataReadSmartThresholds(device, &smartthres)){
1.1.1.3   misho    2832:           pout("Read SMART Thresholds failed: %s\n\n", device->get_errmsg());
1.1       misho    2833:           failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2834:         }
                   2835:         else
                   2836:           smart_thres_ok = true;
                   2837:       }
                   2838:     }
                   2839:   }
                   2840: 
                   2841:   // Enable/Disable Off-line testing
                   2842:   bool needupdate = false;
                   2843:   if (options.smart_auto_offl_enable) {
                   2844:     if (!isSupportAutomaticTimer(&smartval)){
1.1.1.3   misho    2845:       pout("SMART Automatic Timers not supported\n\n");
1.1       misho    2846:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2847:     }
                   2848:     needupdate = smart_val_ok;
                   2849:     if (ataEnableAutoOffline(device)){
1.1.1.3   misho    2850:       pout("SMART Enable Automatic Offline failed: %s\n\n", device->get_errmsg());
1.1       misho    2851:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2852:     }
                   2853:     else
                   2854:       pout("SMART Automatic Offline Testing Enabled every four hours.\n");
                   2855:   }
                   2856: 
                   2857:   if (options.smart_auto_offl_disable) {
                   2858:     if (!isSupportAutomaticTimer(&smartval)){
1.1.1.3   misho    2859:       pout("SMART Automatic Timers not supported\n\n");
1.1       misho    2860:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2861:     }
                   2862:     needupdate = smart_val_ok;
                   2863:     if (ataDisableAutoOffline(device)){
1.1.1.3   misho    2864:       pout("SMART Disable Automatic Offline failed: %s\n\n", device->get_errmsg());
1.1       misho    2865:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2866:     }
                   2867:     else
                   2868:       pout("SMART Automatic Offline Testing Disabled.\n");
                   2869:   }
                   2870: 
                   2871:   if (needupdate && ataReadSmartValues(device, &smartval)){
1.1.1.3   misho    2872:     pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
1.1       misho    2873:     failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2874:     smart_val_ok = false;
                   2875:   }
                   2876: 
                   2877:   // all this for a newline!
                   2878:   if (   options.smart_disable           || options.smart_enable
                   2879:       || options.smart_auto_save_disable || options.smart_auto_save_enable
1.1.1.4 ! misho    2880:       || options.smart_auto_offl_disable || options.smart_auto_offl_enable
        !          2881:       || options.set_aam || options.set_apm || options.set_lookahead
        !          2882:       || options.set_wcache || options.set_security_freeze || options.set_standby
        !          2883:       || options.sct_wcache_reorder_set)
1.1       misho    2884:     pout("\n");
                   2885: 
                   2886:   // START OF READ-ONLY OPTIONS APART FROM -V and -i
                   2887:   if (   options.smart_check_status  || options.smart_general_values
                   2888:       || options.smart_vendor_attrib || options.smart_error_log
                   2889:       || options.smart_selftest_log  || options.smart_selective_selftest_log
                   2890:       || options.smart_ext_error_log || options.smart_ext_selftest_log
                   2891:       || options.sct_temp_sts        || options.sct_temp_hist               )
                   2892:     pout("=== START OF READ SMART DATA SECTION ===\n");
                   2893:   
                   2894:   // Check SMART status
                   2895:   if (options.smart_check_status) {
                   2896: 
                   2897:     switch (ataSmartStatus2(device)) {
                   2898: 
                   2899:     case 0:
                   2900:       // The case where the disk health is OK
                   2901:       pout("SMART overall-health self-assessment test result: PASSED\n");
                   2902:       if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
                   2903:         if (options.smart_vendor_attrib)
                   2904:           pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
                   2905:         else {
                   2906:           print_on();
                   2907:           pout("Please note the following marginal Attributes:\n");
1.1.1.3   misho    2908:           PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
1.1       misho    2909:         } 
                   2910:         returnval|=FAILAGE;
                   2911:       }
                   2912:       else
                   2913:         pout("\n");
                   2914:       break;
                   2915:       
                   2916:     case 1:
                   2917:       // The case where the disk health is NOT OK
                   2918:       print_on();
                   2919:       pout("SMART overall-health self-assessment test result: FAILED!\n"
                   2920:            "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
                   2921:       print_off();
                   2922:       if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
                   2923:         returnval|=FAILATTR;
                   2924:         if (options.smart_vendor_attrib)
                   2925:           pout("See vendor-specific Attribute list for failed Attributes.\n\n");
                   2926:         else {
                   2927:           print_on();
                   2928:           pout("Failed Attributes:\n");
1.1.1.3   misho    2929:           PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
1.1       misho    2930:         }
                   2931:       }
                   2932:       else
                   2933:         pout("No failed Attributes found.\n\n");   
                   2934:       returnval|=FAILSTATUS;
                   2935:       print_off();
                   2936:       break;
                   2937: 
                   2938:     case -1:
                   2939:     default:
                   2940:       // Something went wrong with the SMART STATUS command.
                   2941:       // The ATA SMART RETURN STATUS command provides the result in the ATA output
                   2942:       // registers. Buggy ATA/SATA drivers and SAT Layers often do not properly
                   2943:       // return the registers values.
                   2944:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   2945:       if (!(smart_val_ok && smart_thres_ok)) {
                   2946:         print_on();
                   2947:         pout("SMART overall-health self-assessment test result: UNKNOWN!\n"
                   2948:              "SMART Status, Attributes and Thresholds cannot be read.\n\n");
                   2949:       }
                   2950:       else if (find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
                   2951:         print_on();
                   2952:         pout("SMART overall-health self-assessment test result: FAILED!\n"
                   2953:              "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
                   2954:         print_off();
                   2955:         returnval|=FAILATTR;
                   2956:         returnval|=FAILSTATUS;
                   2957:         if (options.smart_vendor_attrib)
                   2958:           pout("See vendor-specific Attribute list for failed Attributes.\n\n");
                   2959:         else {
                   2960:           print_on();
                   2961:           pout("Failed Attributes:\n");
1.1.1.3   misho    2962:           PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
1.1       misho    2963:         }
                   2964:       }
                   2965:       else {
                   2966:         pout("SMART overall-health self-assessment test result: PASSED\n");
                   2967:         pout("Warning: This result is based on an Attribute check.\n");
                   2968:         if (find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
                   2969:           if (options.smart_vendor_attrib)
                   2970:             pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
                   2971:           else {
                   2972:             print_on();
                   2973:             pout("Please note the following marginal Attributes:\n");
1.1.1.3   misho    2974:             PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
1.1       misho    2975:           } 
                   2976:           returnval|=FAILAGE;
                   2977:         }
                   2978:         else
                   2979:           pout("\n");
                   2980:       } 
                   2981:       print_off();
                   2982:       break;
                   2983:     } // end of switch statement
                   2984:     
                   2985:     print_off();
                   2986:   } // end of checking SMART Status
                   2987:   
                   2988:   // Print general SMART values
                   2989:   if (smart_val_ok && options.smart_general_values)
1.1.1.3   misho    2990:     PrintGeneralSmartValues(&smartval, &drive, firmwarebugs);
1.1       misho    2991: 
                   2992:   // Print vendor-specific attributes
                   2993:   if (smart_val_ok && options.smart_vendor_attrib) {
                   2994:     print_on();
1.1.1.3   misho    2995:     PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm,
1.1       misho    2996:                               (printing_is_switchable ? 2 : 0), options.output_format);
                   2997:     print_off();
                   2998:   }
                   2999: 
                   3000:   // If GP Log is supported use smart log directory for
                   3001:   // error and selftest log support check.
                   3002:   if (   isGeneralPurposeLoggingCapable(&drive)
                   3003:       && (   options.smart_error_log || options.smart_selftest_log
                   3004:           || options.retry_error_log || options.retry_selftest_log))
                   3005:     need_smart_logdir = true;
                   3006: 
                   3007:   ata_smart_log_directory smartlogdir_buf, gplogdir_buf;
                   3008:   const ata_smart_log_directory * smartlogdir = 0, * gplogdir = 0;
                   3009: 
                   3010:   // Read SMART Log directory
                   3011:   if (need_smart_logdir) {
1.1.1.3   misho    3012:     if (firmwarebugs.is_set(BUG_NOLOGDIR))
                   3013:       smartlogdir = fake_logdir(&smartlogdir_buf, options);
                   3014:     else if (ataReadLogDirectory(device, &smartlogdir_buf, false)) {
                   3015:       pout("Read SMART Log Directory failed: %s\n\n", device->get_errmsg());
1.1       misho    3016:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3017:     }
                   3018:     else
                   3019:       smartlogdir = &smartlogdir_buf;
                   3020:   }
                   3021: 
                   3022:   // Read GP Log directory
                   3023:   if (need_gp_logdir) {
1.1.1.3   misho    3024:     if (firmwarebugs.is_set(BUG_NOLOGDIR))
                   3025:       gplogdir = fake_logdir(&gplogdir_buf, options);
                   3026:     else if (ataReadLogDirectory(device, &gplogdir_buf, true)) {
                   3027:       pout("Read GP Log Directory failed\n\n");
1.1       misho    3028:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3029:     }
                   3030:     else
                   3031:       gplogdir = &gplogdir_buf;
                   3032:   }
                   3033: 
                   3034:   // Print log directories
1.1.1.3   misho    3035:   if ((options.gp_logdir && gplogdir) || (options.smart_logdir && smartlogdir)) {
                   3036:     if (firmwarebugs.is_set(BUG_NOLOGDIR))
                   3037:       pout("Log Directories not read due to '-F nologdir' option\n\n");
                   3038:     else
                   3039:       PrintLogDirectories(gplogdir, smartlogdir);
                   3040:   }
1.1       misho    3041: 
                   3042:   // Print log pages
                   3043:   for (i = 0; i < options.log_requests.size(); i++) {
                   3044:     const ata_log_request & req = options.log_requests[i];
                   3045: 
                   3046:     const char * type;
                   3047:     unsigned max_nsectors;
                   3048:     if (req.gpl) {
                   3049:       type = "General Purpose";
                   3050:       max_nsectors = GetNumLogSectors(gplogdir, req.logaddr, true);
                   3051:     }
                   3052:     else {
                   3053:       type = "SMART";
                   3054:       max_nsectors = GetNumLogSectors(smartlogdir, req.logaddr, false);
                   3055:     }
                   3056: 
                   3057:     if (!max_nsectors) {
                   3058:       if (!is_permissive()) {
                   3059:         pout("%s Log 0x%02x does not exist (override with '-T permissive' option)\n", type, req.logaddr);
                   3060:         continue;
                   3061:       }
                   3062:       max_nsectors = req.page+1;
                   3063:     }
                   3064:     if (max_nsectors <= req.page) {
                   3065:       pout("%s Log 0x%02x has only %u sectors, output skipped\n", type, req.logaddr, max_nsectors);
                   3066:       continue;
                   3067:     }
                   3068: 
                   3069:     unsigned ns = req.nsectors;
                   3070:     if (ns > max_nsectors - req.page) {
                   3071:       if (req.nsectors != ~0U) // "FIRST-max"
                   3072:         pout("%s Log 0x%02x has only %u sectors, output truncated\n", type, req.logaddr, max_nsectors);
                   3073:       ns = max_nsectors - req.page;
                   3074:     }
                   3075: 
                   3076:     // SMART log don't support sector offset, start with first sector
                   3077:     unsigned offs = (req.gpl ? 0 : req.page);
                   3078: 
                   3079:     raw_buffer log_buf((offs + ns) * 512);
                   3080:     bool ok;
                   3081:     if (req.gpl)
                   3082:       ok = ataReadLogExt(device, req.logaddr, 0x00, req.page, log_buf.data(), ns);
                   3083:     else
                   3084:       ok = ataReadSmartLog(device, req.logaddr, log_buf.data(), offs + ns);
                   3085:     if (!ok)
                   3086:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3087:     else
                   3088:       PrintLogPages(type, log_buf.data() + offs*512, req.logaddr, req.page, ns, max_nsectors);
                   3089:   }
                   3090: 
                   3091:   // Print SMART Extendend Comprehensive Error Log
                   3092:   bool do_smart_error_log = options.smart_error_log;
                   3093:   if (options.smart_ext_error_log) {
                   3094:     bool ok = false;
                   3095:     unsigned nsectors = GetNumLogSectors(gplogdir, 0x03, true);
                   3096:     if (!nsectors)
1.1.1.3   misho    3097:       pout("SMART Extended Comprehensive Error Log (GP Log 0x03) not supported\n\n");
1.1       misho    3098:     else if (nsectors >= 256)
1.1.1.3   misho    3099:       pout("SMART Extended Comprehensive Error Log size %u not supported\n\n", nsectors);
1.1       misho    3100:     else {
                   3101:       raw_buffer log_03_buf(nsectors * 512);
                   3102:       ata_smart_exterrlog * log_03 = (ata_smart_exterrlog *)log_03_buf.data();
1.1.1.3   misho    3103:       if (!ataReadExtErrorLog(device, log_03, nsectors, firmwarebugs)) {
                   3104:         pout("Read SMART Extended Comprehensive Error Log failed\n\n");
1.1       misho    3105:         failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1.1.1.3   misho    3106:       }
1.1       misho    3107:       else {
                   3108:         if (PrintSmartExtErrorLog(log_03, nsectors, options.smart_ext_error_log))
                   3109:           returnval |= FAILERR;
                   3110:         ok = true;
                   3111:       }
                   3112:     }
                   3113: 
                   3114:     if (!ok) {
                   3115:       if (options.retry_error_log)
                   3116:         do_smart_error_log = true;
                   3117:       else if (!do_smart_error_log)
                   3118:         pout("Try '-l [xerror,]error' to read traditional SMART Error Log\n");
                   3119:     }
                   3120:   }
                   3121: 
                   3122:   // Print SMART error log
                   3123:   if (do_smart_error_log) {
                   3124:     if (!(   ( smartlogdir && GetNumLogSectors(smartlogdir, 0x01, false))
                   3125:           || (!smartlogdir && isSmartErrorLogCapable(&smartval, &drive) )
                   3126:           || is_permissive()                                             )) {
1.1.1.3   misho    3127:       pout("SMART Error Log not supported\n\n");
1.1       misho    3128:     }
                   3129:     else {
                   3130:       ata_smart_errorlog smarterror; memset(&smarterror, 0, sizeof(smarterror));
1.1.1.3   misho    3131:       if (ataReadErrorLog(device, &smarterror, firmwarebugs)) {
                   3132:         pout("Read SMART Error Log failed: %s\n\n", device->get_errmsg());
1.1       misho    3133:         failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3134:       }
                   3135:       else {
                   3136:         // quiet mode is turned on inside PrintSmartErrorLog()
1.1.1.3   misho    3137:         if (PrintSmartErrorlog(&smarterror, firmwarebugs))
1.1       misho    3138:          returnval|=FAILERR;
                   3139:         print_off();
                   3140:       }
                   3141:     }
                   3142:   }
                   3143: 
                   3144:   // Print SMART Extendend Self-test Log
                   3145:   bool do_smart_selftest_log = options.smart_selftest_log;
                   3146:   if (options.smart_ext_selftest_log) {
                   3147:     bool ok = false;
                   3148:     unsigned nsectors = GetNumLogSectors(gplogdir, 0x07, true);
                   3149:     if (!nsectors)
1.1.1.3   misho    3150:       pout("SMART Extended Self-test Log (GP Log 0x07) not supported\n\n");
1.1       misho    3151:     else if (nsectors >= 256)
1.1.1.3   misho    3152:       pout("SMART Extended Self-test Log size %u not supported\n\n", nsectors);
1.1       misho    3153:     else {
                   3154:       raw_buffer log_07_buf(nsectors * 512);
                   3155:       ata_smart_extselftestlog * log_07 = (ata_smart_extselftestlog *)log_07_buf.data();
1.1.1.3   misho    3156:       if (!ataReadExtSelfTestLog(device, log_07, nsectors)) {
                   3157:         pout("Read SMART Extended Self-test Log failed\n\n");
1.1       misho    3158:         failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1.1.1.3   misho    3159:       }
1.1       misho    3160:       else {
                   3161:         if (PrintSmartExtSelfTestLog(log_07, nsectors, options.smart_ext_selftest_log))
                   3162:           returnval |= FAILLOG;
                   3163:         ok = true;
                   3164:       }
                   3165:     }
                   3166: 
                   3167:     if (!ok) {
                   3168:       if (options.retry_selftest_log)
                   3169:         do_smart_selftest_log = true;
                   3170:       else if (!do_smart_selftest_log)
                   3171:         pout("Try '-l [xselftest,]selftest' to read traditional SMART Self Test Log\n");
                   3172:     }
                   3173:   }
                   3174: 
                   3175:   // Print SMART self-test log
                   3176:   if (do_smart_selftest_log) {
                   3177:     if (!(   ( smartlogdir && GetNumLogSectors(smartlogdir, 0x06, false))
                   3178:           || (!smartlogdir && isSmartTestLogCapable(&smartval, &drive)  )
                   3179:           || is_permissive()                                             )) {
1.1.1.3   misho    3180:       pout("SMART Self-test Log not supported\n\n");
1.1       misho    3181:     }
                   3182:     else {
                   3183:       ata_smart_selftestlog smartselftest; memset(&smartselftest, 0, sizeof(smartselftest));
1.1.1.3   misho    3184:       if (ataReadSelfTestLog(device, &smartselftest, firmwarebugs)) {
                   3185:         pout("Read SMART Self-test Log failed: %s\n\n", device->get_errmsg());
1.1       misho    3186:         failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3187:       }
                   3188:       else {
                   3189:         print_on();
1.1.1.3   misho    3190:         if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, firmwarebugs))
1.1       misho    3191:           returnval |= FAILLOG;
                   3192:         print_off();
                   3193:         pout("\n");
                   3194:       }
                   3195:     }
                   3196:   }
                   3197: 
                   3198:   // Print SMART selective self-test log
                   3199:   if (options.smart_selective_selftest_log) {
                   3200:     ata_selective_self_test_log log;
                   3201: 
                   3202:     if (!isSupportSelectiveSelfTest(&smartval))
1.1.1.3   misho    3203:       pout("Selective Self-tests/Logging not supported\n\n");
1.1       misho    3204:     else if(ataReadSelectiveSelfTestLog(device, &log)) {
1.1.1.3   misho    3205:       pout("Read SMART Selective Self-test Log failed: %s\n\n", device->get_errmsg());
1.1       misho    3206:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3207:     }
                   3208:     else {
                   3209:       print_on();
                   3210:       // If any errors were found, they are logged in the SMART Self-test log.
                   3211:       // So there is no need to print the Selective Self Test log in silent
                   3212:       // mode.
                   3213:       if (!printing_is_switchable)
                   3214:         ataPrintSelectiveSelfTestLog(&log, &smartval);
                   3215:       print_off();
                   3216:       pout("\n");
                   3217:     }
                   3218:   }
                   3219: 
1.1.1.4 ! misho    3220:   if(!sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int
        !          3221:                  || options.sct_erc_get || options.sct_erc_set                        ))
        !          3222:     pout("SCT Commands not supported\n\n");
1.1       misho    3223: 
                   3224:   // Print SCT status and temperature history table
                   3225:   if (sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int)) {
                   3226:     for (;;) {
                   3227:       if (options.sct_temp_sts || options.sct_temp_hist) {
                   3228:         ata_sct_status_response sts;
                   3229:         ata_sct_temperature_history_table tmh;
                   3230:         if (!options.sct_temp_hist) {
                   3231:           // Read SCT status only
                   3232:           if (ataReadSCTStatus(device, &sts)) {
                   3233:             failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3234:             break;
                   3235:           }
                   3236:         }
                   3237:         else {
                   3238:           if (!isSCTDataTableCapable(&drive)) {
1.1.1.3   misho    3239:             pout("SCT Data Table command not supported\n\n");
1.1       misho    3240:             failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3241:             break;
                   3242:           }
                   3243:           // Read SCT status and temperature history
                   3244:           if (ataReadSCTTempHist(device, &tmh, &sts)) {
1.1.1.3   misho    3245:             pout("Read SCT Temperature History failed\n\n");
1.1       misho    3246:             failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3247:             break;
                   3248:           }
                   3249:         }
                   3250:         if (options.sct_temp_sts)
                   3251:           ataPrintSCTStatus(&sts);
                   3252:         if (options.sct_temp_hist)
                   3253:           ataPrintSCTTempHist(&tmh);
                   3254:         pout("\n");
                   3255:       }
                   3256:       if (options.sct_temp_int) {
                   3257:         // Set new temperature logging interval
                   3258:         if (!isSCTFeatureControlCapable(&drive)) {
1.1.1.3   misho    3259:           pout("SCT Feature Control command not supported\n\n");
1.1       misho    3260:           failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3261:           break;
                   3262:         }
                   3263:         if (ataSetSCTTempInterval(device, options.sct_temp_int, options.sct_temp_int_pers)) {
1.1.1.3   misho    3264:           pout("Write Temperature Logging Interval failed\n\n");
1.1       misho    3265:           failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3266:           break;
                   3267:         }
                   3268:         pout("Temperature Logging Interval set to %u minute%s (%s)\n",
                   3269:           options.sct_temp_int, (options.sct_temp_int == 1 ? "" : "s"),
                   3270:           (options.sct_temp_int_pers ? "persistent" : "volatile"));
                   3271:       }
                   3272:       break;
                   3273:     }
                   3274:   }
                   3275: 
                   3276:   // SCT Error Recovery Control
                   3277:   if (sct_ok && (options.sct_erc_get || options.sct_erc_set)) {
                   3278:     if (!isSCTErrorRecoveryControlCapable(&drive)) {
1.1.1.3   misho    3279:       pout("SCT Error Recovery Control command not supported\n\n");
1.1       misho    3280:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3281:     }
                   3282:     else {
                   3283:       bool sct_erc_get = options.sct_erc_get;
                   3284:       if (options.sct_erc_set) {
                   3285:         // Set SCT Error Recovery Control
                   3286:         if (   ataSetSCTErrorRecoveryControltime(device, 1, options.sct_erc_readtime )
                   3287:             || ataSetSCTErrorRecoveryControltime(device, 2, options.sct_erc_writetime)) {
1.1.1.3   misho    3288:           pout("SCT (Set) Error Recovery Control command failed\n");
1.1       misho    3289:           if (!(   (options.sct_erc_readtime == 70 && options.sct_erc_writetime == 70)
                   3290:                 || (options.sct_erc_readtime ==  0 && options.sct_erc_writetime ==  0)))
                   3291:             pout("Retry with: 'scterc,70,70' to enable ERC or 'scterc,0,0' to disable\n");
                   3292:           failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3293:           sct_erc_get = false;
                   3294:         }
                   3295:         else if (!sct_erc_get)
                   3296:           ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
                   3297:             options.sct_erc_writetime);
                   3298:       }
                   3299: 
                   3300:       if (sct_erc_get) {
                   3301:         // Print SCT Error Recovery Control
                   3302:         unsigned short read_timer, write_timer;
                   3303:         if (   ataGetSCTErrorRecoveryControltime(device, 1, read_timer )
                   3304:             || ataGetSCTErrorRecoveryControltime(device, 2, write_timer)) {
1.1.1.3   misho    3305:           pout("SCT (Get) Error Recovery Control command failed\n");
1.1       misho    3306:           if (options.sct_erc_set) {
                   3307:             pout("The previous SCT (Set) Error Recovery Control command succeeded\n");
                   3308:             ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
                   3309:               options.sct_erc_writetime);
                   3310:           }
                   3311:           failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3312:         }
                   3313:         else
                   3314:           ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer);
                   3315:       }
                   3316:       pout("\n");
                   3317:     }
                   3318:   }
                   3319: 
                   3320:   // Print Device Statistics
                   3321:   if (options.devstat_all_pages || options.devstat_ssd_page || !options.devstat_pages.empty()) {
                   3322:     unsigned nsectors = GetNumLogSectors(gplogdir, 0x04, true);
                   3323:     if (!nsectors)
1.1.1.3   misho    3324:       pout("Device Statistics (GP Log 0x04) not supported\n\n");
1.1       misho    3325:     else if (!print_device_statistics(device, nsectors, options.devstat_pages,
                   3326:                options.devstat_all_pages, options.devstat_ssd_page))
                   3327:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3328:   }
                   3329: 
                   3330:   // Print SATA Phy Event Counters
                   3331:   if (options.sataphy) {
                   3332:     unsigned nsectors = GetNumLogSectors(gplogdir, 0x11, true);
1.1.1.3   misho    3333:     // Packet interface devices do not provide a log directory, check support bit
                   3334:     if (!nsectors && (drive.words047_079[76-47] & 0x0401) == 0x0400)
                   3335:       nsectors = 1;
1.1       misho    3336:     if (!nsectors)
1.1.1.3   misho    3337:       pout("SATA Phy Event Counters (GP Log 0x11) not supported\n\n");
1.1       misho    3338:     else if (nsectors != 1)
1.1.1.3   misho    3339:       pout("SATA Phy Event Counters with %u sectors not supported\n\n", nsectors);
1.1       misho    3340:     else {
                   3341:       unsigned char log_11[512] = {0, };
                   3342:       unsigned char features = (options.sataphy_reset ? 0x01 : 0x00);
1.1.1.3   misho    3343:       if (!ataReadLogExt(device, 0x11, features, 0, log_11, 1)) {
                   3344:         pout("Read SATA Phy Event Counters failed\n\n");
1.1       misho    3345:         failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1.1.1.3   misho    3346:       }
1.1       misho    3347:       else
                   3348:         PrintSataPhyEventCounters(log_11, options.sataphy_reset);
                   3349:     }
                   3350:   }
                   3351: 
1.1.1.2   misho    3352:   // Set to standby (spindown) mode
                   3353:   // (Above commands may spinup drive)
                   3354:   if (options.set_standby_now) {
                   3355:     if (!ata_nodata_command(device, ATA_STANDBY_IMMEDIATE)) {
                   3356:         pout("ATA STANDBY IMMEDIATE command failed: %s\n", device->get_errmsg());
                   3357:         returnval |= FAILSMART;
                   3358:     }
                   3359:     else
                   3360:       pout("Device placed in STANDBY mode\n");
                   3361:   }
                   3362: 
1.1       misho    3363:   // START OF THE TESTING SECTION OF THE CODE.  IF NO TESTING, RETURN
                   3364:   if (!smart_val_ok || options.smart_selftest_type == -1)
                   3365:     return returnval;
                   3366:   
                   3367:   pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
                   3368:   // if doing a self-test, be sure it's supported by the hardware
                   3369:   switch (options.smart_selftest_type) {
                   3370:   case OFFLINE_FULL_SCAN:
                   3371:     if (!isSupportExecuteOfflineImmediate(&smartval)){
1.1.1.3   misho    3372:       pout("Execute Offline Immediate function not supported\n\n");
1.1       misho    3373:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3374:     }
                   3375:     break;
                   3376:   case ABORT_SELF_TEST:
                   3377:   case SHORT_SELF_TEST:
                   3378:   case EXTEND_SELF_TEST:
                   3379:   case SHORT_CAPTIVE_SELF_TEST:
                   3380:   case EXTEND_CAPTIVE_SELF_TEST:
                   3381:     if (!isSupportSelfTest(&smartval)){
1.1.1.3   misho    3382:       pout("Self-test functions not supported\n\n");
1.1       misho    3383:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3384:     }
                   3385:     break;
                   3386:   case CONVEYANCE_SELF_TEST:
                   3387:   case CONVEYANCE_CAPTIVE_SELF_TEST:
                   3388:     if (!isSupportConveyanceSelfTest(&smartval)){
1.1.1.3   misho    3389:       pout("Conveyance Self-test functions not supported\n\n");
1.1       misho    3390:       failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3391:     }
                   3392:     break;
                   3393:   case SELECTIVE_SELF_TEST:
                   3394:   case SELECTIVE_CAPTIVE_SELF_TEST:
                   3395:     if (!isSupportSelectiveSelfTest(&smartval)){
1.1.1.3   misho    3396:       pout("Selective Self-test functions not supported\n\n");
1.1       misho    3397:       failuretest(MANDATORY_CMD, returnval|=FAILSMART);
                   3398:     }
                   3399:     break;
                   3400:   default:
                   3401:     break; // Vendor specific type
                   3402:   }
                   3403: 
                   3404:   // Now do the test.  Note ataSmartTest prints its own error/success
                   3405:   // messages
1.1.1.2   misho    3406:   if (ataSmartTest(device, options.smart_selftest_type, options.smart_selftest_force,
                   3407:                    options.smart_selective_args, &smartval, sizes.sectors            ))
1.1       misho    3408:     failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3409:   else {  
                   3410:     // Tell user how long test will take to complete.  This is tricky
                   3411:     // because in the case of an Offline Full Scan, the completion
                   3412:     // timer is volatile, and needs to be read AFTER the command is
                   3413:     // given. If this will interrupt the Offline Full Scan, we don't
                   3414:     // do it, just warn user.
                   3415:     if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
                   3416:       if (isSupportOfflineAbort(&smartval))
                   3417:        pout("Note: giving further SMART commands will abort Offline testing\n");
                   3418:       else if (ataReadSmartValues(device, &smartval)){
1.1.1.3   misho    3419:         pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
1.1       misho    3420:        failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
                   3421:       }
                   3422:     }
                   3423:     
                   3424:     // Now say how long the test will take to complete
                   3425:     int timewait = TestTime(&smartval, options.smart_selftest_type);
                   3426:     if (timewait) {
                   3427:       time_t t=time(NULL);
                   3428:       if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
                   3429:        t+=timewait;
                   3430:        pout("Please wait %d seconds for test to complete.\n", (int)timewait);
                   3431:       } else {
                   3432:        t+=timewait*60;
                   3433:        pout("Please wait %d minutes for test to complete.\n", (int)timewait);
                   3434:       }
                   3435:       pout("Test will complete after %s\n", ctime(&t));
                   3436:       
                   3437:       if (   options.smart_selftest_type != SHORT_CAPTIVE_SELF_TEST
                   3438:           && options.smart_selftest_type != EXTEND_CAPTIVE_SELF_TEST
                   3439:           && options.smart_selftest_type != CONVEYANCE_CAPTIVE_SELF_TEST
                   3440:           && options.smart_selftest_type != SELECTIVE_CAPTIVE_SELF_TEST )
                   3441:         pout("Use smartctl -X to abort test.\n");
                   3442:     }
                   3443:   }
                   3444: 
                   3445:   return returnval;
                   3446: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>