smartmontools SVN Rev 3317
Utility to control and monitor storage systems with "S.M.A.R.T."
atacmds.h
Go to the documentation of this file.
00001 /*
00002  * atacmds.h
00003  *
00004  * Home page of code is: http://smartmontools.sourceforge.net
00005  *
00006  * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
00007  * Copyright (C) 2008-12 Christian Franke <smartmontools-support@lists.sourceforge.net>
00008  * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
00009  *
00010  * This program is free software; you can redistribute it and/or modify
00011  * it under the terms of the GNU General Public License as published by
00012  * the Free Software Foundation; either version 2, or (at your option)
00013  * any later version.
00014  *
00015  * You should have received a copy of the GNU General Public License
00016  * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
00017  *
00018  * This code was originally developed as a Senior Thesis by Michael Cornwell
00019  * at the Concurrent Systems Laboratory (now part of the Storage Systems
00020  * Research Center), Jack Baskin School of Engineering, University of
00021  * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
00022  *
00023  */
00024 
00025 #ifndef ATACMDS_H_
00026 #define ATACMDS_H_
00027 
00028 #define ATACMDS_H_CVSID "$Id: atacmds.h 3825 2013-07-06 21:38:25Z samm2 $"
00029 
00030 #include "dev_interface.h" // ata_device
00031 
00032 // Macro to check expected size of struct at compile time using a
00033 // dummy typedef.  On size mismatch, compiler reports a negative array
00034 // size.  If you see an error message of this form, it means that the
00035 // #pragma pack(1) pragma below is not having the desired effect on
00036 // your compiler.
00037 #define ASSERT_SIZEOF_STRUCT(s, n) \
00038   typedef char assert_sizeof_struct_##s[(sizeof(struct s) == (n)) ? 1 : -1]
00039 
00040 // Add __attribute__((packed)) if compiler supports it
00041 // because some gcc versions (at least ARM) lack support of #pragma pack()
00042 #ifdef HAVE_ATTR_PACKED
00043 #define ATTR_PACKED __attribute__((packed))
00044 #else
00045 #define ATTR_PACKED
00046 #endif
00047 
00048 typedef enum {
00049   // returns no data, just succeeds or fails
00050   ENABLE,
00051   DISABLE,
00052   AUTOSAVE,
00053   IMMEDIATE_OFFLINE,
00054   AUTO_OFFLINE,
00055   STATUS,       // just says if SMART is working or not
00056   STATUS_CHECK, // says if disk's SMART status is healthy, or failing
00057   // return 512 bytes of data:
00058   READ_VALUES,
00059   READ_THRESHOLDS,
00060   READ_LOG,
00061   IDENTIFY,
00062   PIDENTIFY,
00063   // returns 1 byte of data
00064   CHECK_POWER_MODE,
00065   // writes 512 bytes of data:
00066   WRITE_LOG
00067 } smart_command_set;
00068 
00069 
00070 // ATA Specification Command Register Values (Commands)
00071 #define ATA_CHECK_POWER_MODE            0xe5
00072 #define ATA_IDENTIFY_DEVICE             0xec
00073 #define ATA_IDENTIFY_PACKET_DEVICE      0xa1
00074 #define ATA_IDLE                        0xe3
00075 #define ATA_SMART_CMD                   0xb0
00076 #define ATA_SECURITY_FREEZE_LOCK        0xf5
00077 #define ATA_SET_FEATURES                0xef
00078 #define ATA_STANDBY_IMMEDIATE           0xe0
00079 
00080 // SET_FEATURES subcommands
00081 #define ATA_DISABLE_AAM                 0xc2
00082 #define ATA_DISABLE_APM                 0x85
00083 #define ATA_DISABLE_WRITE_CACHE         0x82
00084 #define ATA_DISABLE_READ_LOOK_AHEAD     0x55
00085 #define ATA_ENABLE_AAM                  0x42
00086 #define ATA_ENABLE_APM                  0x05
00087 #define ATA_ENABLE_WRITE_CACHE          0x02
00088 #define ATA_ENABLE_READ_LOOK_AHEAD      0xaa
00089 
00090 // 48-bit commands
00091 #define ATA_READ_LOG_EXT                0x2F
00092 
00093 // ATA Specification Feature Register Values (SMART Subcommands).
00094 // Note that some are obsolete as of ATA-7.
00095 #define ATA_SMART_READ_VALUES           0xd0
00096 #define ATA_SMART_READ_THRESHOLDS       0xd1
00097 #define ATA_SMART_AUTOSAVE              0xd2
00098 #define ATA_SMART_SAVE                  0xd3
00099 #define ATA_SMART_IMMEDIATE_OFFLINE     0xd4
00100 #define ATA_SMART_READ_LOG_SECTOR       0xd5
00101 #define ATA_SMART_WRITE_LOG_SECTOR      0xd6
00102 #define ATA_SMART_WRITE_THRESHOLDS      0xd7
00103 #define ATA_SMART_ENABLE                0xd8
00104 #define ATA_SMART_DISABLE               0xd9
00105 #define ATA_SMART_STATUS                0xda
00106 // SFF 8035i Revision 2 Specification Feature Register Value (SMART
00107 // Subcommand)
00108 #define ATA_SMART_AUTO_OFFLINE          0xdb
00109 
00110 // Sector Number values for ATA_SMART_IMMEDIATE_OFFLINE Subcommand
00111 #define OFFLINE_FULL_SCAN               0
00112 #define SHORT_SELF_TEST                 1
00113 #define EXTEND_SELF_TEST                2
00114 #define CONVEYANCE_SELF_TEST            3
00115 #define SELECTIVE_SELF_TEST             4
00116 #define ABORT_SELF_TEST                 127
00117 #define SHORT_CAPTIVE_SELF_TEST         129
00118 #define EXTEND_CAPTIVE_SELF_TEST        130
00119 #define CONVEYANCE_CAPTIVE_SELF_TEST    131
00120 #define SELECTIVE_CAPTIVE_SELF_TEST     132
00121 #define CAPTIVE_MASK                    (0x01<<7)
00122 
00123 // Maximum allowed number of SMART Attributes
00124 #define NUMBER_ATA_SMART_ATTRIBUTES     30
00125 
00126 // Needed parts of the ATA DRIVE IDENTIFY Structure. Those labeled
00127 // word* are NOT used.
00128 #pragma pack(1)
00129 struct ata_identify_device {
00130   unsigned short words000_009[10];
00131   unsigned char  serial_no[20];
00132   unsigned short words020_022[3];
00133   unsigned char  fw_rev[8];
00134   unsigned char  model[40];
00135   unsigned short words047_079[33];
00136   unsigned short major_rev_num;
00137   unsigned short minor_rev_num;
00138   unsigned short command_set_1;
00139   unsigned short command_set_2;
00140   unsigned short command_set_extension;
00141   unsigned short cfs_enable_1;
00142   unsigned short word086;
00143   unsigned short csf_default;
00144   unsigned short words088_255[168];
00145 } ATTR_PACKED;
00146 #pragma pack()
00147 ASSERT_SIZEOF_STRUCT(ata_identify_device, 512);
00148 
00149 /* ata_smart_attribute is the vendor specific in SFF-8035 spec */ 
00150 #pragma pack(1)
00151 struct ata_smart_attribute {
00152   unsigned char id;
00153   // meaning of flag bits: see MACROS just below
00154   // WARNING: MISALIGNED!
00155   unsigned short flags; 
00156   unsigned char current;
00157   unsigned char worst;
00158   unsigned char raw[6];
00159   unsigned char reserv;
00160 } ATTR_PACKED;
00161 #pragma pack()
00162 ASSERT_SIZEOF_STRUCT(ata_smart_attribute, 12);
00163 
00164 // MACROS to interpret the flags bits in the previous structure.
00165 // These have not been implemented using bitflags and a union, to make
00166 // it portable across bit/little endian and different platforms.
00167 
00168 // 0: Prefailure bit
00169 
00170 // From SFF 8035i Revision 2 page 19: Bit 0 (pre-failure/advisory bit)
00171 // - If the value of this bit equals zero, an attribute value less
00172 // than or equal to its corresponding attribute threshold indicates an
00173 // advisory condition where the usage or age of the device has
00174 // exceeded its intended design life period. If the value of this bit
00175 // equals one, an attribute value less than or equal to its
00176 // corresponding attribute threshold indicates a prefailure condition
00177 // where imminent loss of data is being predicted.
00178 #define ATTRIBUTE_FLAGS_PREFAILURE(x) (x & 0x01)
00179 
00180 // 1: Online bit 
00181 
00182 //  From SFF 8035i Revision 2 page 19: Bit 1 (on-line data collection
00183 // bit) - If the value of this bit equals zero, then the attribute
00184 // value is updated only during off-line data collection
00185 // activities. If the value of this bit equals one, then the attribute
00186 // value is updated during normal operation of the device or during
00187 // both normal operation and off-line testing.
00188 #define ATTRIBUTE_FLAGS_ONLINE(x) (x & 0x02)
00189 
00190 
00191 // The following are (probably) IBM's, Maxtors and  Quantum's definitions for the
00192 // vendor-specific bits:
00193 // 2: Performance type bit
00194 #define ATTRIBUTE_FLAGS_PERFORMANCE(x) (x & 0x04)
00195 
00196 // 3: Errorrate type bit
00197 #define ATTRIBUTE_FLAGS_ERRORRATE(x) (x & 0x08)
00198 
00199 // 4: Eventcount bit
00200 #define ATTRIBUTE_FLAGS_EVENTCOUNT(x) (x & 0x10)
00201 
00202 // 5: Selfpereserving bit
00203 #define ATTRIBUTE_FLAGS_SELFPRESERVING(x) (x & 0x20)
00204 
00205 // 6-15: Reserved for future use
00206 #define ATTRIBUTE_FLAGS_OTHER(x) ((x) & 0xffc0)
00207 
00208 
00209 // Format of data returned by SMART READ DATA
00210 // Table 62 of T13/1699-D (ATA8-ACS) Revision 6a, September 2008
00211 #pragma pack(1)
00212 struct ata_smart_values {
00213   unsigned short int revnumber;
00214   struct ata_smart_attribute vendor_attributes [NUMBER_ATA_SMART_ATTRIBUTES];
00215   unsigned char offline_data_collection_status;
00216   unsigned char self_test_exec_status;  //IBM # segments for offline collection
00217   unsigned short int total_time_to_complete_off_line; // IBM different
00218   unsigned char vendor_specific_366; // Maxtor & IBM curent segment pointer
00219   unsigned char offline_data_collection_capability;
00220   unsigned short int smart_capability;
00221   unsigned char errorlog_capability;
00222   unsigned char vendor_specific_371;  // Maxtor, IBM: self-test failure checkpoint see below!
00223   unsigned char short_test_completion_time;
00224   unsigned char extend_test_completion_time_b; // If 0xff, use 16-bit value below
00225   unsigned char conveyance_test_completion_time;
00226   unsigned short extend_test_completion_time_w; // e04130r2, added to T13/1699-D Revision 1c, April 2005
00227   unsigned char reserved_377_385[9];
00228   unsigned char vendor_specific_386_510[125]; // Maxtor bytes 508-509 Attribute/Threshold Revision #
00229   unsigned char chksum;
00230 } ATTR_PACKED;
00231 #pragma pack()
00232 ASSERT_SIZEOF_STRUCT(ata_smart_values, 512);
00233 
00234 /* Maxtor, IBM: self-test failure checkpoint byte meaning:
00235  00 - write test
00236  01 - servo basic
00237  02 - servo random
00238  03 - G-list scan
00239  04 - Handling damage
00240  05 - Read scan
00241 */
00242 
00243 /* Vendor attribute of SMART Threshold (compare to ata_smart_attribute above) */
00244 #pragma pack(1)
00245 struct ata_smart_threshold_entry {
00246   unsigned char id;
00247   unsigned char threshold;
00248   unsigned char reserved[10];
00249 } ATTR_PACKED;
00250 #pragma pack()
00251 ASSERT_SIZEOF_STRUCT(ata_smart_threshold_entry, 12);
00252 
00253 /* Format of Read SMART THreshold Command */
00254 /* Compare to ata_smart_values above */
00255 #pragma pack(1)
00256 struct ata_smart_thresholds_pvt {
00257   unsigned short int revnumber;
00258   struct ata_smart_threshold_entry thres_entries[NUMBER_ATA_SMART_ATTRIBUTES];
00259   unsigned char reserved[149];
00260   unsigned char chksum;
00261 } ATTR_PACKED;
00262 #pragma pack()
00263 ASSERT_SIZEOF_STRUCT(ata_smart_thresholds_pvt, 512);
00264 
00265 
00266 // Table 42 of T13/1321D Rev 1 spec (Error Data Structure)
00267 #pragma pack(1)
00268 struct ata_smart_errorlog_error_struct {
00269   unsigned char reserved;
00270   unsigned char error_register;
00271   unsigned char sector_count;
00272   unsigned char sector_number;
00273   unsigned char cylinder_low;
00274   unsigned char cylinder_high;
00275   unsigned char drive_head;
00276   unsigned char status;
00277   unsigned char extended_error[19];
00278   unsigned char state;
00279   unsigned short timestamp;
00280 } ATTR_PACKED;
00281 #pragma pack()
00282 ASSERT_SIZEOF_STRUCT(ata_smart_errorlog_error_struct, 30);
00283 
00284 
00285 // Table 41 of T13/1321D Rev 1 spec (Command Data Structure)
00286 #pragma pack(1)
00287 struct ata_smart_errorlog_command_struct {
00288   unsigned char devicecontrolreg;
00289   unsigned char featuresreg;
00290   unsigned char sector_count;
00291   unsigned char sector_number;
00292   unsigned char cylinder_low;
00293   unsigned char cylinder_high;
00294   unsigned char drive_head;
00295   unsigned char commandreg;
00296   unsigned int timestamp;
00297 } ATTR_PACKED;
00298 #pragma pack()
00299 ASSERT_SIZEOF_STRUCT(ata_smart_errorlog_command_struct, 12);
00300 
00301 // Table 40 of T13/1321D Rev 1 spec (Error log data structure)
00302 #pragma pack(1)
00303 struct ata_smart_errorlog_struct {
00304   struct ata_smart_errorlog_command_struct commands[5];
00305   struct ata_smart_errorlog_error_struct error_struct;
00306 } ATTR_PACKED;
00307 #pragma pack()
00308 ASSERT_SIZEOF_STRUCT(ata_smart_errorlog_struct, 90);
00309 
00310 // Table 39 of T13/1321D Rev 1 spec (SMART error log sector)
00311 #pragma pack(1)
00312 struct ata_smart_errorlog {
00313   unsigned char revnumber;
00314   unsigned char error_log_pointer;
00315   struct ata_smart_errorlog_struct errorlog_struct[5];
00316   unsigned short int ata_error_count;
00317   unsigned char reserved[57];
00318   unsigned char checksum;
00319 } ATTR_PACKED;
00320 #pragma pack()
00321 ASSERT_SIZEOF_STRUCT(ata_smart_errorlog, 512);
00322 
00323 
00324 // Extended Comprehensive SMART Error Log data structures
00325 // See Section A.7 of
00326 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
00327 //   T13/1699-D Revision 6a (Working Draft), September 6, 2008.
00328 
00329 // Command data structure
00330 // Table A.9 of T13/1699-D Revision 6a
00331 #pragma pack(1)
00332 struct ata_smart_exterrlog_command
00333 {
00334   unsigned char device_control_register;
00335   unsigned char features_register;
00336   unsigned char features_register_hi;
00337   unsigned char count_register;
00338   unsigned char count_register_hi;
00339   unsigned char lba_low_register;
00340   unsigned char lba_low_register_hi;
00341   unsigned char lba_mid_register;
00342   unsigned char lba_mid_register_hi;
00343   unsigned char lba_high_register;
00344   unsigned char lba_high_register_hi;
00345   unsigned char device_register;
00346   unsigned char command_register;
00347 
00348   unsigned char reserved;
00349   unsigned int timestamp;
00350 } ATTR_PACKED;
00351 #pragma pack()
00352 ASSERT_SIZEOF_STRUCT(ata_smart_exterrlog_command, 18);
00353 
00354 // Error data structure
00355 // Table A.10 T13/1699-D Revision 6a
00356 #pragma pack(1)
00357 struct ata_smart_exterrlog_error
00358 {
00359   unsigned char device_control_register;
00360   unsigned char error_register;
00361   unsigned char count_register;
00362   unsigned char count_register_hi;
00363   unsigned char lba_low_register;
00364   unsigned char lba_low_register_hi;
00365   unsigned char lba_mid_register;
00366   unsigned char lba_mid_register_hi;
00367   unsigned char lba_high_register;
00368   unsigned char lba_high_register_hi;
00369   unsigned char device_register;
00370   unsigned char status_register;
00371 
00372   unsigned char extended_error[19];
00373   unsigned char state;
00374   unsigned short timestamp;
00375 } ATTR_PACKED;
00376 #pragma pack()
00377 ASSERT_SIZEOF_STRUCT(ata_smart_exterrlog_error, 34);
00378 
00379 // Error log data structure
00380 // Table A.8 of T13/1699-D Revision 6a
00381 #pragma pack(1)
00382 struct ata_smart_exterrlog_error_log
00383 {
00384   ata_smart_exterrlog_command commands[5];
00385   ata_smart_exterrlog_error error;
00386 } ATTR_PACKED;
00387 #pragma pack()
00388 ASSERT_SIZEOF_STRUCT(ata_smart_exterrlog_error_log, 124);
00389 
00390 // Ext. Comprehensive SMART error log
00391 // Table A.7 of T13/1699-D Revision 6a
00392 #pragma pack(1)
00393 struct ata_smart_exterrlog
00394 {
00395   unsigned char version;
00396   unsigned char reserved1;
00397   unsigned short error_log_index;
00398   ata_smart_exterrlog_error_log error_logs[4];
00399   unsigned short device_error_count;
00400   unsigned char reserved2[9];
00401   unsigned char checksum;
00402 } ATTR_PACKED;
00403 #pragma pack()
00404 ASSERT_SIZEOF_STRUCT(ata_smart_exterrlog, 512);
00405 
00406 
00407 // Table 45 of T13/1321D Rev 1 spec (Self-test log descriptor entry)
00408 #pragma pack(1)
00409 struct ata_smart_selftestlog_struct {
00410   unsigned char selftestnumber; // Sector number register
00411   unsigned char selfteststatus;
00412   unsigned short int timestamp;
00413   unsigned char selftestfailurecheckpoint;
00414   unsigned int lbafirstfailure;
00415   unsigned char vendorspecific[15];
00416 } ATTR_PACKED;
00417 #pragma pack()
00418 ASSERT_SIZEOF_STRUCT(ata_smart_selftestlog_struct, 24);
00419 
00420 // Table 44 of T13/1321D Rev 1 spec (Self-test log data structure)
00421 #pragma pack(1)
00422 struct ata_smart_selftestlog {
00423   unsigned short int revnumber;
00424   struct ata_smart_selftestlog_struct selftest_struct[21];
00425   unsigned char vendorspecific[2];
00426   unsigned char mostrecenttest;
00427   unsigned char reserved[2];
00428   unsigned char chksum;
00429 } ATTR_PACKED;
00430 #pragma pack()
00431 ASSERT_SIZEOF_STRUCT(ata_smart_selftestlog, 512);
00432 
00433 // Extended SMART Self-test log data structures
00434 // See Section A.8 of
00435 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
00436 //   T13/1699-D Revision 6a (Working Draft), September 6, 2008.
00437 
00438 // Extended Self-test log descriptor entry
00439 // Table A.13 of T13/1699-D Revision 6a
00440 #pragma pack(1)
00441 struct ata_smart_extselftestlog_desc
00442 {
00443   unsigned char self_test_type;
00444   unsigned char self_test_status;
00445   unsigned short timestamp;
00446   unsigned char checkpoint;
00447   unsigned char failing_lba[6];
00448   unsigned char vendorspecific[15];
00449 } ATTR_PACKED;
00450 #pragma pack()
00451 ASSERT_SIZEOF_STRUCT(ata_smart_extselftestlog_desc, 26);
00452 
00453 // Extended Self-test log data structure
00454 // Table A.12 of T13/1699-D Revision 6a
00455 #pragma pack(1)
00456 struct ata_smart_extselftestlog
00457 {
00458   unsigned char version;
00459   unsigned char reserved1;
00460   unsigned short log_desc_index;
00461   struct ata_smart_extselftestlog_desc log_descs[19];
00462   unsigned char vendor_specifc[2];
00463   unsigned char reserved2[11];
00464   unsigned char chksum;
00465 } ATTR_PACKED;
00466 #pragma pack()
00467 ASSERT_SIZEOF_STRUCT(ata_smart_extselftestlog, 512);
00468 
00469 // SMART LOG DIRECTORY Table 52 of T13/1532D Vol 1 Rev 1a
00470 #pragma pack(1)
00471 struct ata_smart_log_entry {
00472   unsigned char numsectors;
00473   unsigned char reserved;
00474 } ATTR_PACKED;
00475 #pragma pack()
00476 ASSERT_SIZEOF_STRUCT(ata_smart_log_entry, 2);
00477 
00478 #pragma pack(1)
00479 struct ata_smart_log_directory {
00480   unsigned short int logversion;
00481   struct ata_smart_log_entry entry[255];
00482 } ATTR_PACKED;
00483 #pragma pack()
00484 ASSERT_SIZEOF_STRUCT(ata_smart_log_directory, 512);
00485 
00486 // SMART SELECTIVE SELF-TEST LOG Table 61 of T13/1532D Volume 1
00487 // Revision 3
00488 #pragma pack(1)
00489 struct test_span {
00490   uint64_t start;
00491   uint64_t end;
00492 } ATTR_PACKED;
00493 #pragma pack()
00494 ASSERT_SIZEOF_STRUCT(test_span, 16);
00495 
00496 #pragma pack(1)
00497 struct ata_selective_self_test_log {
00498   unsigned short     logversion;
00499   struct test_span   span[5];
00500   unsigned char      reserved1[337-82+1];
00501   unsigned char      vendor_specific1[491-338+1];
00502   uint64_t           currentlba;
00503   unsigned short     currentspan;
00504   unsigned short     flags;
00505   unsigned char      vendor_specific2[507-504+1];
00506   unsigned short     pendingtime;
00507   unsigned char      reserved2;
00508   unsigned char      checksum;
00509 } ATTR_PACKED;
00510 #pragma pack()
00511 ASSERT_SIZEOF_STRUCT(ata_selective_self_test_log, 512);
00512 
00513 #define SELECTIVE_FLAG_DOSCAN  (0x0002)
00514 #define SELECTIVE_FLAG_PENDING (0x0008)
00515 #define SELECTIVE_FLAG_ACTIVE  (0x0010)
00516 
00517 
00518 // SCT (SMART Command Transport) data structures
00519 // See Sections 8.2 and 8.3 of:
00520 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
00521 //   T13/1699-D Revision 3f (Working Draft), December 11, 2006.
00522 
00523 // SCT Status response (read with SMART_READ_LOG page 0xe0)
00524 // Table 60 of T13/1699-D Revision 3f 
00525 #pragma pack(1)
00526 struct ata_sct_status_response
00527 {
00528   unsigned short format_version;    // 0-1: Status response format version number (2, 3)
00529   unsigned short sct_version;       // 2-3: Vendor specific version number
00530   unsigned short sct_spec;          // 4-5: SCT level supported (1)
00531   unsigned int status_flags;        // 6-9: Status flags (Bit 0: Segment initialized, Bits 1-31: reserved)
00532   unsigned char device_state;       // 10: Device State (0-5)
00533   unsigned char bytes011_013[3];    // 11-13: reserved
00534   unsigned short ext_status_code;   // 14-15: Status of last SCT command (0xffff if executing)
00535   unsigned short action_code;       // 16-17: Action code of last SCT command
00536   unsigned short function_code;     // 18-19: Function code of last SCT command
00537   unsigned char bytes020_039[20];   // 20-39: reserved
00538   uint64_t lba_current;             // 40-47: LBA of SCT command executing in background
00539   unsigned char bytes048_199[152];  // 48-199: reserved
00540   signed char hda_temp;             // 200: Current temperature in Celsius (0x80 = invalid)
00541   signed char min_temp;             // 201: Minimum temperature this power cycle
00542   signed char max_temp;             // 202: Maximum temperature this power cycle
00543   signed char life_min_temp;        // 203: Minimum lifetime temperature
00544   signed char life_max_temp;        // 204: Maximum lifetime temperature
00545   unsigned char byte205;            // 205: reserved (T13/e06152r0-2: Average lifetime temperature)
00546   unsigned int over_limit_count;    // 206-209: # intervals since last reset with temperature > Max Op Limit
00547   unsigned int under_limit_count;   // 210-213: # intervals since last reset with temperature < Min Op Limit
00548   unsigned char bytes214_479[266];  // 214-479: reserved
00549   unsigned char vendor_specific[32];// 480-511: vendor specific
00550 } ATTR_PACKED;
00551 #pragma pack()
00552 ASSERT_SIZEOF_STRUCT(ata_sct_status_response, 512);
00553 
00554 // SCT Error Recovery Control command (send with SMART_WRITE_LOG page 0xe0)
00555 // Table 88 of T13/1699-D Revision 6a
00556 #pragma pack(1)
00557 struct ata_sct_error_recovery_control_command
00558 {
00559   unsigned short action_code;       // 3 = Error Recovery Control
00560   unsigned short function_code;     // 1 = Set, 2 = Return
00561   unsigned short selection_code;    // 1 = Read Timer, 2 = Write Timer
00562   unsigned short time_limit;        // If set: Recovery time limit in 100ms units
00563   unsigned short words004_255[252]; // reserved
00564 } ATTR_PACKED;
00565 #pragma pack()
00566 ASSERT_SIZEOF_STRUCT(ata_sct_error_recovery_control_command, 512);
00567 
00568 // SCT Feature Control command (send with SMART_WRITE_LOG page 0xe0)
00569 // Table 72 of T13/1699-D Revision 3f
00570 #pragma pack(1)
00571 struct ata_sct_feature_control_command
00572 {
00573   unsigned short action_code;       // 4 = Feature Control
00574   unsigned short function_code;     // 1 = Set, 2 = Return, 3 = Return options
00575   unsigned short feature_code;      // 3 = Temperature logging interval
00576   unsigned short state;             // Interval
00577   unsigned short option_flags;      // Bit 0: persistent, Bits 1-15: reserved
00578   unsigned short words005_255[251]; // reserved
00579 } ATTR_PACKED;
00580 #pragma pack()
00581 ASSERT_SIZEOF_STRUCT(ata_sct_feature_control_command, 512);
00582 
00583 // SCT Data Table command (send with SMART_WRITE_LOG page 0xe0)
00584 // Table 73 of T13/1699-D Revision 3f 
00585 #pragma pack(1)
00586 struct ata_sct_data_table_command
00587 {
00588   unsigned short action_code;       // 5 = Data Table
00589   unsigned short function_code;     // 1 = Read Table
00590   unsigned short table_id;          // 2 = Temperature History
00591   unsigned short words003_255[253]; // reserved
00592 } ATTR_PACKED;
00593 #pragma pack()
00594 ASSERT_SIZEOF_STRUCT(ata_sct_data_table_command, 512);
00595 
00596 // SCT Temperature History Table (read with SMART_READ_LOG page 0xe1)
00597 // Table 75 of T13/1699-D Revision 3f 
00598 #pragma pack(1)
00599 struct ata_sct_temperature_history_table
00600 {
00601   unsigned short format_version;    // 0-1: Data table format version number (2)
00602   unsigned short sampling_period;   // 2-3: Temperature sampling period in minutes
00603   unsigned short interval;          // 4-5: Timer interval between history entries
00604   signed char max_op_limit;         // 6: Maximum recommended continuous operating temperature
00605   signed char over_limit;           // 7: Maximum temperature limit
00606   signed char min_op_limit;         // 8: Minimum recommended continuous operating limit
00607   signed char under_limit;          // 9: Minimum temperature limit
00608   unsigned char bytes010_029[20];   // 10-29: reserved
00609   unsigned short cb_size;           // 30-31: Number of history entries (range 128-478)
00610   unsigned short cb_index;          // 32-33: Index of last updated entry (zero-based)
00611   signed char cb[478];              // 34-(34+cb_size-1): Circular buffer of temperature values
00612 } ATTR_PACKED;
00613 #pragma pack()
00614 ASSERT_SIZEOF_STRUCT(ata_sct_temperature_history_table, 512);
00615 
00616 // Possible values for span_args.mode
00617 enum {
00618   SEL_RANGE, // MIN-MAX
00619   SEL_REDO,  // redo this
00620   SEL_NEXT,  // do next range
00621   SEL_CONT   // redo or next depending of last test status
00622 };
00623 
00624 // Arguments for selective self-test
00625 struct ata_selective_selftest_args
00626 {
00627   // Arguments for each span
00628   struct span_args
00629   {
00630     uint64_t start;   // First block
00631     uint64_t end;     // Last block
00632     int mode;         // SEL_*, see above
00633 
00634     span_args()
00635       : start(0), end(0), mode(SEL_RANGE) { }
00636   };
00637 
00638   span_args span[5];  // Range and mode for 5 spans
00639   int num_spans;      // Number of spans
00640   int pending_time;   // One plus time in minutes to wait after powerup before restarting
00641                       // interrupted offline scan after selective self-test.
00642   int scan_after_select; // Run offline scan after selective self-test:
00643                       // 0: don't change,
00644                       // 1: turn off scan after selective self-test,
00645                       // 2: turn on scan after selective self-test.
00646 
00647   ata_selective_selftest_args()
00648     : num_spans(0), pending_time(0), scan_after_select(0) { }
00649 };
00650 
00651 // Priority for vendor attribute defs
00652 enum ata_vendor_def_prior
00653 {
00654   PRIOR_DEFAULT,
00655   PRIOR_DATABASE,
00656   PRIOR_USER
00657 };
00658 
00659 // Raw attribute value print formats
00660 enum ata_attr_raw_format
00661 {
00662   RAWFMT_DEFAULT,
00663   RAWFMT_RAW8,
00664   RAWFMT_RAW16,
00665   RAWFMT_RAW48,
00666   RAWFMT_HEX48,
00667   RAWFMT_RAW56,
00668   RAWFMT_HEX56,
00669   RAWFMT_RAW64,
00670   RAWFMT_HEX64,
00671   RAWFMT_RAW16_OPT_RAW16,
00672   RAWFMT_RAW16_OPT_AVG16,
00673   RAWFMT_RAW24_OPT_RAW8,
00674   RAWFMT_RAW24_DIV_RAW24,
00675   RAWFMT_RAW24_DIV_RAW32,
00676   RAWFMT_SEC2HOUR,
00677   RAWFMT_MIN2HOUR,
00678   RAWFMT_HALFMIN2HOUR,
00679   RAWFMT_MSEC24_HOUR32,
00680   RAWFMT_TEMPMINMAX,
00681   RAWFMT_TEMP10X,
00682 };
00683 
00684 // Attribute flags
00685 enum {
00686   ATTRFLAG_INCREASING = 0x01,   // Value not reset (for reallocated/pending counts)
00687   ATTRFLAG_NO_NORMVAL = 0x02,   // Normalized value not valid
00688   ATTRFLAG_NO_WORSTVAL = 0x04   // Worst value not valid
00689 };
00690 
00691 // Vendor attribute display defs for all attribute ids
00692 class ata_vendor_attr_defs
00693 {
00694 public:
00695   struct entry
00696   {
00697     std::string name; // Attribute name, empty for default
00698     ata_attr_raw_format raw_format; // Raw value print format
00699     ata_vendor_def_prior priority; // Setting priority
00700     unsigned flags; // ATTRFLAG_*
00701     char byteorder[8+1]; // String [012345rvwz] to define byte order
00702 
00703     entry()
00704       : raw_format(RAWFMT_DEFAULT),
00705         priority(PRIOR_DEFAULT),
00706         flags(0)
00707       { byteorder[0] = 0; }
00708   };
00709 
00710   entry & operator[](unsigned char id)
00711     { return m_defs[id]; }
00712 
00713   const entry & operator[](unsigned char id) const
00714     { return m_defs[id]; }
00715 
00716 private:
00717   entry m_defs[256];
00718 };
00719 
00720 
00721 // Possible values for firmwarebugs
00722 enum firmwarebug_t {
00723   BUG_NONE = 0,
00724   BUG_NOLOGDIR,
00725   BUG_SAMSUNG,
00726   BUG_SAMSUNG2,
00727   BUG_SAMSUNG3,
00728   BUG_XERRORLBA
00729 };
00730 
00731 // Set of firmware bugs
00732 class firmwarebug_defs
00733 {
00734 public:
00735   firmwarebug_defs()
00736     : m_bugs(0) { }
00737 
00738   bool is_set(firmwarebug_t bug) const
00739     { return !!(m_bugs & (1 << bug)); }
00740 
00741   void set(firmwarebug_t bug)
00742     { m_bugs |= (1 << bug); }
00743 
00744   void set(firmwarebug_defs bugs)
00745     { m_bugs |= bugs.m_bugs; }
00746 
00747 private:
00748   unsigned m_bugs;
00749 };
00750 
00751 
00752 // Print ATA debug messages?
00753 extern unsigned char ata_debugmode;
00754 
00755 // Suppress serial number?
00756 extern bool dont_print_serial_number;
00757 
00758 // Get information from drive
00759 int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_swapped_id,
00760                       unsigned char * raw_buf = 0);
00761 int ataCheckPowerMode(ata_device * device);
00762 
00763 // Issue a no-data ATA command with optional sector count register value
00764 bool ata_nodata_command(ata_device * device, unsigned char command, int sector_count = -1);
00765 
00766 // Issue SET FEATURES command with optional sector count register value
00767 bool ata_set_features(ata_device * device, unsigned char features, int sector_count = -1);
00768 
00769 /* Read S.M.A.R.T information from drive */
00770 int ataReadSmartValues(ata_device * device,struct ata_smart_values *);
00771 int ataReadSmartThresholds(ata_device * device, struct ata_smart_thresholds_pvt *);
00772 int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data,
00773                      firmwarebug_defs firmwarebugs);
00774 int ataReadSelfTestLog(ata_device * device, ata_smart_selftestlog * data,
00775                        firmwarebug_defs firmwarebugs);
00776 int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_test_log *data);
00777 int ataReadLogDirectory(ata_device * device, ata_smart_log_directory *, bool gpl);
00778 
00779 // Read GP Log page(s)
00780 bool ataReadLogExt(ata_device * device, unsigned char logaddr,
00781                    unsigned char features, unsigned page,
00782                    void * data, unsigned nsectors);
00783 // Read SMART Log page(s)
00784 bool ataReadSmartLog(ata_device * device, unsigned char logaddr,
00785                      void * data, unsigned nsectors);
00786 // Read SMART Extended Comprehensive Error Log
00787 bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log,
00788                         unsigned nsectors, firmwarebug_defs firwarebugs);
00789 // Read SMART Extended Self-test Log
00790 bool ataReadExtSelfTestLog(ata_device * device, ata_smart_extselftestlog * log,
00791                            unsigned nsectors);
00792 
00793 // Read SCT information
00794 int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts);
00795 int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * tmh,
00796                        ata_sct_status_response * sts);
00797 // Set SCT temperature logging interval
00798 int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persistent);
00799 
00800 // Get/Set SCT Error Recovery Control
00801 int ataGetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short & time_limit);
00802 int ataSetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short time_limit);
00803 
00804 
00805 /* Enable/Disable SMART on device */
00806 int ataEnableSmart (ata_device * device);
00807 int ataDisableSmart (ata_device * device);
00808 int ataEnableAutoSave(ata_device * device);
00809 int ataDisableAutoSave(ata_device * device);
00810 
00811 /* Automatic Offline Testing */
00812 int ataEnableAutoOffline (ata_device * device);
00813 int ataDisableAutoOffline (ata_device * device);
00814 
00815 /* S.M.A.R.T. test commands */
00816 int ataSmartTest(ata_device * device, int testtype, bool force,
00817                  const ata_selective_selftest_args & args,
00818                  const ata_smart_values * sv, uint64_t num_sectors);
00819 
00820 int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_args & args,
00821                                  const ata_smart_values * sv, uint64_t num_sectors,
00822                                  const ata_selective_selftest_args * prev_spans = 0);
00823 
00824 // Get World Wide Name (WWN) fields.
00825 // Return NAA field or -1 if WWN is unsupported.
00826 int ata_get_wwn(const ata_identify_device * id, unsigned & oui, uint64_t & unique_id);
00827 
00828 // Get nominal media rotation rate.
00829 // Returns: 0 = not reported, 1 = SSD, >1 = HDD rpm, < 0 = -(Unknown value)
00830 int ata_get_rotation_rate(const ata_identify_device * id);
00831 
00832 // If SMART supported, this is guaranteed to return 1 if SMART is enabled, else 0.
00833 int ataDoesSmartWork(ata_device * device);
00834 
00835 // returns 1 if SMART supported, 0 if not supported or can't tell
00836 int ataSmartSupport(const ata_identify_device * drive);
00837 
00838 // Return values:
00839 //  1: Write Cache Reordering enabled
00840 //  2: Write Cache Reordering disabled
00841 // -1: error
00842 int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool persistent, bool set);
00843 
00844 // Return values:
00845 //  1: SMART enabled
00846 //  0: SMART disabled
00847 // -1: can't tell if SMART is enabled -- try issuing ataDoesSmartWork command to see
00848 int ataIsSmartEnabled(const ata_identify_device * drive);
00849 
00850 int ataSmartStatus2(ata_device * device);
00851 
00852 int isSmartErrorLogCapable(const ata_smart_values * data, const ata_identify_device * identity);
00853 
00854 int isSmartTestLogCapable(const ata_smart_values * data, const ata_identify_device * identity);
00855 
00856 int isGeneralPurposeLoggingCapable(const ata_identify_device * identity);
00857 
00858 int isSupportExecuteOfflineImmediate(const ata_smart_values * data);
00859 
00860 int isSupportAutomaticTimer(const ata_smart_values * data);
00861 
00862 int isSupportOfflineAbort(const ata_smart_values * data);
00863 
00864 int isSupportOfflineSurfaceScan(const ata_smart_values * data);
00865 
00866 int isSupportSelfTest(const ata_smart_values * data);
00867 
00868 int isSupportConveyanceSelfTest(const ata_smart_values * data);
00869 
00870 int isSupportSelectiveSelfTest(const ata_smart_values * data);
00871 
00872 inline bool isSCTCapable(const ata_identify_device *drive)
00873   { return !!(drive->words088_255[206-88] & 0x01); } // 0x01 = SCT support
00874 
00875 inline bool isSCTErrorRecoveryControlCapable(const ata_identify_device *drive)
00876   { return ((drive->words088_255[206-88] & 0x09) == 0x09); } // 0x08 = SCT Error Recovery Control support
00877 
00878 inline bool isSCTFeatureControlCapable(const ata_identify_device *drive)
00879   { return ((drive->words088_255[206-88] & 0x11) == 0x11); } // 0x10 = SCT Feature Control support
00880 
00881 inline bool isSCTDataTableCapable(const ata_identify_device *drive)
00882   { return ((drive->words088_255[206-88] & 0x21) == 0x21); } // 0x20 = SCT Data Table support
00883 
00884 int TestTime(const ata_smart_values * data, int testtype);
00885 
00886 // Attribute state
00887 enum ata_attr_state
00888 {
00889   ATTRSTATE_NON_EXISTING,   // No such Attribute
00890   ATTRSTATE_NO_NORMVAL,     // Normalized value not valid
00891   ATTRSTATE_NO_THRESHOLD,   // Unknown or no threshold
00892   ATTRSTATE_OK,             // Never failed
00893   ATTRSTATE_FAILED_PAST,    // Failed in the past
00894   ATTRSTATE_FAILED_NOW      // Failed now
00895 };
00896 
00897 // Get attribute state
00898 ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
00899                                   int attridx,
00900                                   const ata_smart_threshold_entry * thresholds,
00901                                   const ata_vendor_attr_defs & defs,
00902                                   unsigned char * threshval = 0);
00903 
00904 // Get attribute raw value.
00905 uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr,
00906                                 const ata_vendor_attr_defs & defs);
00907 
00908 // Format attribute raw value.
00909 std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
00910                                       const ata_vendor_attr_defs & defs);
00911 
00912 // Get attribute name
00913 std::string ata_get_smart_attr_name(unsigned char id,
00914                                     const ata_vendor_attr_defs & defs,
00915                                     int rpm = 0);
00916 
00917 // External handler function, for when a checksum is not correct.  Can
00918 // simply return if no action is desired, or can print error messages
00919 // as needed, or exit.  Is passed a string with the name of the Data
00920 // Structure with the incorrect checksum.
00921 void checksumwarning(const char *string);
00922 
00923 // Find attribute index for attribute id, -1 if not found.
00924 int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval);
00925 
00926 // Return Temperature Attribute raw value selected according to possible
00927 // non-default interpretations. If the Attribute does not exist, return 0
00928 unsigned char ata_return_temperature_value(const ata_smart_values * data, const ata_vendor_attr_defs & defs);
00929 
00930 
00931 #define MAX_ATTRIBUTE_NUM 256
00932 
00933 // Parse vendor attribute display def (-v option).
00934 // Return false on error.
00935 bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
00936                          ata_vendor_def_prior priority);
00937 
00938 // Get ID and increase flag of current pending or offline
00939 // uncorrectable attribute.
00940 unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
00941                               bool & increase);
00942 
00943 // Return a multiline string containing a list of valid arguments for
00944 // parse_attribute_def().
00945 std::string create_vendor_attribute_arg_list();
00946 
00947 // Parse firmwarebug def (-F option).
00948 // Return false on error.
00949 bool parse_firmwarebug_def(const char * opt, firmwarebug_defs & firmwarebugs);
00950 
00951 // Return a string of valid argument words for parse_firmwarebug_def()
00952 const char * get_valid_firmwarebug_args();
00953 
00954 
00955 // These are two of the functions that are defined in os_*.c and need
00956 // to be ported to get smartmontools onto another OS.
00957 // Moved to C++ interface
00958 //int ata_command_interface(int device, smart_command_set command, int select, char *data);
00959 //int escalade_command_interface(int fd, int escalade_port, int escalade_type, smart_command_set command, int select, char *data);
00960 //int marvell_command_interface(int device, smart_command_set command, int select, char *data);
00961 //int highpoint_command_interface(int device, smart_command_set command, int select, char *data);
00962 //int areca_command_interface(int fd, int disknum, smart_command_set command, int select, char *data);
00963 
00964 
00965 // This function is exported to give low-level capability
00966 int smartcommandhandler(ata_device * device, smart_command_set command, int select, char *data);
00967 
00968 // Print one self-test log entry.
00969 // Returns:
00970 // -1: failed self-test
00971 //  1: extended self-test completed without error
00972 //  0: otherwise
00973 int ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type,
00974                                unsigned char test_status,
00975                                unsigned short timestamp,
00976                                uint64_t failing_lba,
00977                                bool print_error_only, bool & print_header);
00978 
00979 // Print Smart self-test log, used by smartctl and smartd.
00980 int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * data, bool allentries,
00981                              firmwarebug_defs firmwarebugs);
00982 
00983 // Get capacity and sector sizes from IDENTIFY data
00984 struct ata_size_info
00985 {
00986   uint64_t sectors;
00987   uint64_t capacity;
00988   unsigned log_sector_size;
00989   unsigned phy_sector_size;
00990   unsigned log_sector_offset;
00991 };
00992 
00993 void ata_get_size_info(const ata_identify_device * id, ata_size_info & sizes);
00994 
00995 // Convenience function for formatting strings from ata_identify_device.
00996 void ata_format_id_string(char * out, const unsigned char * in, int n);
00997 
00998 // Utility routines.
00999 unsigned char checksum(const void * data);
01000 
01001 void swap2(char *location);
01002 void swap4(char *location);
01003 void swap8(char *location);
01004 // Typesafe variants using overloading
01005 inline void swapx(unsigned short * p)
01006   { swap2((char*)p); }
01007 inline void swapx(unsigned int * p)
01008   { swap4((char*)p); }
01009 inline void swapx(uint64_t * p)
01010   { swap8((char*)p); }
01011 
01012 // Return pseudo-device to parse "smartctl -r ataioctl,2 ..." output
01013 // and simulate an ATA device with same behaviour
01014 ata_device * get_parsed_ata_device(smart_interface * intf, const char * dev_name);
01015 
01016 #endif /* ATACMDS_H_ */