1 /*
2  * atacmds.h
3  *
4  * Home page of code is: https://www.smartmontools.org
5  *
6  * Copyright (C) 2002-11 Bruce Allen
7  * Copyright (C) 2008-19 Christian Franke
8  * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
9  *
10  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12 
13 #ifndef ATACMDS_H_
14 #define ATACMDS_H_
15 
16 #define ATACMDS_H_CVSID "$Id: atacmds.h 4934 2019-07-01 20:54:14Z chrfranke $"
17 
18 #include "dev_interface.h" // ata_device
19 #include "static_assert.h"
20 
21 // Add __attribute__((packed)) if compiler supports it
22 // because some gcc versions (at least ARM) lack support of #pragma pack()
23 #ifdef HAVE_ATTR_PACKED
24 #define ATTR_PACKED __attribute__((packed))
25 #else
26 #define ATTR_PACKED
27 #endif
28 
29 typedef enum {
30   // returns no data, just succeeds or fails
31   ENABLE,
32   DISABLE,
33   AUTOSAVE,
34   IMMEDIATE_OFFLINE,
35   AUTO_OFFLINE,
36   STATUS,       // just says if SMART is working or not
37   STATUS_CHECK, // says if disk's SMART status is healthy, or failing
38   // return 512 bytes of data:
39   READ_VALUES,
40   READ_THRESHOLDS,
41   READ_LOG,
42   IDENTIFY,
43   PIDENTIFY,
44   // returns 1 byte of data
45   CHECK_POWER_MODE,
46   // writes 512 bytes of data:
47   WRITE_LOG
48 } smart_command_set;
49 
50 
51 // ATA Specification Command Register Values (Commands)
52 #define ATA_CHECK_POWER_MODE            0xe5
53 #define ATA_IDENTIFY_DEVICE             0xec
54 #define ATA_IDENTIFY_PACKET_DEVICE      0xa1
55 #define ATA_IDLE                        0xe3
56 #define ATA_SMART_CMD                   0xb0
57 #define ATA_SECURITY_FREEZE_LOCK        0xf5
58 #ifndef ATA_SET_FEATURES
59 #define ATA_SET_FEATURES                0xef
60 #endif
61 #define ATA_STANDBY                     0xe2
62 #define ATA_STANDBY_IMMEDIATE           0xe0
63 
64 // SET_FEATURES subcommands
65 #define ATA_DISABLE_AAM                 0xc2
66 #define ATA_DISABLE_APM                 0x85
67 #define ATA_DISABLE_WRITE_CACHE         0x82
68 #define ATA_DISABLE_READ_LOOK_AHEAD     0x55
69 #define ATA_ENABLE_AAM                  0x42
70 #define ATA_ENABLE_APM                  0x05
71 #define ATA_ENABLE_WRITE_CACHE          0x02
72 #define ATA_ENABLE_READ_LOOK_AHEAD      0xaa
73 #define ATA_ENABLE_DISABLE_DSN          0x63
74 
75 // 48-bit commands
76 #define ATA_READ_LOG_EXT                0x2F
77 #define ATA_WRITE_LOG_EXT               0x3f
78 
79 // ATA Specification Feature Register Values (SMART Subcommands).
80 // Note that some are obsolete as of ATA-7.
81 #define ATA_SMART_READ_VALUES           0xd0
82 #define ATA_SMART_READ_THRESHOLDS       0xd1
83 #define ATA_SMART_AUTOSAVE              0xd2
84 #define ATA_SMART_SAVE                  0xd3
85 #define ATA_SMART_IMMEDIATE_OFFLINE     0xd4
86 #define ATA_SMART_READ_LOG_SECTOR       0xd5
87 #define ATA_SMART_WRITE_LOG_SECTOR      0xd6
88 #define ATA_SMART_WRITE_THRESHOLDS      0xd7
89 #define ATA_SMART_ENABLE                0xd8
90 #define ATA_SMART_DISABLE               0xd9
91 #define ATA_SMART_STATUS                0xda
92 // SFF 8035i Revision 2 Specification Feature Register Value (SMART
93 // Subcommand)
94 #define ATA_SMART_AUTO_OFFLINE          0xdb
95 
96 // Sector Number values for ATA_SMART_IMMEDIATE_OFFLINE Subcommand
97 #define OFFLINE_FULL_SCAN               0
98 #define SHORT_SELF_TEST                 1
99 #define EXTEND_SELF_TEST                2
100 #define CONVEYANCE_SELF_TEST            3
101 #define SELECTIVE_SELF_TEST             4
102 #define ABORT_SELF_TEST                 127
103 #define SHORT_CAPTIVE_SELF_TEST         129
104 #define EXTEND_CAPTIVE_SELF_TEST        130
105 #define CONVEYANCE_CAPTIVE_SELF_TEST    131
106 #define SELECTIVE_CAPTIVE_SELF_TEST     132
107 #define CAPTIVE_MASK                    (0x01<<7)
108 
109 // Maximum allowed number of SMART Attributes
110 #define NUMBER_ATA_SMART_ATTRIBUTES     30
111 
112 // Needed parts of the ATA DRIVE IDENTIFY Structure. Those labeled
113 // word* are NOT used.
114 #pragma pack(1)
115 struct ata_identify_device {
116   unsigned short words000_009[10];
117   unsigned char  serial_no[20];
118   unsigned short words020_022[3];
119   unsigned char  fw_rev[8];
120   unsigned char  model[40];
121   unsigned short words047_079[33];
122   unsigned short major_rev_num;
123   unsigned short minor_rev_num;
124   unsigned short command_set_1;
125   unsigned short command_set_2;
126   unsigned short command_set_extension;
127   unsigned short cfs_enable_1;
128   unsigned short word086;
129   unsigned short csf_default;
130   unsigned short words088_255[168];
131 } ATTR_PACKED;
132 #pragma pack()
133 STATIC_ASSERT(sizeof(ata_identify_device) == 512);
134 
135 /* ata_smart_attribute is the vendor specific in SFF-8035 spec */
136 #pragma pack(1)
137 struct ata_smart_attribute {
138   unsigned char id;
139   // meaning of flag bits: see MACROS just below
140   // WARNING: MISALIGNED!
141   unsigned short flags;
142   unsigned char current;
143   unsigned char worst;
144   unsigned char raw[6];
145   unsigned char reserv;
146 } ATTR_PACKED;
147 #pragma pack()
148 STATIC_ASSERT(sizeof(ata_smart_attribute) == 12);
149 
150 // MACROS to interpret the flags bits in the previous structure.
151 // These have not been implemented using bitflags and a union, to make
152 // it portable across bit/little endian and different platforms.
153 
154 // 0: Prefailure bit
155 
156 // From SFF 8035i Revision 2 page 19: Bit 0 (pre-failure/advisory bit)
157 // - If the value of this bit equals zero, an attribute value less
158 // than or equal to its corresponding attribute threshold indicates an
159 // advisory condition where the usage or age of the device has
160 // exceeded its intended design life period. If the value of this bit
161 // equals one, an attribute value less than or equal to its
162 // corresponding attribute threshold indicates a prefailure condition
163 // where imminent loss of data is being predicted.
164 #define ATTRIBUTE_FLAGS_PREFAILURE(x) (x & 0x01)
165 
166 // 1: Online bit
167 
168 //  From SFF 8035i Revision 2 page 19: Bit 1 (on-line data collection
169 // bit) - If the value of this bit equals zero, then the attribute
170 // value is updated only during off-line data collection
171 // activities. If the value of this bit equals one, then the attribute
172 // value is updated during normal operation of the device or during
173 // both normal operation and off-line testing.
174 #define ATTRIBUTE_FLAGS_ONLINE(x) (x & 0x02)
175 
176 
177 // The following are (probably) IBM's, Maxtors and  Quantum's definitions for the
178 // vendor-specific bits:
179 // 2: Performance type bit
180 #define ATTRIBUTE_FLAGS_PERFORMANCE(x) (x & 0x04)
181 
182 // 3: Errorrate type bit
183 #define ATTRIBUTE_FLAGS_ERRORRATE(x) (x & 0x08)
184 
185 // 4: Eventcount bit
186 #define ATTRIBUTE_FLAGS_EVENTCOUNT(x) (x & 0x10)
187 
188 // 5: Selfpereserving bit
189 #define ATTRIBUTE_FLAGS_SELFPRESERVING(x) (x & 0x20)
190 
191 // 6-15: Reserved for future use
192 #define ATTRIBUTE_FLAGS_OTHER(x) ((x) & 0xffc0)
193 
194 
195 // Format of data returned by SMART READ DATA
196 // Table 62 of T13/1699-D (ATA8-ACS) Revision 6a, September 2008
197 #pragma pack(1)
198 struct ata_smart_values {
199   unsigned short int revnumber;
200   struct ata_smart_attribute vendor_attributes [NUMBER_ATA_SMART_ATTRIBUTES];
201   unsigned char offline_data_collection_status;
202   unsigned char self_test_exec_status;  //IBM # segments for offline collection
203   unsigned short int total_time_to_complete_off_line; // IBM different
204   unsigned char vendor_specific_366; // Maxtor & IBM current segment pointer
205   unsigned char offline_data_collection_capability;
206   unsigned short int smart_capability;
207   unsigned char errorlog_capability;
208   unsigned char vendor_specific_371;  // Maxtor, IBM: self-test failure checkpoint see below!
209   unsigned char short_test_completion_time;
210   unsigned char extend_test_completion_time_b; // If 0xff, use 16-bit value below
211   unsigned char conveyance_test_completion_time;
212   unsigned short extend_test_completion_time_w; // e04130r2, added to T13/1699-D Revision 1c, April 2005
213   unsigned char reserved_377_385[9];
214   unsigned char vendor_specific_386_510[125]; // Maxtor bytes 508-509 Attribute/Threshold Revision #
215   unsigned char chksum;
216 } ATTR_PACKED;
217 #pragma pack()
218 STATIC_ASSERT(sizeof(ata_smart_values) == 512);
219 
220 /* Maxtor, IBM: self-test failure checkpoint byte meaning:
221  00 - write test
222  01 - servo basic
223  02 - servo random
224  03 - G-list scan
225  04 - Handling damage
226  05 - Read scan
227 */
228 
229 /* Vendor attribute of SMART Threshold (compare to ata_smart_attribute above) */
230 #pragma pack(1)
231 struct ata_smart_threshold_entry {
232   unsigned char id;
233   unsigned char threshold;
234   unsigned char reserved[10];
235 } ATTR_PACKED;
236 #pragma pack()
237 STATIC_ASSERT(sizeof(ata_smart_threshold_entry) == 12);
238 
239 /* Format of Read SMART THreshold Command */
240 /* Compare to ata_smart_values above */
241 #pragma pack(1)
242 struct ata_smart_thresholds_pvt {
243   unsigned short int revnumber;
244   struct ata_smart_threshold_entry thres_entries[NUMBER_ATA_SMART_ATTRIBUTES];
245   unsigned char reserved[149];
246   unsigned char chksum;
247 } ATTR_PACKED;
248 #pragma pack()
249 STATIC_ASSERT(sizeof(ata_smart_thresholds_pvt) == 512);
250 
251 
252 // Table 42 of T13/1321D Rev 1 spec (Error Data Structure)
253 #pragma pack(1)
254 struct ata_smart_errorlog_error_struct {
255   unsigned char reserved;
256   unsigned char error_register;
257   unsigned char sector_count;
258   unsigned char sector_number;
259   unsigned char cylinder_low;
260   unsigned char cylinder_high;
261   unsigned char drive_head;
262   unsigned char status;
263   unsigned char extended_error[19];
264   unsigned char state;
265   unsigned short timestamp;
266 } ATTR_PACKED;
267 #pragma pack()
268 STATIC_ASSERT(sizeof(ata_smart_errorlog_error_struct) == 30);
269 
270 
271 // Table 41 of T13/1321D Rev 1 spec (Command Data Structure)
272 #pragma pack(1)
273 struct ata_smart_errorlog_command_struct {
274   unsigned char devicecontrolreg;
275   unsigned char featuresreg;
276   unsigned char sector_count;
277   unsigned char sector_number;
278   unsigned char cylinder_low;
279   unsigned char cylinder_high;
280   unsigned char drive_head;
281   unsigned char commandreg;
282   unsigned int timestamp;
283 } ATTR_PACKED;
284 #pragma pack()
285 STATIC_ASSERT(sizeof(ata_smart_errorlog_command_struct) == 12);
286 
287 // Table 40 of T13/1321D Rev 1 spec (Error log data structure)
288 #pragma pack(1)
289 struct ata_smart_errorlog_struct {
290   struct ata_smart_errorlog_command_struct commands[5];
291   struct ata_smart_errorlog_error_struct error_struct;
292 } ATTR_PACKED;
293 #pragma pack()
294 STATIC_ASSERT(sizeof(ata_smart_errorlog_struct) == 90);
295 
296 // Table 39 of T13/1321D Rev 1 spec (SMART error log sector)
297 #pragma pack(1)
298 struct ata_smart_errorlog {
299   unsigned char revnumber;
300   unsigned char error_log_pointer;
301   struct ata_smart_errorlog_struct errorlog_struct[5];
302   unsigned short int ata_error_count;
303   unsigned char reserved[57];
304   unsigned char checksum;
305 } ATTR_PACKED;
306 #pragma pack()
307 STATIC_ASSERT(sizeof(ata_smart_errorlog) == 512);
308 
309 
310 // Extended Comprehensive SMART Error Log data structures
311 // See Section A.7 of
312 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
313 //   T13/1699-D Revision 6a (Working Draft), September 6, 2008.
314 
315 // Command data structure
316 // Table A.9 of T13/1699-D Revision 6a
317 #pragma pack(1)
318 struct ata_smart_exterrlog_command
319 {
320   unsigned char device_control_register;
321   unsigned char features_register;
322   unsigned char features_register_hi;
323   unsigned char count_register;
324   unsigned char count_register_hi;
325   unsigned char lba_low_register;
326   unsigned char lba_low_register_hi;
327   unsigned char lba_mid_register;
328   unsigned char lba_mid_register_hi;
329   unsigned char lba_high_register;
330   unsigned char lba_high_register_hi;
331   unsigned char device_register;
332   unsigned char command_register;
333 
334   unsigned char reserved;
335   unsigned int timestamp;
336 } ATTR_PACKED;
337 #pragma pack()
338 STATIC_ASSERT(sizeof(ata_smart_exterrlog_command) == 18);
339 
340 // Error data structure
341 // Table A.10 T13/1699-D Revision 6a
342 #pragma pack(1)
343 struct ata_smart_exterrlog_error
344 {
345   unsigned char device_control_register;
346   unsigned char error_register;
347   unsigned char count_register;
348   unsigned char count_register_hi;
349   unsigned char lba_low_register;
350   unsigned char lba_low_register_hi;
351   unsigned char lba_mid_register;
352   unsigned char lba_mid_register_hi;
353   unsigned char lba_high_register;
354   unsigned char lba_high_register_hi;
355   unsigned char device_register;
356   unsigned char status_register;
357 
358   unsigned char extended_error[19];
359   unsigned char state;
360   unsigned short timestamp;
361 } ATTR_PACKED;
362 #pragma pack()
363 STATIC_ASSERT(sizeof(ata_smart_exterrlog_error) == 34);
364 
365 // Error log data structure
366 // Table A.8 of T13/1699-D Revision 6a
367 #pragma pack(1)
368 struct ata_smart_exterrlog_error_log
369 {
370   ata_smart_exterrlog_command commands[5];
371   ata_smart_exterrlog_error error;
372 } ATTR_PACKED;
373 #pragma pack()
374 STATIC_ASSERT(sizeof(ata_smart_exterrlog_error_log) == 124);
375 
376 // Ext. Comprehensive SMART error log
377 // Table A.7 of T13/1699-D Revision 6a
378 #pragma pack(1)
379 struct ata_smart_exterrlog
380 {
381   unsigned char version;
382   unsigned char reserved1;
383   unsigned short error_log_index;
384   ata_smart_exterrlog_error_log error_logs[4];
385   unsigned short device_error_count;
386   unsigned char reserved2[9];
387   unsigned char checksum;
388 } ATTR_PACKED;
389 #pragma pack()
390 STATIC_ASSERT(sizeof(ata_smart_exterrlog) == 512);
391 
392 
393 // Table 45 of T13/1321D Rev 1 spec (Self-test log descriptor entry)
394 #pragma pack(1)
395 struct ata_smart_selftestlog_struct {
396   unsigned char selftestnumber; // Sector number register
397   unsigned char selfteststatus;
398   unsigned short int timestamp;
399   unsigned char selftestfailurecheckpoint;
400   unsigned int lbafirstfailure;
401   unsigned char vendorspecific[15];
402 } ATTR_PACKED;
403 #pragma pack()
404 STATIC_ASSERT(sizeof(ata_smart_selftestlog_struct) == 24);
405 
406 // Table 44 of T13/1321D Rev 1 spec (Self-test log data structure)
407 #pragma pack(1)
408 struct ata_smart_selftestlog {
409   unsigned short int revnumber;
410   struct ata_smart_selftestlog_struct selftest_struct[21];
411   unsigned char vendorspecific[2];
412   unsigned char mostrecenttest;
413   unsigned char reserved[2];
414   unsigned char chksum;
415 } ATTR_PACKED;
416 #pragma pack()
417 STATIC_ASSERT(sizeof(ata_smart_selftestlog) == 512);
418 
419 // Extended SMART Self-test log data structures
420 // See Section A.8 of
421 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
422 //   T13/1699-D Revision 6a (Working Draft), September 6, 2008.
423 
424 // Extended Self-test log descriptor entry
425 // Table A.13 of T13/1699-D Revision 6a
426 #pragma pack(1)
427 struct ata_smart_extselftestlog_desc
428 {
429   unsigned char self_test_type;
430   unsigned char self_test_status;
431   unsigned short timestamp;
432   unsigned char checkpoint;
433   unsigned char failing_lba[6];
434   unsigned char vendorspecific[15];
435 } ATTR_PACKED;
436 #pragma pack()
437 STATIC_ASSERT(sizeof(ata_smart_extselftestlog_desc) == 26);
438 
439 // Extended Self-test log data structure
440 // Table A.12 of T13/1699-D Revision 6a
441 #pragma pack(1)
442 struct ata_smart_extselftestlog
443 {
444   unsigned char version;
445   unsigned char reserved1;
446   unsigned short log_desc_index;
447   struct ata_smart_extselftestlog_desc log_descs[19];
448   unsigned char vendor_specifc[2];
449   unsigned char reserved2[11];
450   unsigned char chksum;
451 } ATTR_PACKED;
452 #pragma pack()
453 STATIC_ASSERT(sizeof(ata_smart_extselftestlog) == 512);
454 
455 // SMART LOG DIRECTORY Table 52 of T13/1532D Vol 1 Rev 1a
456 #pragma pack(1)
457 struct ata_smart_log_entry {
458   unsigned char numsectors;
459   unsigned char reserved;
460 } ATTR_PACKED;
461 #pragma pack()
462 STATIC_ASSERT(sizeof(ata_smart_log_entry) == 2);
463 
464 #pragma pack(1)
465 struct ata_smart_log_directory {
466   unsigned short int logversion;
467   struct ata_smart_log_entry entry[255];
468 } ATTR_PACKED;
469 #pragma pack()
470 STATIC_ASSERT(sizeof(ata_smart_log_directory) == 512);
471 
472 // SMART SELECTIVE SELF-TEST LOG Table 61 of T13/1532D Volume 1
473 // Revision 3
474 #pragma pack(1)
475 struct test_span {
476   uint64_t start;
477   uint64_t end;
478 } ATTR_PACKED;
479 #pragma pack()
480 STATIC_ASSERT(sizeof(test_span) == 16);
481 
482 #pragma pack(1)
483 struct ata_selective_self_test_log {
484   unsigned short     logversion;
485   struct test_span   span[5];
486   unsigned char      reserved1[337-82+1];
487   unsigned char      vendor_specific1[491-338+1];
488   uint64_t           currentlba;
489   unsigned short     currentspan;
490   unsigned short     flags;
491   unsigned char      vendor_specific2[507-504+1];
492   unsigned short     pendingtime;
493   unsigned char      reserved2;
494   unsigned char      checksum;
495 } ATTR_PACKED;
496 #pragma pack()
497 STATIC_ASSERT(sizeof(ata_selective_self_test_log) == 512);
498 
499 #define SELECTIVE_FLAG_DOSCAN  (0x0002)
500 #define SELECTIVE_FLAG_PENDING (0x0008)
501 #define SELECTIVE_FLAG_ACTIVE  (0x0010)
502 
503 
504 // SCT (SMART Command Transport) data structures
505 // See Sections 8.2 and 8.3 of:
506 //   AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
507 //   T13/1699-D Revision 3f (Working Draft), December 11, 2006.
508 
509 // SCT Status response (read with SMART_READ_LOG page 0xe0)
510 // Table 194 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
511 #pragma pack(1)
512 struct ata_sct_status_response
513 {
514   unsigned short format_version;    // 0-1: Status response format version number (2, 3)
515   unsigned short sct_version;       // 2-3: Vendor specific version number
516   unsigned short sct_spec;          // 4-5: SCT level supported (1)
517   unsigned int status_flags;        // 6-9: Status flags (Bit 0: Segment initialized, Bits 1-31: reserved)
518   unsigned char device_state;       // 10: Device State (0-5)
519   unsigned char bytes011_013[3];    // 11-13: reserved
520   unsigned short ext_status_code;   // 14-15: Status of last SCT command (0xffff if executing)
521   unsigned short action_code;       // 16-17: Action code of last SCT command
522   unsigned short function_code;     // 18-19: Function code of last SCT command
523   unsigned char bytes020_039[20];   // 20-39: reserved
524   uint64_t lba_current;             // 40-47: LBA of SCT command executing in background
525   unsigned char bytes048_199[152];  // 48-199: reserved
526   signed char hda_temp;             // 200: Current temperature in Celsius (0x80 = invalid)
527   signed char min_temp;             // 201: Minimum temperature this power cycle
528   signed char max_temp;             // 202: Maximum temperature this power cycle
529   signed char life_min_temp;        // 203: Minimum lifetime temperature
530   signed char life_max_temp;        // 204: Maximum lifetime temperature
531   signed char max_op_limit;         // 205: Specified maximum operating temperature (ACS-4)
532   unsigned int over_limit_count;    // 206-209: # intervals since last reset with temperature > Max Op Limit
533   unsigned int under_limit_count;   // 210-213: # intervals since last reset with temperature < Min Op Limit
534   unsigned short smart_status;      // 214-215: LBA(32:8) of SMART RETURN STATUS (0, 0x2cf4, 0xc24f) (ACS-4)
535   unsigned short min_erc_time;      // 216-217: Minimum supported value for ERC (ACS-4)
536   unsigned char bytes216_479[479-218+1]; // 218-479: reserved
537   unsigned char vendor_specific[32];// 480-511: vendor specific
538 } ATTR_PACKED;
539 #pragma pack()
540 STATIC_ASSERT(sizeof(ata_sct_status_response) == 512);
541 
542 // SCT Error Recovery Control command (send with SMART_WRITE_LOG page 0xe0)
543 // Table 88 of T13/1699-D Revision 6a
544 #pragma pack(1)
545 struct ata_sct_error_recovery_control_command
546 {
547   unsigned short action_code;       // 3 = Error Recovery Control
548   unsigned short function_code;     // 1 = Set, 2 = Return
549   unsigned short selection_code;    // 1 = Read Timer, 2 = Write Timer
550   unsigned short time_limit;        // If set: Recovery time limit in 100ms units
551   unsigned short words004_255[252]; // reserved
552 } ATTR_PACKED;
553 #pragma pack()
554 STATIC_ASSERT(sizeof(ata_sct_error_recovery_control_command) == 512);
555 
556 // SCT Feature Control command (send with SMART_WRITE_LOG page 0xe0)
557 // Table 72 of T13/1699-D Revision 3f
558 #pragma pack(1)
559 struct ata_sct_feature_control_command
560 {
561   unsigned short action_code;       // 4 = Feature Control
562   unsigned short function_code;     // 1 = Set, 2 = Return, 3 = Return options
563   unsigned short feature_code;      // 3 = Temperature logging interval
564   unsigned short state;             // Interval
565   unsigned short option_flags;      // Bit 0: persistent, Bits 1-15: reserved
566   unsigned short words005_255[251]; // reserved
567 } ATTR_PACKED;
568 #pragma pack()
569 STATIC_ASSERT(sizeof(ata_sct_feature_control_command) == 512);
570 
571 // SCT Data Table command (send with SMART_WRITE_LOG page 0xe0)
572 // Table 73 of T13/1699-D Revision 3f
573 #pragma pack(1)
574 struct ata_sct_data_table_command
575 {
576   unsigned short action_code;       // 5 = Data Table
577   unsigned short function_code;     // 1 = Read Table
578   unsigned short table_id;          // 2 = Temperature History
579   unsigned short words003_255[253]; // reserved
580 } ATTR_PACKED;
581 #pragma pack()
582 STATIC_ASSERT(sizeof(ata_sct_data_table_command) == 512);
583 
584 // SCT Temperature History Table (read with SMART_READ_LOG page 0xe1)
585 // Table 75 of T13/1699-D Revision 3f
586 #pragma pack(1)
587 struct ata_sct_temperature_history_table
588 {
589   unsigned short format_version;    // 0-1: Data table format version number (2)
590   unsigned short sampling_period;   // 2-3: Temperature sampling period in minutes
591   unsigned short interval;          // 4-5: Timer interval between history entries
592   signed char max_op_limit;         // 6: Maximum recommended continuous operating temperature
593   signed char over_limit;           // 7: Maximum temperature limit
594   signed char min_op_limit;         // 8: Minimum recommended continuous operating limit
595   signed char under_limit;          // 9: Minimum temperature limit
596   unsigned char bytes010_029[20];   // 10-29: reserved
597   unsigned short cb_size;           // 30-31: Number of history entries (range 128-478)
598   unsigned short cb_index;          // 32-33: Index of last updated entry (zero-based)
599   signed char cb[478];              // 34-(34+cb_size-1): Circular buffer of temperature values
600 } ATTR_PACKED;
601 #pragma pack()
602 STATIC_ASSERT(sizeof(ata_sct_temperature_history_table) == 512);
603 
604 // Possible values for span_args.mode
605 enum {
606   SEL_RANGE, // MIN-MAX
607   SEL_REDO,  // redo this
608   SEL_NEXT,  // do next range
609   SEL_CONT   // redo or next depending of last test status
610 };
611 
612 // Arguments for selective self-test
613 struct ata_selective_selftest_args
614 {
615   // Arguments for each span
616   struct span_args
617   {
618     uint64_t start;   // First block
619     uint64_t end;     // Last block
620     int mode;         // SEL_*, see above
621 
span_argsata_selective_selftest_args::span_args622     span_args()
623       : start(0), end(0), mode(SEL_RANGE) { }
624   };
625 
626   span_args span[5];  // Range and mode for 5 spans
627   int num_spans;      // Number of spans
628   int pending_time;   // One plus time in minutes to wait after powerup before restarting
629                       // interrupted offline scan after selective self-test.
630   int scan_after_select; // Run offline scan after selective self-test:
631                       // 0: don't change,
632                       // 1: turn off scan after selective self-test,
633                       // 2: turn on scan after selective self-test.
634 
ata_selective_selftest_argsata_selective_selftest_args635   ata_selective_selftest_args()
636     : num_spans(0), pending_time(0), scan_after_select(0) { }
637 };
638 
639 // Priority for vendor attribute defs
640 enum ata_vendor_def_prior
641 {
642   PRIOR_DEFAULT,
643   PRIOR_DATABASE,
644   PRIOR_USER
645 };
646 
647 // Raw attribute value print formats
648 enum ata_attr_raw_format
649 {
650   RAWFMT_DEFAULT,
651   RAWFMT_RAW8,
652   RAWFMT_RAW16,
653   RAWFMT_RAW48,
654   RAWFMT_HEX48,
655   RAWFMT_RAW56,
656   RAWFMT_HEX56,
657   RAWFMT_RAW64,
658   RAWFMT_HEX64,
659   RAWFMT_RAW16_OPT_RAW16,
660   RAWFMT_RAW16_OPT_AVG16,
661   RAWFMT_RAW24_OPT_RAW8,
662   RAWFMT_RAW24_DIV_RAW24,
663   RAWFMT_RAW24_DIV_RAW32,
664   RAWFMT_SEC2HOUR,
665   RAWFMT_MIN2HOUR,
666   RAWFMT_HALFMIN2HOUR,
667   RAWFMT_MSEC24_HOUR32,
668   RAWFMT_TEMPMINMAX,
669   RAWFMT_TEMP10X,
670 };
671 
672 // Attribute flags
673 enum {
674   ATTRFLAG_INCREASING  = 0x01, // Value not reset (for reallocated/pending counts)
675   ATTRFLAG_NO_NORMVAL  = 0x02, // Normalized value not valid
676   ATTRFLAG_NO_WORSTVAL = 0x04, // Worst value not valid
677   ATTRFLAG_HDD_ONLY    = 0x08, // DEFAULT setting for HDD only
678   ATTRFLAG_SSD_ONLY    = 0x10, // DEFAULT setting for SSD only
679 };
680 
681 // Vendor attribute display defs for all attribute ids
682 class ata_vendor_attr_defs
683 {
684 public:
685   struct entry
686   {
687     std::string name; // Attribute name, empty for default
688     ata_attr_raw_format raw_format; // Raw value print format
689     ata_vendor_def_prior priority; // Setting priority
690     unsigned flags; // ATTRFLAG_*
691     char byteorder[8+1]; // String [012345rvwz] to define byte order
692 
entryentry693     entry()
694       : raw_format(RAWFMT_DEFAULT),
695         priority(PRIOR_DEFAULT),
696         flags(0)
697       { byteorder[0] = 0; }
698   };
699 
700   entry & operator[](unsigned char id)
701     { return m_defs[id]; }
702 
703   const entry & operator[](unsigned char id) const
704     { return m_defs[id]; }
705 
706 private:
707   entry m_defs[256];
708 };
709 
710 
711 // Possible values for firmwarebugs
712 enum firmwarebug_t {
713   BUG_NONE = 0,
714   BUG_NOLOGDIR,
715   BUG_SAMSUNG,
716   BUG_SAMSUNG2,
717   BUG_SAMSUNG3,
718   BUG_XERRORLBA
719 };
720 
721 // Set of firmware bugs
722 class firmwarebug_defs
723 {
724 public:
firmwarebug_defs()725   firmwarebug_defs()
726     : m_bugs(0) { }
727 
is_set(firmwarebug_t bug)728   bool is_set(firmwarebug_t bug) const
729     { return !!(m_bugs & (1 << bug)); }
730 
set(firmwarebug_t bug)731   void set(firmwarebug_t bug)
732     { m_bugs |= (1 << bug); }
733 
set(firmwarebug_defs bugs)734   void set(firmwarebug_defs bugs)
735     { m_bugs |= bugs.m_bugs; }
736 
737 private:
738   unsigned m_bugs;
739 };
740 
741 
742 // Print ATA debug messages?
743 extern unsigned char ata_debugmode;
744 
745 // Suppress serial number?
746 extern bool dont_print_serial_number;
747 
748 // Get information from drive
749 int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_swapped_id,
750                       unsigned char * raw_buf = 0);
751 int ataCheckPowerMode(ata_device * device);
752 
753 // Issue a no-data ATA command with optional sector count register value
754 bool ata_nodata_command(ata_device * device, unsigned char command, int sector_count = -1);
755 
756 // Issue SET FEATURES command with optional sector count register value
757 bool ata_set_features(ata_device * device, unsigned char features, int sector_count = -1);
758 
759 /* Read S.M.A.R.T information from drive */
760 int ataReadSmartValues(ata_device * device,struct ata_smart_values *);
761 int ataReadSmartThresholds(ata_device * device, struct ata_smart_thresholds_pvt *);
762 int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data,
763                      firmwarebug_defs firmwarebugs);
764 int ataReadSelfTestLog(ata_device * device, ata_smart_selftestlog * data,
765                        firmwarebug_defs firmwarebugs);
766 int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_test_log *data);
767 int ataReadLogDirectory(ata_device * device, ata_smart_log_directory *, bool gpl);
768 
769 // Write GP Log page(s)
770 bool ataWriteLogExt(ata_device * device, unsigned char logaddr,
771                     unsigned page, void * data, unsigned nsectors);
772 
773 // Read GP Log page(s)
774 bool ataReadLogExt(ata_device * device, unsigned char logaddr,
775                    unsigned char features, unsigned page,
776                    void * data, unsigned nsectors);
777 // Read SMART Log page(s)
778 bool ataReadSmartLog(ata_device * device, unsigned char logaddr,
779                      void * data, unsigned nsectors);
780 // Read SMART Extended Comprehensive Error Log
781 bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log,
782                         unsigned page, unsigned nsectors, firmwarebug_defs firmwarebugs);
783 // Read SMART Extended Self-test Log
784 bool ataReadExtSelfTestLog(ata_device * device, ata_smart_extselftestlog * log,
785                            unsigned nsectors);
786 
787 // Read SCT information
788 int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts);
789 int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * tmh,
790                        ata_sct_status_response * sts);
791 // Set SCT temperature logging interval
792 int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persistent);
793 
794 // Get/Set SCT Error Recovery Control
795 int ataGetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short & time_limit);
796 int ataSetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short time_limit);
797 
798 
799 /* Enable/Disable SMART on device */
800 int ataEnableSmart (ata_device * device);
801 int ataDisableSmart (ata_device * device);
802 int ataEnableAutoSave(ata_device * device);
803 int ataDisableAutoSave(ata_device * device);
804 
805 /* Automatic Offline Testing */
806 int ataEnableAutoOffline (ata_device * device);
807 int ataDisableAutoOffline (ata_device * device);
808 
809 /* S.M.A.R.T. test commands */
810 int ataSmartTest(ata_device * device, int testtype, bool force,
811                  const ata_selective_selftest_args & args,
812                  const ata_smart_values * sv, uint64_t num_sectors);
813 
814 int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_args & args,
815                                  const ata_smart_values * sv, uint64_t num_sectors,
816                                  const ata_selective_selftest_args * prev_spans = 0);
817 
818 // Get World Wide Name (WWN) fields.
819 // Return NAA field or -1 if WWN is unsupported.
820 int ata_get_wwn(const ata_identify_device * id, unsigned & oui, uint64_t & unique_id);
821 
822 // Get nominal media rotation rate.
823 // Returns: 0 = not reported, 1 = SSD, >1 = HDD rpm, < 0 = -(Unknown value)
824 int ata_get_rotation_rate(const ata_identify_device * id);
825 
826 // If SMART supported, this is guaranteed to return 1 if SMART is enabled, else 0.
827 int ataDoesSmartWork(ata_device * device);
828 
829 // returns 1 if SMART supported, 0 if not supported or can't tell
830 int ataSmartSupport(const ata_identify_device * drive);
831 
832 // Return values:
833 //  1: Write Cache Reordering enabled
834 //  2: Write Cache Reordering disabled
835 // -1: error
836 int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool persistent, bool set);
837 
838 // Return values:
839 // 1: Write cache controlled by ATA Set Features command
840 // 2: Force enable write cache
841 // 3: Force disable write cache
842 int ataGetSetSCTWriteCache(ata_device * device, unsigned short state, bool persistent, bool set);
843 
844 // Return values:
845 //  1: SMART enabled
846 //  0: SMART disabled
847 // -1: can't tell if SMART is enabled -- try issuing ataDoesSmartWork command to see
848 int ataIsSmartEnabled(const ata_identify_device * drive);
849 
850 int ataSmartStatus2(ata_device * device);
851 
852 bool isSmartErrorLogCapable(const ata_smart_values * data, const ata_identify_device * identity);
853 
854 bool isSmartTestLogCapable(const ata_smart_values * data, const ata_identify_device * identity);
855 
856 bool isGeneralPurposeLoggingCapable(const ata_identify_device * identity);
857 
858 // SMART self-test capability is also indicated in bit 1 of DEVICE
859 // IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
860 // However this was only introduced in ATA-6 (but self-test log was in
861 // ATA-5).
isSupportExecuteOfflineImmediate(const ata_smart_values * data)862 inline bool isSupportExecuteOfflineImmediate(const ata_smart_values *data)
863   { return !!(data->offline_data_collection_capability & 0x01); }
864 
865 // TODO: Remove uses of this check.  Bit 1 is vendor specific since ATA-4.
866 // Automatic timer support was only documented for very old IBM drives
867 // (for example IBM Travelstar 40GNX).
isSupportAutomaticTimer(const ata_smart_values * data)868 inline bool isSupportAutomaticTimer(const ata_smart_values * data)
869   { return !!(data->offline_data_collection_capability & 0x02); }
870 
isSupportOfflineAbort(const ata_smart_values * data)871 inline bool isSupportOfflineAbort(const ata_smart_values *data)
872   { return !!(data->offline_data_collection_capability & 0x04); }
873 
isSupportOfflineSurfaceScan(const ata_smart_values * data)874 inline bool isSupportOfflineSurfaceScan(const ata_smart_values * data)
875   { return !!(data->offline_data_collection_capability & 0x08); }
876 
isSupportSelfTest(const ata_smart_values * data)877 inline bool isSupportSelfTest(const ata_smart_values * data)
878   { return !!(data->offline_data_collection_capability & 0x10); }
879 
isSupportConveyanceSelfTest(const ata_smart_values * data)880 inline bool isSupportConveyanceSelfTest(const ata_smart_values * data)
881   { return !!(data->offline_data_collection_capability & 0x20); }
882 
isSupportSelectiveSelfTest(const ata_smart_values * data)883 inline bool isSupportSelectiveSelfTest(const ata_smart_values * data)
884   { return !!(data->offline_data_collection_capability & 0x40); }
885 
isSCTCapable(const ata_identify_device * drive)886 inline bool isSCTCapable(const ata_identify_device *drive)
887   { return !!(drive->words088_255[206-88] & 0x01); } // 0x01 = SCT support
888 
isSCTErrorRecoveryControlCapable(const ata_identify_device * drive)889 inline bool isSCTErrorRecoveryControlCapable(const ata_identify_device *drive)
890   { return ((drive->words088_255[206-88] & 0x09) == 0x09); } // 0x08 = SCT Error Recovery Control support
891 
isSCTFeatureControlCapable(const ata_identify_device * drive)892 inline bool isSCTFeatureControlCapable(const ata_identify_device *drive)
893   { return ((drive->words088_255[206-88] & 0x11) == 0x11); } // 0x10 = SCT Feature Control support
894 
isSCTDataTableCapable(const ata_identify_device * drive)895 inline bool isSCTDataTableCapable(const ata_identify_device *drive)
896   { return ((drive->words088_255[206-88] & 0x21) == 0x21); } // 0x20 = SCT Data Table support
897 
898 int TestTime(const ata_smart_values * data, int testtype);
899 
900 // Attribute state
901 enum ata_attr_state
902 {
903   ATTRSTATE_NON_EXISTING,   // No such Attribute
904   ATTRSTATE_NO_NORMVAL,     // Normalized value not valid
905   ATTRSTATE_NO_THRESHOLD,   // Unknown or no threshold
906   ATTRSTATE_OK,             // Never failed
907   ATTRSTATE_FAILED_PAST,    // Failed in the past
908   ATTRSTATE_FAILED_NOW      // Failed now
909 };
910 
911 // Get attribute state
912 ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
913                                   int attridx,
914                                   const ata_smart_threshold_entry * thresholds,
915                                   const ata_vendor_attr_defs & defs,
916                                   unsigned char * threshval = 0);
917 
918 // Get attribute raw value.
919 uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr,
920                                 const ata_vendor_attr_defs & defs);
921 
922 // Format attribute raw value.
923 std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
924                                       const ata_vendor_attr_defs & defs);
925 
926 // Get attribute name
927 std::string ata_get_smart_attr_name(unsigned char id,
928                                     const ata_vendor_attr_defs & defs,
929                                     int rpm = 0);
930 
931 // External handler function, for when a checksum is not correct.  Can
932 // simply return if no action is desired, or can print error messages
933 // as needed, or exit.  Is passed a string with the name of the Data
934 // Structure with the incorrect checksum.
935 void checksumwarning(const char *string);
936 
937 // Find attribute index for attribute id, -1 if not found.
938 int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval);
939 
940 // Return Temperature Attribute raw value selected according to possible
941 // non-default interpretations. If the Attribute does not exist, return 0
942 unsigned char ata_return_temperature_value(const ata_smart_values * data, const ata_vendor_attr_defs & defs);
943 
944 
945 #define MAX_ATTRIBUTE_NUM 256
946 
947 // Parse vendor attribute display def (-v option).
948 // Return false on error.
949 bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
950                          ata_vendor_def_prior priority);
951 
952 // Get ID and increase flag of current pending or offline
953 // uncorrectable attribute.
954 unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
955                               bool & increase);
956 
957 // Return a multiline string containing a list of valid arguments for
958 // parse_attribute_def().
959 std::string create_vendor_attribute_arg_list();
960 
961 // Parse firmwarebug def (-F option).
962 // Return false on error.
963 bool parse_firmwarebug_def(const char * opt, firmwarebug_defs & firmwarebugs);
964 
965 // Return a string of valid argument words for parse_firmwarebug_def()
966 const char * get_valid_firmwarebug_args();
967 
968 
969 // These are two of the functions that are defined in os_*.c and need
970 // to be ported to get smartmontools onto another OS.
971 // Moved to C++ interface
972 //int ata_command_interface(int device, smart_command_set command, int select, char *data);
973 //int escalade_command_interface(int fd, int escalade_port, int escalade_type, smart_command_set command, int select, char *data);
974 //int marvell_command_interface(int device, smart_command_set command, int select, char *data);
975 //int highpoint_command_interface(int device, smart_command_set command, int select, char *data);
976 //int areca_command_interface(int fd, int disknum, smart_command_set command, int select, char *data);
977 
978 
979 // This function is exported to give low-level capability
980 int smartcommandhandler(ata_device * device, smart_command_set command, int select, char *data);
981 
982 // Get capacity and sector sizes from IDENTIFY data
983 struct ata_size_info
984 {
985   uint64_t sectors;
986   uint64_t capacity;
987   unsigned log_sector_size;
988   unsigned phy_sector_size;
989   unsigned log_sector_offset;
990 };
991 
992 void ata_get_size_info(const ata_identify_device * id, ata_size_info & sizes);
993 
994 // Convenience function for formatting strings from ata_identify_device.
995 void ata_format_id_string(char * out, const unsigned char * in, int n);
996 
997 // Utility routines.
998 unsigned char checksum(const void * data);
999 
1000 // Return pseudo-device to parse "smartctl -r ataioctl,2 ..." output
1001 // and simulate an ATA device with same behaviour
1002 ata_device * get_parsed_ata_device(smart_interface * intf, const char * dev_name);
1003 
1004 #endif /* ATACMDS_H_ */
1005