-
Notifications
You must be signed in to change notification settings - Fork 50
/
atacmds.cpp
2841 lines (2476 loc) · 88.2 KB
/
atacmds.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* atacmds.cpp
*
* Home page of code is: https://www.smartmontools.org
*
* Copyright (C) 2002-11 Bruce Allen
* Copyright (C) 2008-21 Christian Franke
* Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
* Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <ctype.h>
#include "atacmds.h"
#include "knowndrives.h" // get_default_attr_defs()
#include "utility.h"
#include "dev_ata_cmd_set.h" // for parsed_ata_device
const char * atacmds_cpp_cvsid = "$Id$"
ATACMDS_H_CVSID;
// Print ATA debug messages?
unsigned char ata_debugmode = 0;
// Suppress serial number?
// (also used in scsiprint.cpp)
bool dont_print_serial_number = false;
#define SMART_CYL_LOW 0x4F
#define SMART_CYL_HI 0xC2
// SMART RETURN STATUS yields SMART_CYL_HI,SMART_CYL_LOW to indicate drive
// is healthy and SRET_STATUS_HI_EXCEEDED,SRET_STATUS_MID_EXCEEDED to
// indicate that a threshold exceeded condition has been detected.
// Those values (byte pairs) are placed in ATA register "LBA 23:8".
#define SRET_STATUS_HI_EXCEEDED 0x2C
#define SRET_STATUS_MID_EXCEEDED 0xF4
// Get ID and increase flag of current pending or offline
// uncorrectable attribute.
unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
bool & increase)
{
unsigned char id = (!offline ? 197 : 198);
const ata_vendor_attr_defs::entry & def = defs[id];
if (def.flags & ATTRFLAG_INCREASING)
increase = true; // '-v 19[78],increasing' option
else if (def.name.empty() || (id == 198 && def.name == "Offline_Scan_UNC_SectCt"))
increase = false; // no or '-v 198,offlinescanuncsectorct' option
else
id = 0; // other '-v 19[78],...' option
return id;
}
#if 0 // TODO: never used
// This are the meanings of the Self-test failure checkpoint byte.
// This is in the self-test log at offset 4 bytes into the self-test
// descriptor and in the SMART READ DATA structure at byte offset
// 371. These codes are not well documented. The meanings returned by
// this routine are used (at least) by Maxtor and IBM. Returns NULL if
// not recognized. Currently the maximum length is 15 bytes.
const char *SelfTestFailureCodeName(unsigned char which){
switch (which) {
case 0:
return "Write_Test";
case 1:
return "Servo_Basic";
case 2:
return "Servo_Random";
case 3:
return "G-list_Scan";
case 4:
return "Handling_Damage";
case 5:
return "Read_Scan";
default:
return NULL;
}
}
#endif
// Table of raw print format names
struct format_name_entry
{
const char * name;
ata_attr_raw_format format;
};
const format_name_entry format_names[] = {
{"raw8" , RAWFMT_RAW8},
{"raw16" , RAWFMT_RAW16},
{"raw48" , RAWFMT_RAW48},
{"hex48" , RAWFMT_HEX48},
{"raw56" , RAWFMT_RAW56},
{"hex56" , RAWFMT_HEX56},
{"raw64" , RAWFMT_RAW64},
{"hex64" , RAWFMT_HEX64},
{"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16},
{"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16},
{"raw24(raw8)" , RAWFMT_RAW24_OPT_RAW8},
{"raw24/raw24" , RAWFMT_RAW24_DIV_RAW24},
{"raw24/raw32" , RAWFMT_RAW24_DIV_RAW32},
{"sec2hour" , RAWFMT_SEC2HOUR},
{"min2hour" , RAWFMT_MIN2HOUR},
{"halfmin2hour" , RAWFMT_HALFMIN2HOUR},
{"msec24hour32" , RAWFMT_MSEC24_HOUR32},
{"tempminmax" , RAWFMT_TEMPMINMAX},
{"temp10x" , RAWFMT_TEMP10X},
};
const unsigned num_format_names = sizeof(format_names)/sizeof(format_names[0]);
// Table to map old to new '-v' option arguments
const char * const map_old_vendor_opts[][2] = {
{ "9,halfminutes" , "9,halfmin2hour,Power_On_Half_Minutes"},
{ "9,minutes" , "9,min2hour,Power_On_Minutes"},
{ "9,seconds" , "9,sec2hour,Power_On_Seconds"},
{ "9,temp" , "9,tempminmax,Temperature_Celsius"},
{"192,emergencyretractcyclect" , "192,raw48,Emerg_Retract_Cycle_Ct"},
{"193,loadunload" , "193,raw24/raw24"},
{"194,10xCelsius" , "194,temp10x,Temperature_Celsius_x10"},
{"194,unknown" , "194,raw48,Unknown_Attribute"},
{"197,increasing" , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
{"198,offlinescanuncsectorct" , "198,raw48,Offline_Scan_UNC_SectCt"}, // see also get_unc_attr_id() above
{"198,increasing" , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
{"200,writeerrorcount" , "200,raw48,Write_Error_Count"},
{"201,detectedtacount" , "201,raw48,Detected_TA_Count"},
{"220,temp" , "220,tempminmax,Temperature_Celsius"},
};
const unsigned num_old_vendor_opts = sizeof(map_old_vendor_opts)/sizeof(map_old_vendor_opts[0]);
// Parse vendor attribute display def (-v option).
// Return false on error.
bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
ata_vendor_def_prior priority)
{
// Map old -> new options
unsigned i;
for (i = 0; i < num_old_vendor_opts; i++) {
if (!strcmp(opt, map_old_vendor_opts[i][0])) {
opt = map_old_vendor_opts[i][1];
break;
}
}
// Parse option
int len = strlen(opt);
int id = 0, n1 = -1, n2 = -1;
char fmtname[32+1], attrname[32+1], hddssd[3+1];
attrname[0] = hddssd[0] = 0;
if (opt[0] == 'N') {
// "N,format[,name]"
if (!( sscanf(opt, "N,%32[^,]%n,%32[^,]%n", fmtname, &n1, attrname, &n2) >= 1
&& (n1 == len || n2 == len)))
return false;
}
else {
// "id,format[+][,name[,HDD|SSD]]"
int n3 = -1;
if (!( sscanf(opt, "%d,%32[^,]%n,%32[^,]%n,%3[DHS]%n",
&id, fmtname, &n1, attrname, &n2, hddssd, &n3) >= 2
&& 1 <= id && id <= 255
&& ( n1 == len || n2 == len
// ",HDD|SSD" for DEFAULT settings only
|| (n3 == len && priority == PRIOR_DEFAULT))))
return false;
}
unsigned flags = 0;
// For "-v 19[78],increasing" above
if (fmtname[strlen(fmtname)-1] == '+') {
fmtname[strlen(fmtname)-1] = 0;
flags = ATTRFLAG_INCREASING;
}
// Split "format[:byteorder]"
char byteorder[8+1] = "";
if (strchr(fmtname, ':')) {
if (priority == PRIOR_DEFAULT)
// TODO: Allow Byteorder in DEFAULT entry
return false;
n1 = n2 = -1;
if (!( sscanf(fmtname, "%*[^:]%n:%8[012345rvwz]%n", &n1, byteorder, &n2) >= 1
&& n2 == (int)strlen(fmtname)))
return false;
fmtname[n1] = 0;
if (strchr(byteorder, 'v'))
flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
if (strchr(byteorder, 'w'))
flags |= ATTRFLAG_NO_WORSTVAL;
}
// Find format name
for (i = 0; ; i++) {
if (i >= num_format_names)
return false; // Not found
if (!strcmp(fmtname, format_names[i].name))
break;
}
ata_attr_raw_format format = format_names[i].format;
// 64-bit formats use the normalized and worst value bytes.
if (!*byteorder && (format == RAWFMT_RAW64 || format == RAWFMT_HEX64))
flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
// ",HDD|SSD" suffix for DEFAULT settings
if (hddssd[0]) {
if (!strcmp(hddssd, "HDD"))
flags |= ATTRFLAG_HDD_ONLY;
else if (!strcmp(hddssd, "SSD"))
flags |= ATTRFLAG_SSD_ONLY;
else
return false;
}
if (!id) {
// "N,format" -> set format for all entries
for (i = 0; i < MAX_ATTRIBUTE_NUM; i++) {
if (defs[i].priority >= priority)
continue;
if (attrname[0])
defs[i].name = attrname;
defs[i].priority = priority;
defs[i].raw_format = format;
defs[i].flags = flags;
snprintf(defs[i].byteorder, sizeof(defs[i].byteorder), "%s", byteorder);
}
}
else if (defs[id].priority <= priority) {
// "id,format[,name]"
if (attrname[0])
defs[id].name = attrname;
defs[id].raw_format = format;
defs[id].priority = priority;
defs[id].flags = flags;
snprintf(defs[id].byteorder, sizeof(defs[id].byteorder), "%s", byteorder);
}
return true;
}
// Return a multiline string containing a list of valid arguments for
// parse_attribute_def(). The strings are preceded by tabs and followed
// (except for the last) by newlines.
std::string create_vendor_attribute_arg_list()
{
std::string s;
unsigned i;
for (i = 0; i < num_format_names; i++)
s += strprintf("%s\tN,%s[:012345rvwz][,ATTR_NAME]",
(i>0 ? "\n" : ""), format_names[i].name);
for (i = 0; i < num_old_vendor_opts; i++)
s += strprintf("\n\t%s", map_old_vendor_opts[i][0]);
return s;
}
// Parse firmwarebug def (-F option).
// Return false on error.
bool parse_firmwarebug_def(const char * opt, firmwarebug_defs & firmwarebugs)
{
if (!strcmp(opt, "none"))
firmwarebugs.set(BUG_NONE);
else if (!strcmp(opt, "nologdir"))
firmwarebugs.set(BUG_NOLOGDIR);
else if (!strcmp(opt, "samsung"))
firmwarebugs.set(BUG_SAMSUNG);
else if (!strcmp(opt, "samsung2"))
firmwarebugs.set(BUG_SAMSUNG2);
else if (!strcmp(opt, "samsung3"))
firmwarebugs.set(BUG_SAMSUNG3);
else if (!strcmp(opt, "xerrorlba"))
firmwarebugs.set(BUG_XERRORLBA);
else
return false;
return true;
}
// Return a string of valid argument words for parse_firmwarebug_def()
const char * get_valid_firmwarebug_args()
{
return "none, nologdir, samsung, samsung2, samsung3, xerrorlba";
}
// swap two bytes. Point to low address
void swap2(char *location){
char tmp=*location;
*location=*(location+1);
*(location+1)=tmp;
return;
}
// swap four bytes. Point to low address
void swap4(char *location){
char tmp=*location;
*location=*(location+3);
*(location+3)=tmp;
swap2(location+1);
return;
}
// swap eight bytes. Points to low address
void swap8(char *location){
char tmp=*location;
*location=*(location+7);
*(location+7)=tmp;
tmp=*(location+1);
*(location+1)=*(location+6);
*(location+6)=tmp;
swap4(location+2);
return;
}
// When using the overloaded swapx() function with member of packed ATA structs,
// it is required to pass a possibly unaligned pointer as argument.
// Clang++ 4.0 prints -Waddress-of-packed-member warning in this case.
// The SWAPV() macro below is a replacement which prevents the use of such pointers.
template <typename T>
static T get_swapx_val(T x)
{ swapx(&x); return x; }
#define SWAPV(x) ((x) = get_swapx_val(x))
// Invalidate serial number and WWN and adjust checksum in IDENTIFY data
static void invalidate_serno(ata_identify_device * id)
{
unsigned char sum = 0;
unsigned i;
for (i = 0; i < sizeof(id->serial_no); i++) {
sum += id->serial_no[i]; sum -= id->serial_no[i] = 'X';
}
unsigned char * b = (unsigned char *)id;
for (i = 2*108; i < 2*112; i++) { // words108-111: WWN
sum += b[i]; sum -= b[i] = 0x00;
}
if (isbigendian())
SWAPV(id->words088_255[255-88]);
if ((id->words088_255[255-88] & 0x00ff) == 0x00a5)
id->words088_255[255-88] += sum << 8;
if (isbigendian())
SWAPV(id->words088_255[255-88]);
}
static const char * const commandstrings[]={
"SMART ENABLE",
"SMART DISABLE",
"SMART AUTOMATIC ATTRIBUTE SAVE",
"SMART IMMEDIATE OFFLINE",
"SMART AUTO OFFLINE",
"SMART STATUS",
"SMART STATUS CHECK",
"SMART READ ATTRIBUTE VALUES",
"SMART READ ATTRIBUTE THRESHOLDS",
"SMART READ LOG",
"IDENTIFY DEVICE",
"IDENTIFY PACKET DEVICE",
"CHECK POWER MODE",
"SMART WRITE LOG",
"WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT ")\n"
};
static const char * preg(const ata_register & r, char (& buf)[8])
{
if (!r.is_set())
//return "n/a ";
return "....";
snprintf(buf, sizeof(buf), "0x%02x", r.val());
return buf;
}
static void print_regs(const char * prefix, const ata_in_regs & r, const char * suffix = "\n")
{
char bufs[7][8];
pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix,
preg(r.features, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]),
preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]),
preg(r.command, bufs[6]), suffix);
}
static void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix = "\n")
{
char bufs[7][8];
pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix,
preg(r.error, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]),
preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]),
preg(r.status, bufs[6]), suffix);
}
static void prettyprint(const unsigned char *p, const char *name){
pout("\n===== [%s] DATA START (BASE-16) =====\n", name);
for (int i=0; i<512; i+=16, p+=16)
#define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
// print complete line to avoid slow tty output and extra lines in syslog.
pout("%03d-%03d: %02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x"
" |%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c|"
"%c",
i, i+16-1,
p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15],
P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15),
'\n');
#undef P
pout("===== [%s] DATA END (512 Bytes) =====\n\n", name);
}
// This function provides the pretty-print reporting for SMART
// commands: it implements the various -r "reporting" options for ATA
// ioctls.
int smartcommandhandler(ata_device * device, smart_command_set command, int select, char *data){
// TODO: Rework old stuff below
// This conditional is true for commands that return data
int getsdata=(command==PIDENTIFY ||
command==IDENTIFY ||
command==READ_LOG ||
command==READ_THRESHOLDS ||
command==READ_VALUES ||
command==CHECK_POWER_MODE);
int sendsdata=(command==WRITE_LOG);
// If reporting is enabled, say what the command will be before it's executed
if (ata_debugmode) {
// conditional is true for commands that use parameters
int usesparam=(command==READ_LOG ||
command==AUTO_OFFLINE ||
command==AUTOSAVE ||
command==IMMEDIATE_OFFLINE ||
command==WRITE_LOG);
pout("\nREPORT-IOCTL: Device=%s Command=%s", device->get_dev_name(), commandstrings[command]);
if (usesparam)
pout(" InputParameter=%d\n", select);
else
pout("\n");
}
if ((getsdata || sendsdata) && !data){
pout("REPORT-IOCTL: Unable to execute command %s : data destination address is NULL\n", commandstrings[command]);
return -1;
}
// The reporting is cleaner, and we will find coding bugs faster, if
// the commands that failed clearly return empty (zeroed) data
// structures
if (getsdata) {
if (command==CHECK_POWER_MODE)
data[0]=0;
else
memset(data, '\0', 512);
}
// if requested, pretty-print the input data structure
if (ata_debugmode > 1 && sendsdata)
//pout("REPORT-IOCTL: Device=%s Command=%s\n", device->get_dev_name(), commandstrings[command]);
prettyprint((unsigned char *)data, commandstrings[command]);
// now execute the command
int retval = -1;
{
ata_cmd_in in;
// Set common register values
switch (command) {
default: // SMART commands
in.in_regs.command = ATA_SMART_CMD;
in.in_regs.lba_high = SMART_CYL_HI; in.in_regs.lba_mid = SMART_CYL_LOW;
break;
case IDENTIFY: case PIDENTIFY: case CHECK_POWER_MODE: // Non SMART commands
break;
}
// Set specific values
switch (command) {
case IDENTIFY:
in.in_regs.command = ATA_IDENTIFY_DEVICE;
in.set_data_in(data, 1);
break;
case PIDENTIFY:
in.in_regs.command = ATA_IDENTIFY_PACKET_DEVICE;
in.set_data_in(data, 1);
break;
case CHECK_POWER_MODE:
in.in_regs.command = ATA_CHECK_POWER_MODE;
in.out_needed.sector_count = true; // Powermode returned here
break;
case READ_VALUES:
in.in_regs.features = ATA_SMART_READ_VALUES;
in.set_data_in(data, 1);
break;
case READ_THRESHOLDS:
in.in_regs.features = ATA_SMART_READ_THRESHOLDS;
in.in_regs.lba_low = 1; // TODO: CORRECT ???
in.set_data_in(data, 1);
break;
case READ_LOG:
in.in_regs.features = ATA_SMART_READ_LOG_SECTOR;
in.in_regs.lba_low = select;
in.set_data_in(data, 1);
break;
case WRITE_LOG:
in.in_regs.features = ATA_SMART_WRITE_LOG_SECTOR;
in.in_regs.lba_low = select;
in.set_data_out(data, 1);
break;
case ENABLE:
in.in_regs.features = ATA_SMART_ENABLE;
in.in_regs.lba_low = 1; // TODO: CORRECT ???
break;
case DISABLE:
in.in_regs.features = ATA_SMART_DISABLE;
in.in_regs.lba_low = 1; // TODO: CORRECT ???
break;
case STATUS_CHECK:
in.out_needed.lba_high = in.out_needed.lba_mid = true; // Status returned here
/* FALLTHRU */
case STATUS:
in.in_regs.features = ATA_SMART_STATUS;
break;
case AUTO_OFFLINE:
in.in_regs.features = ATA_SMART_AUTO_OFFLINE;
in.in_regs.sector_count = select; // Caution: Non-DATA command!
break;
case AUTOSAVE:
in.in_regs.features = ATA_SMART_AUTOSAVE;
in.in_regs.sector_count = select; // Caution: Non-DATA command!
break;
case IMMEDIATE_OFFLINE:
in.in_regs.features = ATA_SMART_IMMEDIATE_OFFLINE;
in.in_regs.lba_low = select;
break;
default:
pout("Unrecognized command %d in smartcommandhandler()\n"
"Please contact " PACKAGE_BUGREPORT "\n", command);
device->set_err(ENOSYS);
return -1;
}
if (ata_debugmode)
print_regs(" Input: ", in.in_regs,
(in.direction==ata_cmd_in::data_in ? " IN\n":
in.direction==ata_cmd_in::data_out ? " OUT\n":"\n"));
ata_cmd_out out;
auto start_usec = (ata_debugmode ? get_timer_usec() : -1);
bool ok = device->ata_pass_through(in, out);
if (start_usec >= 0) {
auto duration_usec = get_timer_usec() - start_usec;
if (duration_usec > 0)
pout(" [Duration: %.6fs]\n", duration_usec / 1000000.0);
}
if (ata_debugmode && out.out_regs.is_set())
print_regs(" Output: ", out.out_regs);
if (ok) switch (command) {
default:
retval = 0;
break;
case CHECK_POWER_MODE:
if (out.out_regs.sector_count.is_set()) {
data[0] = out.out_regs.sector_count;
retval = 0;
}
else {
pout("CHECK POWER MODE: incomplete response, ATA output registers missing\n");
device->set_err(ENOSYS);
retval = -1;
}
break;
case STATUS_CHECK:
// Cyl low and Cyl high unchanged means "Good SMART status"
if ((out.out_regs.lba_high == SMART_CYL_HI) &&
(out.out_regs.lba_mid == SMART_CYL_LOW))
retval = 0;
// These values mean "Bad SMART status"
else if ((out.out_regs.lba_high == SRET_STATUS_HI_EXCEEDED) &&
(out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED))
retval = 1;
else if (out.out_regs.lba_mid == SMART_CYL_LOW) {
retval = 0;
if (ata_debugmode)
pout("SMART STATUS RETURN: half healthy response sequence, "
"probable SAT/USB truncation\n");
} else if (out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED) {
retval = 1;
if (ata_debugmode)
pout("SMART STATUS RETURN: half unhealthy response sequence, "
"probable SAT/USB truncation\n");
}
else if (!out.out_regs.is_set()) {
device->set_err(ENOSYS, "Incomplete response, ATA output registers missing");
retval = -1;
}
else {
// We haven't gotten output that makes sense; print out some debugging info
pout("SMART Status command failed\n");
pout("Please get assistance from %s\n", PACKAGE_URL);
pout("Register values returned from SMART Status command are:\n");
print_regs(" ", out.out_regs);
device->set_err(ENOSYS, "Invalid ATA output register values");
retval = -1;
}
break;
}
}
// If requested, invalidate serial number before any printing is done
if ((command == IDENTIFY || command == PIDENTIFY) && !retval && dont_print_serial_number)
invalidate_serno( reinterpret_cast<ata_identify_device *>(data) );
// If reporting is enabled, say what output was produced by the command
if (ata_debugmode) {
if (retval && device->get_errno())
pout("REPORT-IOCTL: Device=%s Command=%s returned %d errno=%d [%s]\n",
device->get_dev_name(), commandstrings[command], retval,
device->get_errno(), device->get_errmsg());
else
pout("REPORT-IOCTL: Device=%s Command=%s returned %d\n",
device->get_dev_name(), commandstrings[command], retval);
// if requested, pretty-print the output data structure
if (ata_debugmode > 1 && getsdata) {
if (command==CHECK_POWER_MODE)
pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data));
else
prettyprint((unsigned char *)data, commandstrings[command]);
}
}
return retval;
}
// Get capacity and sector sizes from IDENTIFY data
void ata_get_size_info(const ata_identify_device * id, ata_size_info & sizes)
{
sizes.sectors = sizes.capacity = 0;
sizes.log_sector_size = sizes.phy_sector_size = 0;
sizes.log_sector_offset = 0;
// Return if no LBA support
if (!(id->words047_079[49-47] & 0x0200))
return;
// Determine 28-bit LBA capacity
unsigned lba28 = (unsigned)id->words047_079[61-47] << 16
| (unsigned)id->words047_079[60-47] ;
// Determine 48-bit LBA capacity if supported
uint64_t lba48 = 0;
if ((id->command_set_2 & 0xc400) == 0x4400)
lba48 = (uint64_t)id->words088_255[103-88] << 48
| (uint64_t)id->words088_255[102-88] << 32
| (uint64_t)id->words088_255[101-88] << 16
| (uint64_t)id->words088_255[100-88] ;
// Return if capacity unknown (ATAPI CD/DVD)
if (!(lba28 || lba48))
return;
// Determine sector sizes
sizes.log_sector_size = sizes.phy_sector_size = 512;
unsigned short word106 = id->words088_255[106-88];
if ((word106 & 0xc000) == 0x4000) {
// Long Logical/Physical Sectors (LLS/LPS) ?
if (word106 & 0x1000)
// Logical sector size is specified in 16-bit words
sizes.log_sector_size = sizes.phy_sector_size =
((id->words088_255[118-88] << 16) | id->words088_255[117-88]) << 1;
if (word106 & 0x2000)
// Physical sector size is multiple of logical sector size
sizes.phy_sector_size <<= (word106 & 0x0f);
unsigned short word209 = id->words088_255[209-88];
if ((word209 & 0xc000) == 0x4000)
sizes.log_sector_offset = (word209 & 0x3fff) * sizes.log_sector_size;
}
// Some early 4KiB LLS disks (Samsung N3U-3) return bogus lba28 value
if (lba48 >= lba28 || (lba48 && sizes.log_sector_size > 512))
sizes.sectors = lba48;
else
sizes.sectors = lba28;
sizes.capacity = sizes.sectors * sizes.log_sector_size;
}
// This function computes the checksum of a single disk sector (512
// bytes). Returns zero if checksum is OK, nonzero if the checksum is
// incorrect. The size (512) is correct for all SMART structures.
unsigned char checksum(const void * data)
{
unsigned char sum = 0;
for (int i = 0; i < 512; i++)
sum += ((const unsigned char *)data)[i];
return sum;
}
// Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
// bytes.
static void swapbytes(char * out, const char * in, size_t n)
{
for (size_t i = 0; i < n; i += 2) {
out[i] = in[i+1];
out[i+1] = in[i];
}
}
// Copies in to out, but removes leading and trailing whitespace.
static void trim(char * out, const char * in)
{
// Find the first non-space character (maybe none).
int first = -1;
int i;
for (i = 0; in[i]; i++)
if (!isspace((int)in[i])) {
first = i;
break;
}
if (first == -1) {
// There are no non-space characters.
out[0] = '\0';
return;
}
// Find the last non-space character.
for (i = strlen(in)-1; i >= first && isspace((int)in[i]); i--)
;
int last = i;
strncpy(out, in+first, last-first+1);
out[last-first+1] = '\0';
}
// Convenience function for formatting strings from ata_identify_device
void ata_format_id_string(char * out, const unsigned char * in, int n)
{
char tmp[65];
n = n > 64 ? 64 : n;
swapbytes(tmp, (const char *)in, n);
tmp[n] = '\0';
trim(out, tmp);
}
// returns -1 if command fails or the device is in Sleep mode, else
// value of Sector Count register. Sector Count result values:
// 00h device is in Standby mode.
// 80h device is in Idle mode.
// FFh device is in Active mode or Idle mode.
int ataCheckPowerMode(ata_device * device) {
unsigned char result;
if ((smartcommandhandler(device, CHECK_POWER_MODE, 0, (char *)&result)))
return -1;
return (int)result;
}
// Issue a no-data ATA command with optional sector count register value
bool ata_nodata_command(ata_device * device, unsigned char command,
int sector_count /* = -1 */)
{
ata_cmd_in in;
in.in_regs.command = command;
if (sector_count >= 0)
in.in_regs.sector_count = sector_count;
return device->ata_pass_through(in);
}
// Issue SET FEATURES command with optional sector count register value
bool ata_set_features(ata_device * device, unsigned char features,
int sector_count /* = -1 */)
{
ata_cmd_in in;
in.in_regs.command = ATA_SET_FEATURES;
in.in_regs.features = features;
if (sector_count >= 0)
in.in_regs.sector_count = sector_count;
return device->ata_pass_through(in);
}
// Reads current Device Identity info (512 bytes) into buf. Returns 0
// if all OK. Returns -1 if no ATA Device identity can be
// established. Returns >0 if Device is ATA Packet Device (not SMART
// capable). The value of the integer helps identify the type of
// Packet device, which is useful so that the user can connect the
// formal device number with whatever object is inside their computer.
int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_swapped_id,
unsigned char * raw_buf /* = 0 */)
{
// See if device responds either to IDENTIFY DEVICE or IDENTIFY
// PACKET DEVICE
bool packet = false;
if ((smartcommandhandler(device, IDENTIFY, 0, (char *)buf))){
smart_device::error_info err = device->get_err();
if (smartcommandhandler(device, PIDENTIFY, 0, (char *)buf)){
device->set_err(err);
return -1;
}
packet = true;
}
if (fix_swapped_id) {
// Swap ID strings
unsigned i;
for (i = 0; i < sizeof(buf->serial_no)-1; i += 2)
swap2((char *)(buf->serial_no+i));
for (i = 0; i < sizeof(buf->fw_rev)-1; i += 2)
swap2((char *)(buf->fw_rev+i));
for (i = 0; i < sizeof(buf->model)-1; i += 2)
swap2((char *)(buf->model+i));
}
// If requested, save raw data before endianness adjustments
if (raw_buf)
memcpy(raw_buf, buf, sizeof(*buf));
// If there is a checksum there, validate it
unsigned char * rawbyte = (unsigned char *)buf;
if (rawbyte[512-2] == 0xa5 && checksum(rawbyte))
checksumwarning("Drive Identity Structure");
// if machine is big-endian, swap byte order as needed
if (isbigendian()){
// swap various capability words that are needed
unsigned i;
for (i=0; i<33; i++)
swap2((char *)(buf->words047_079+i));
for (i=80; i<=87; i++)
swap2((char *)(rawbyte+2*i));
for (i=0; i<168; i++)
swap2((char *)(buf->words088_255+i));
}
// AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
// T13/1699-D Revision 6a (Final Draft), September 6, 2008.
// Sections 7.16.7 and 7.17.6:
//
// Word 0 of IDENTIFY DEVICE data:
// Bit 15 = 0 : ATA device
//
// Word 0 of IDENTIFY PACKET DEVICE data:
// Bits 15:14 = 10b : ATAPI device
// Bits 15:14 = 11b : Reserved
// Bits 12:8 : Device type (SPC-4, e.g 0x05 = CD/DVD)
// CF+ and CompactFlash Specification Revision 4.0, May 24, 2006.
// Section 6.2.1.6:
//
// Word 0 of IDENTIFY DEVICE data:
// 848Ah = Signature for CompactFlash Storage Card
// 044Ah = Alternate value turns on ATA device while preserving all retired bits
// 0040h = Alternate value turns on ATA device while zeroing all retired bits
// Assume ATA if IDENTIFY DEVICE returns CompactFlash Signature
if (!packet && rawbyte[1] == 0x84 && rawbyte[0] == 0x8a)
return 0;
// If this is a PACKET DEVICE, return device type
if (rawbyte[1] & 0x80)
return 1+(rawbyte[1] & 0x1f);
// Not a PACKET DEVICE
return 0;
}
// Get World Wide Name (WWN) fields.
// Return NAA field or -1 if WWN is unsupported.
// Table 34 of T13/1699-D Revision 6a (ATA8-ACS), September 6, 2008.
// (WWN was introduced in ATA/ATAPI-7 and is mandatory since ATA8-ACS Revision 3b)
int ata_get_wwn(const ata_identify_device * id, unsigned & oui, uint64_t & unique_id)
{
// Don't use word 84 to be compatible with some older ATA-7 disks
unsigned short word087 = id->csf_default;
if ((word087 & 0xc100) != 0x4100)
return -1; // word not valid or WWN support bit 8 not set
unsigned short word108 = id->words088_255[108-88];
unsigned short word109 = id->words088_255[109-88];
unsigned short word110 = id->words088_255[110-88];
unsigned short word111 = id->words088_255[111-88];
oui = ((word108 & 0x0fff) << 12) | (word109 >> 4);
unique_id = ((uint64_t)(word109 & 0xf) << 32)
| (unsigned)((word110 << 16) | word111);
return (word108 >> 12);
}
// Get nominal media rotation rate.
// Returns: 0 = not reported, 1 = SSD, >1 = HDD rpm, < 0 = -(Unknown value)
int ata_get_rotation_rate(const ata_identify_device * id)
{
// Table 37 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
// Table A.31 of T13/2161-D (ACS-3) Revision 3b, August 25, 2012
unsigned short word217 = id->words088_255[217-88];
if (word217 == 0x0000 || word217 == 0xffff)
return 0;
else if (word217 == 0x0001)
return 1;
else if (word217 > 0x0400)
return word217;
else
return -(int)word217;
}
// returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
int ataSmartSupport(const ata_identify_device * drive)
{
unsigned short word82=drive->command_set_1;
unsigned short word83=drive->command_set_2;
// check if words 82/83 contain valid info
if ((word83>>14) == 0x01)
// return value of SMART support bit
return word82 & 0x0001;
// since we can're rely on word 82, we don't know if SMART supported
return -1;
}
// returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
int ataIsSmartEnabled(const ata_identify_device * drive)
{
unsigned short word85=drive->cfs_enable_1;
unsigned short word87=drive->csf_default;
// check if words 85/86/87 contain valid info
if ((word87>>14) == 0x01)
// return value of SMART enabled bit
return word85 & 0x0001;
// Since we can't rely word85, we don't know if SMART is enabled.
return -1;
}
// Reads SMART attributes into *data
int ataReadSmartValues(ata_device * device, struct ata_smart_values *data){
if (smartcommandhandler(device, READ_VALUES, 0, (char *)data)){
return -1;
}
// compute checksum
if (checksum(data))
checksumwarning("SMART Attribute Data Structure");
// swap endian order if needed
if (isbigendian()){
int i;
swap2((char *)&(data->revnumber));
swap2((char *)&(data->total_time_to_complete_off_line));
swap2((char *)&(data->smart_capability));
SWAPV(data->extend_test_completion_time_w);
for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
struct ata_smart_attribute *x=data->vendor_attributes+i;
swap2((char *)&(x->flags));
}
}
return 0;
}
// This corrects some quantities that are byte reversed in the SMART
// SELF TEST LOG
static void fixsamsungselftestlog(ata_smart_selftestlog * data)
{
// bytes 508/509 (numbered from 0) swapped (swap of self-test index
// with one byte of reserved.
swap2((char *)&(data->mostrecenttest));