[go: up one dir, main page]

File: os_linux.c

package info (click to toggle)
smartmontools 5.36-8
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,384 kB
  • ctags: 2,683
  • sloc: ansic: 26,592; sh: 4,636; asm: 576; makefile: 423
file content (1527 lines) | stat: -rw-r--r-- 54,178 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
/* 
 *  os_linux.c
 * 
 * Home page of code is: http://smartmontools.sourceforge.net
 *
 * Copyright (C) 2003-6 Bruce Allen <smartmontools-support@lists.sourceforge.net>
 * Copyright (C) 2003-6 Doug Gilbert <dougg@torque.net>
 *
 *  Parts of this file are derived from code that was
 *
 *  Written By: Adam Radford <linux@3ware.com>
 *  Modifications By: Joel Jacobson <linux@3ware.com>
 *                   Arnaldo Carvalho de Melo <acme@conectiva.com.br>
 *                    Brad Strand <linux@3ware.com>
 *
 *  Copyright (C) 1999-2003 3ware Inc.
 *
 *  Kernel compatablity By:     Andre Hedrick <andre@suse.com>
 *  Non-Copyright (C) 2000      Andre Hedrick <andre@suse.com>
 *
 * Other ars of this file are derived from code that was
 * 
 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * You should have received a copy of the GNU General Public License
 * (for example COPYING); if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * This code was originally developed as a Senior Thesis by Michael Cornwell
 * at the Concurrent Systems Laboratory (now part of the Storage Systems
 * Research Center), Jack Baskin School of Engineering, University of
 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
 * 
 */

// This file contains the linux-specific IOCTL parts of
// smartmontools. It includes one interface routine for ATA devices,
// one for SCSI devices, and one for ATA devices behind escalade
// controllers.

#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/sg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#ifndef makedev // old versions of types.h do not include sysmacros.h
#include <sys/sysmacros.h>
#endif

#include "config.h"
#include "int64.h"
#include "atacmds.h"
#include "os_linux.h"
#include "scsicmds.h"
#include "utility.h"

#ifndef ENOTSUP
#define ENOTSUP ENOSYS
#endif
typedef unsigned long long u8;

#define ARGUSED(x) ((void)(x))

static const char *filenameandversion="$Id: os_linux.c,v 1.82 2006/04/12 16:28:56 ballen4705 Exp $";

const char *os_XXXX_c_cvsid="$Id: os_linux.c,v 1.82 2006/04/12 16:28:56 ballen4705 Exp $" \
ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_LINUX_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID;

// to hold onto exit code for atexit routine
extern int exitstatus;

// global variable holding byte count of allocated memory
extern long long bytes;



/* This function will setup and fix device nodes for a 3ware controller. */
#define MAJOR_STRING_LENGTH 3
#define DEVICE_STRING_LENGTH 32
#define NODE_STRING_LENGTH 16
int setup_3ware_nodes(char *nodename, char *driver_name) {
  int              tw_major      = 0;
  int              index         = 0;
  char             majorstring[MAJOR_STRING_LENGTH+1];
  char             device_name[DEVICE_STRING_LENGTH+1];
  char             nodestring[NODE_STRING_LENGTH];
  struct stat      stat_buf;
  FILE             *file;
  
  /* First try to open up /proc/devices */
  if (!(file = fopen("/proc/devices", "r"))) {
    pout("Error opening /proc/devices to check/create 3ware device nodes\n");
    syserror("fopen");
    return 0;  // don't fail here: user might not have /proc !
  }
  
  /* Attempt to get device major number */
  while (EOF != fscanf(file, "%3s %32s", majorstring, device_name)) {
    majorstring[MAJOR_STRING_LENGTH]='\0';
    device_name[DEVICE_STRING_LENGTH]='\0';
    if (!strncmp(device_name, nodename, DEVICE_STRING_LENGTH)) {
      tw_major = atoi(majorstring);
      break;
    }
  }
  fclose(file);
  
  /* See if we found a major device number */
  if (!tw_major) {
    pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename, driver_name);
    return 2;
  }
  
  /* Now check if nodes are correct */
  for (index=0; index<16; index++) {
    sprintf(nodestring, "/dev/%s%d", nodename, index);
	  
    /* Try to stat the node */
    if ((stat(nodestring, &stat_buf))) {
      /* Create a new node if it doesn't exist */
      if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
	pout("problem creating 3ware device nodes %s", nodestring);
	syserror("mknod");
	return 3;
      }
    }
    
    /* See if nodes major and minor numbers are correct */
    if ((tw_major != (int)(major(stat_buf.st_rdev))) ||
	(index    != (int)(minor(stat_buf.st_rdev))) ||
	(!S_ISCHR(stat_buf.st_mode))) {
      
      /* Delete the old node */
      if (unlink(nodestring)) {
	pout("problem unlinking stale 3ware device node %s", nodestring);
	syserror("unlink");
	return 4;
      }
      
      /* Make a new node */
      if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
	pout("problem creating 3ware device nodes %s", nodestring);
	syserror("mknod");
	return 5;
      }
    }
  }
  return 0;
}

// equivalent to open(path, flags)
int deviceopen(const char *pathname, char *type){
  if (!strcmp(type,"SCSI")) {
    int fd = open(pathname, O_RDWR | O_NONBLOCK);
    if (fd < 0 && errno == EROFS)
      fd = open(pathname, O_RDONLY | O_NONBLOCK);
    return fd;
  }
  else if (!strcmp(type,"ATA")) 
    return open(pathname, O_RDONLY | O_NONBLOCK);
  else if (!strcmp(type,"ATA_3WARE_9000")) {
    // the device nodes for this controller are dynamically assigned,
    // so we need to check that they exist with the correct major
    // numbers and if not, create them
    if (setup_3ware_nodes("twa", "3w-9xxx")) {
      if (!errno)
	errno=ENXIO;
      return -1;
    }
    return open(pathname, O_RDONLY | O_NONBLOCK);
  }
  else if (!strcmp(type,"ATA_3WARE_678K")) {
    // the device nodes for this controller are dynamically assigned,
    // so we need to check that they exist with the correct major
    // numbers and if not, create them
    if (setup_3ware_nodes("twe", "3w-xxxx")) {
      if (!errno)
	errno=ENXIO;
      return -1;
    }
    return open(pathname, O_RDONLY | O_NONBLOCK);
  }
  else
    return -1;
}

// equivalent to close(file descriptor)
int deviceclose(int fd){
  return close(fd);
}

// print examples for smartctl
void print_smartctl_examples(){
  printf("=================================================== SMARTCTL EXAMPLES =====\n\n");
#ifdef HAVE_GETOPT_LONG
  printf(
         "  smartctl --all /dev/hda                    (Prints all SMART information)\n\n"
         "  smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
         "                                              (Enables SMART on first disk)\n\n"
         "  smartctl --test=long /dev/hda          (Executes extended disk self-test)\n\n"
         "  smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
         "                                      (Prints Self-Test & Attribute errors)\n"
         "  smartctl --all --device=3ware,2 /dev/sda\n"
         "  smartctl --all --device=3ware,2 /dev/twe0\n"
         "  smartctl --all --device=3ware,2 /dev/twa0\n"
         "          (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
         );
#else
  printf(
         "  smartctl -a /dev/hda                       (Prints all SMART information)\n"
         "  smartctl -s on -o on -S on /dev/hda         (Enables SMART on first disk)\n"
         "  smartctl -t long /dev/hda              (Executes extended disk self-test)\n"
         "  smartctl -A -l selftest -q errorsonly /dev/hda\n"
         "                                      (Prints Self-Test & Attribute errors)\n"
         "  smartctl -a -d 3ware,2 /dev/sda\n"
         "  smartctl -a -d 3ware,2 /dev/twa0\n"
         "  smartctl -a -d 3ware,2 /dev/twe0\n"
         "          (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
         );
#endif
  return;
}


// we are going to take advantage of the fact that Linux's devfs will only
// have device entries for devices that exist.  So if we get the equivalent of
// ls /dev/hd[a-t], we have all the ATA devices on the system
//
// If any errors occur, leave errno set as it was returned by the
// system call, and return <0.
int get_dev_names(char*** names, const char* pattern, const char* name, int max) {
  int n = 0, retglob, i, lim;
  char** mp;
  glob_t globbuf;
  
  memset(&globbuf, 0, sizeof(globbuf));

  // in case of non-clean exit
  *names=NULL;
  
  // Use glob to look for any directory entries matching the pattern
  if ((retglob=glob(pattern, GLOB_ERR, NULL, &globbuf))) {
    
    //  glob failed: free memory and return
    globfree(&globbuf);
    
    if (retglob==GLOB_NOMATCH){
      pout("glob(3) found no matches for pattern %s\n", pattern);
      return 0;
    }
    
    if (retglob==GLOB_NOSPACE)
      pout("glob(3) ran out of memory matching pattern %s\n", pattern);
#ifdef GLOB_ABORTED // missing in old versions of glob.h
    else if (retglob==GLOB_ABORTED)
      pout("glob(3) aborted matching pattern %s\n", pattern);
#endif
    else
      pout("Unexplained error in glob(3) of pattern %s\n", pattern);
    
    return -1;
  }

  // did we find too many paths?
  lim = ((int)globbuf.gl_pathc < max) ? (int)globbuf.gl_pathc : max;
  if (lim < (int)globbuf.gl_pathc)
    pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n", 
         (int)globbuf.gl_pathc, max, pattern, (int)(globbuf.gl_pathc-max));
  
  // allocate space for up to lim number of ATA devices
  if (!(mp =  (char **)calloc(lim, sizeof(char*)))){
    pout("Out of memory constructing scan device list\n");
    return -1;
  }
  
  // now step through the list returned by glob.  If not a link, copy
  // to list.  If it is a link, evaluate it and see if the path ends
  // in "disc".
  for (i=0; i<lim; i++){
    int retlink;
    
    // prepare a buffer for storing the link
    char linkbuf[1024];
    
    // see if path is a link
    retlink=readlink(globbuf.gl_pathv[i], linkbuf, 1023);
    
    // if not a link (or a strange link), keep it
    if (retlink<=0 || retlink>1023)
      mp[n++] = CustomStrDup(globbuf.gl_pathv[i], 1, __LINE__, filenameandversion);
    else {
      // or if it's a link that points to a disc, follow it
      char *p;
      linkbuf[retlink]='\0';
      if ((p=strrchr(linkbuf,'/')) && !strcmp(p+1, "disc"))
        // This is the branch of the code that gets followed if we are
        // using devfs WITH traditional compatibility links. In this
        // case, we add the traditional device name to the list that
        // is returned.
        mp[n++] = CustomStrDup(globbuf.gl_pathv[i], 1, __LINE__, filenameandversion);
      else {
        // This is the branch of the code that gets followed if we are
        // using devfs WITHOUT traditional compatibility links.  In
        // this case, we check that the link to the directory is of
        // the correct type, and then append "disc" to it.
        char tmpname[1024]={0};
        char *type=strcmp(name,"ATA")?"scsi":"ide";
        if (strstr(linkbuf, type)){
          snprintf(tmpname, 1024, "%s/disc", globbuf.gl_pathv[i]);
          mp[n++] = CustomStrDup(tmpname, 1, __LINE__, filenameandversion);
        }
      }
    }
  }
  
  // free memory, track memory usage
  globfree(&globbuf);
  mp = realloc(mp,n*(sizeof(char*)));
  bytes += n*(sizeof(char*));
  
  // and set up return values
  *names=mp;
  return n;
}

// makes a list of device names to scan, for either ATA or SCSI
// devices.  Return -1 if no memory remaining, else the number of
// devices on the list, which can be >=0.
int make_device_names (char*** devlist, const char* name) {
  int retval, maxdev;
  
#if 0
  // for testing case where no device names are found
  return 0;
#endif
  
  if (!strcmp(name,"SCSI"))
    retval=get_dev_names(devlist,"/dev/sd[a-z]", name, maxdev=26);
  else if (!strcmp(name,"ATA"))
    retval=get_dev_names(devlist,"/dev/hd[a-t]", name, maxdev=20);
  else
    // don't recognize disk type!
    return 0;

  // if we found traditional links, we are done
  if (retval>0)
    return retval;
  
  // else look for devfs entries without traditional links
  return get_dev_names(devlist,"/dev/discs/disc*", name, maxdev);
}


// PURPOSE
//   This is an interface routine meant to isolate the OS dependent
//   parts of the code, and to provide a debugging interface.  Each
//   different port and OS needs to provide it's own interface.  This
//   is the linux one.
// DETAILED DESCRIPTION OF ARGUMENTS
//   device: is the file descriptor provided by open()
//   command: defines the different operations.
//   select: additional input data if needed (which log, which type of
//           self-test).
//   data:   location to write output data, if needed (512 bytes).
//   Note: not all commands use all arguments.
// RETURN VALUES
//  -1 if the command failed
//   0 if the command succeeded,
//   STATUS_CHECK routine: 
//  -1 if the command failed
//   0 if the command succeeded and disk SMART status is "OK"
//   1 if the command succeeded and disk SMART status is "FAILING"


// huge value of buffer size needed because HDIO_DRIVE_CMD assumes
// that buff[3] is the data size.  Since the ATA_SMART_AUTOSAVE and
// ATA_SMART_AUTO_OFFLINE use values of 0xf1 and 0xf8 we need the space.
// Otherwise a 4+512 byte buffer would be enough.
#define STRANGE_BUFFER_LENGTH (4+512*0xf8)

int ata_command_interface(int device, smart_command_set command, int select, char *data){
  unsigned char buff[STRANGE_BUFFER_LENGTH];
  // positive: bytes to write to caller.  negative: bytes to READ from
  // caller. zero: non-data command
  int copydata=0;

  const int HDIO_DRIVE_CMD_OFFSET = 4;

  // See struct hd_drive_cmd_hdr in hdreg.h.  Before calling ioctl()
  // buff[0]: ATA COMMAND CODE REGISTER
  // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
  // buff[2]: ATA FEATURES REGISTER
  // buff[3]: ATA SECTOR COUNT REGISTER

  // Note that on return:
  // buff[2] contains the ATA SECTOR COUNT REGISTER
  
  // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
  memset(buff, 0, STRANGE_BUFFER_LENGTH);

  buff[0]=ATA_SMART_CMD;
  switch (command){
  case CHECK_POWER_MODE:
    buff[0]=ATA_CHECK_POWER_MODE;
    copydata=1;
    break;
  case READ_VALUES:
    buff[2]=ATA_SMART_READ_VALUES;
    buff[3]=1;
    copydata=512;
    break;
  case READ_THRESHOLDS:
    buff[2]=ATA_SMART_READ_THRESHOLDS;
    buff[1]=buff[3]=1;
    copydata=512;
    break;
  case READ_LOG:
    buff[2]=ATA_SMART_READ_LOG_SECTOR;
    buff[1]=select;
    buff[3]=1;
    copydata=512;
    break;
  case WRITE_LOG:
    break;
  case IDENTIFY:
    buff[0]=ATA_IDENTIFY_DEVICE;
    buff[3]=1;
    copydata=512;
    break;
  case PIDENTIFY:
    buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
    buff[3]=1;
    copydata=512;
    break;
  case ENABLE:
    buff[2]=ATA_SMART_ENABLE;
    buff[1]=1;
    break;
  case DISABLE:
    buff[2]=ATA_SMART_DISABLE;
    buff[1]=1;
    break;
  case STATUS:
    // this command only says if SMART is working.  It could be
    // replaced with STATUS_CHECK below.
    buff[2]=ATA_SMART_STATUS;
    break;
  case AUTO_OFFLINE:
    buff[2]=ATA_SMART_AUTO_OFFLINE;
    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
    break;
  case AUTOSAVE:
    buff[2]=ATA_SMART_AUTOSAVE;
    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
    break;
  case IMMEDIATE_OFFLINE:
    buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
    buff[1]=select;
    break;
  case STATUS_CHECK:
    // This command uses HDIO_DRIVE_TASK and has different syntax than
    // the other commands.
    buff[1]=ATA_SMART_STATUS;
    break;
  default:
    pout("Unrecognized command %d in linux_ata_command_interface()\n"
         "Please contact " PACKAGE_BUGREPORT "\n", command);
    errno=ENOSYS;
    return -1;
  }
  
  // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
  // only ioctl() that can be used to WRITE data to the disk.
  if (command==WRITE_LOG) {    
    unsigned char task[sizeof(ide_task_request_t)+512];
    ide_task_request_t *reqtask=(ide_task_request_t *) task;
    task_struct_t      *taskfile=(task_struct_t *) reqtask->io_ports;
    int retval;

    memset(task,      0, sizeof(task));
    
    taskfile->data           = 0;
    taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
    taskfile->sector_count   = 1;
    taskfile->sector_number  = select;
    taskfile->low_cylinder   = 0x4f;
    taskfile->high_cylinder  = 0xc2;
    taskfile->device_head    = 0;
    taskfile->command        = ATA_SMART_CMD;
    
    reqtask->data_phase      = TASKFILE_OUT;
    reqtask->req_cmd         = IDE_DRIVE_TASK_OUT;
    reqtask->out_size        = 512;
    reqtask->in_size         = 0;
    
    // copy user data into the task request structure
    memcpy(task+sizeof(ide_task_request_t), data, 512);
      
    if ((retval=ioctl(device, HDIO_DRIVE_TASKFILE, task))) {
      if (retval==-EINVAL)
	pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
      return -1;
    }
    return 0;
  }
    
  // There are two different types of ioctls().  The HDIO_DRIVE_TASK
  // one is this:
  if (command==STATUS_CHECK){
    int retval;

    // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
    // have to read the IDE driver source code.  Sigh.
    // buff[0]: ATA COMMAND CODE REGISTER
    // buff[1]: ATA FEATURES REGISTER
    // buff[2]: ATA SECTOR_COUNT
    // buff[3]: ATA SECTOR NUMBER
    // buff[4]: ATA CYL LO REGISTER
    // buff[5]: ATA CYL HI REGISTER
    // buff[6]: ATA DEVICE HEAD

    unsigned const char normal_lo=0x4f, normal_hi=0xc2;
    unsigned const char failed_lo=0xf4, failed_hi=0x2c;
    buff[4]=normal_lo;
    buff[5]=normal_hi;
    
    if ((retval=ioctl(device, HDIO_DRIVE_TASK, buff))) {
      if (retval==-EINVAL) {
	pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
	pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
      }
      else
	syserror("Error SMART Status command failed");
      return -1;
    }
    
    // Cyl low and Cyl high unchanged means "Good SMART status"
    if (buff[4]==normal_lo && buff[5]==normal_hi)
      return 0;
    
    // These values mean "Bad SMART status"
    if (buff[4]==failed_lo && buff[5]==failed_hi)
      return 1;
    
    // We haven't gotten output that makes sense; print out some debugging info
    syserror("Error SMART Status command failed");
    pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
    pout("Register values returned from SMART Status command are:\n");
    pout("CMD=0x%02x\n",(int)buff[0]);
    pout("FR =0x%02x\n",(int)buff[1]);
    pout("NS =0x%02x\n",(int)buff[2]);
    pout("SC =0x%02x\n",(int)buff[3]);
    pout("CL =0x%02x\n",(int)buff[4]);
    pout("CH =0x%02x\n",(int)buff[5]);
    pout("SEL=0x%02x\n",(int)buff[6]);
    return -1;   
  }
  
#if 1
  // Note to people doing ports to other OSes -- don't worry about
  // this block -- you can safely ignore it.  I have put it here
  // because under linux when you do IDENTIFY DEVICE to a packet
  // device, it generates an ugly kernel syslog error message.  This
  // is harmless but frightens users.  So this block detects packet
  // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
  // error message.
  //
  // If you read only the ATA specs, it appears as if a packet device
  // *might* respond to the IDENTIFY DEVICE command.  This is
  // misleading - it's because around the time that SFF-8020 was
  // incorporated into the ATA-3/4 standard, the ATA authors were
  // sloppy. See SFF-8020 and you will see that ATAPI devices have
  // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
  // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
  if (command==IDENTIFY || command==PIDENTIFY){
    unsigned short deviceid[256];
    // check the device identity, as seen when the system was booted
    // or the device was FIRST registered.  This will not be current
    // if the user has subsequently changed some of the parameters. If
    // device is a packet device, swap the command interpretations.
    if (!ioctl(device, HDIO_GET_IDENTITY, deviceid) && (deviceid[0] & 0x8000))
      buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
  }
#endif
  
  // We are now doing the HDIO_DRIVE_CMD type ioctl.
  if ((ioctl(device, HDIO_DRIVE_CMD, buff)))
    return -1;

  // CHECK POWER MODE command returns information in the Sector Count
  // register (buff[3]).  Copy to return data buffer.
  if (command==CHECK_POWER_MODE)
    buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];

  // if the command returns data then copy it back
  if (copydata)
    memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
  
  return 0; 
}

// >>>>>> Start of general SCSI specific linux code

/* Linux specific code.
 * Historically smartmontools (and smartsuite before it) used the
 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
 * nodes that use the SCSI subsystem. A better interface has been available
 * via the SCSI generic (sg) driver but this involves the extra step of
 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
 * the sg driver have become available via the SG_IO ioctl which is available
 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
 * So the strategy below is to find out if the SG_IO ioctl is available and
 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */

#define MAX_DXFER_LEN 1024      /* can be increased if necessary */
#define SEND_IOCTL_RESP_SENSE_LEN 16    /* ioctl limitation */
#define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
#define LSCSI_DRIVER_MASK  0xf /* mask out "suggestions" */
#define LSCSI_DRIVER_SENSE  0x8 /* alternate CHECK CONDITION indication */
#define LSCSI_DRIVER_TIMEOUT  0x6
#define LSCSI_DID_TIME_OUT  0x3
#define LSCSI_DID_BUS_BUSY  0x2
#define LSCSI_DID_NO_CONNECT  0x1

#ifndef SCSI_IOCTL_SEND_COMMAND
#define SCSI_IOCTL_SEND_COMMAND 1
#endif

#define SG_IO_PRESENT_UNKNOWN 0
#define SG_IO_PRESENT_YES 1
#define SG_IO_PRESENT_NO 2

static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
			 int unknown);
static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report);

static int sg_io_state = SG_IO_PRESENT_UNKNOWN;

/* Preferred implementation for issuing SCSI commands in linux. This
 * function uses the SG_IO ioctl. Return 0 if command issued successfully
 * (various status values should still be checked). If the SCSI command
 * cannot be issued then a negative errno value is returned. */
static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
			 int unknown)
{
#ifndef SG_IO
    ARGUSED(dev_fd); ARGUSED(iop); ARGUSED(report);
    return -ENOTTY;
#else
    struct sg_io_hdr io_hdr;

    if (report > 0) {
        int k, j;
        const unsigned char * ucp = iop->cmnd;
        const char * np;
        char buff[256];
        const int sz = (int)sizeof(buff);

        np = scsi_get_opcode_name(ucp[0]);
        j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
        for (k = 0; k < (int)iop->cmnd_len; ++k)
            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
        if ((report > 1) && 
            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
            int trunc = (iop->dxfer_len > 256) ? 1 : 0;

            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
                          "data, len=%d%s:\n", (int)iop->dxfer_len,
                          (trunc ? " [only first 256 bytes shown]" : ""));
            dStrHex((const char *)iop->dxferp, 
		    (trunc ? 256 : iop->dxfer_len) , 1);
        }
        else
            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
        pout(buff);
    }
    memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
    io_hdr.interface_id = 'S';
    io_hdr.cmd_len = iop->cmnd_len;
    io_hdr.mx_sb_len = iop->max_sense_len;
    io_hdr.dxfer_len = iop->dxfer_len;
    io_hdr.dxferp = iop->dxferp;
    io_hdr.cmdp = iop->cmnd;
    io_hdr.sbp = iop->sensep;
    /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
       defaults to 60 seconds. */
    io_hdr.timeout = ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
    switch (iop->dxfer_dir) {
        case DXFER_NONE:
            io_hdr.dxfer_direction = SG_DXFER_NONE;
            break;
        case DXFER_FROM_DEVICE:
            io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
            break;
        case DXFER_TO_DEVICE:
            io_hdr.dxfer_direction = SG_DXFER_TO_DEV;
            break;
        default:
            pout("do_scsi_cmnd_io: bad dxfer_dir\n");
            return -EINVAL;
    }
    iop->resp_sense_len = 0;
    iop->scsi_status = 0;
    iop->resid = 0;
    if (ioctl(dev_fd, SG_IO, &io_hdr) < 0) {
        if (report && (! unknown))
            pout("  SG_IO ioctl failed, errno=%d [%s]\n", errno,
		 strerror(errno));
        return -errno;
    }
    if (report > 0) {
        pout("  scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
	     "  info=0x%x  duration=%d milliseconds\n", io_hdr.status, 
	     io_hdr.host_status, io_hdr.driver_status, io_hdr.info,
	     io_hdr.duration);
        if (report > 1) {
            if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
                int trunc = (iop->dxfer_len > 256) ? 1 : 0;

                pout("  Incoming data, len=%d%s:\n", (int)iop->dxfer_len,
                     (trunc ? " [only first 256 bytes shown]" : ""));
                dStrHex((const char*)iop->dxferp, 
		        (trunc ? 256 : iop->dxfer_len) , 1);
            }
        }
    }
    iop->resid = io_hdr.resid;
    iop->scsi_status = io_hdr.status;

    if (io_hdr.info | SG_INFO_CHECK) { /* error or warning */
	int masked_driver_status = (LSCSI_DRIVER_MASK & io_hdr.driver_status);

	if (0 != io_hdr.host_status) {
            if ((LSCSI_DID_NO_CONNECT == io_hdr.host_status) ||
                (LSCSI_DID_BUS_BUSY == io_hdr.host_status) ||
                (LSCSI_DID_TIME_OUT == io_hdr.host_status))
                return -ETIMEDOUT;
	    else
		return -EIO;	/* catch all */
        }
        if (0 != masked_driver_status) {
            if (LSCSI_DRIVER_TIMEOUT == masked_driver_status)
                return -ETIMEDOUT;
	    else if (LSCSI_DRIVER_SENSE != masked_driver_status)
		return -EIO;
	}
        if (LSCSI_DRIVER_SENSE == masked_driver_status)
            iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
        iop->resp_sense_len = io_hdr.sb_len_wr;
        if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) && 
            iop->sensep && (iop->resp_sense_len > 0)) {
            if (report > 1) {
                pout("  >>> Sense buffer, len=%d:\n",
		     (int)iop->resp_sense_len);
                dStrHex((const char *)iop->sensep, iop->resp_sense_len , 1);
            }
        }
        if (report) {
            if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
                pout("  status=%x: sense_key=%x asc=%x ascq=%x\n",
		     iop->scsi_status, iop->sensep[2] & 0xf, iop->sensep[12],
		     iop->sensep[13]);
            }
            else
                pout("  status=0x%x\n", iop->scsi_status);
        }
    }
    return 0;
#endif
}

struct linux_ioctl_send_command
{
    int inbufsize;
    int outbufsize;
    UINT8 buff[MAX_DXFER_LEN + 16];
};

/* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't 
 * support: CDB length (guesses it from opcode), resid and timeout.
 * Patches in Linux 2.4.21 and 2.5.70 to extend SEND DIAGNOSTIC timeout
 * to 2 hours in order to allow long foreground extended self tests. */
static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
{
    struct linux_ioctl_send_command wrk;
    int status, buff_offset;
    size_t len;

    memcpy(wrk.buff, iop->cmnd, iop->cmnd_len);
    buff_offset = iop->cmnd_len;
    if (report > 0) {
        int k, j;
        const unsigned char * ucp = iop->cmnd;
        const char * np;
        char buff[256];
        const int sz = (int)sizeof(buff);

        np = scsi_get_opcode_name(ucp[0]);
        j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
        for (k = 0; k < (int)iop->cmnd_len; ++k)
            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
        if ((report > 1) && 
            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
            int trunc = (iop->dxfer_len > 256) ? 1 : 0;

            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
                          "data, len=%d%s:\n", (int)iop->dxfer_len,
                          (trunc ? " [only first 256 bytes shown]" : ""));
            dStrHex((const char *)iop->dxferp, 
		    (trunc ? 256 : iop->dxfer_len) , 1);
        }
        else
            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
        pout(buff);
    }
    switch (iop->dxfer_dir) {
        case DXFER_NONE:
            wrk.inbufsize = 0;
            wrk.outbufsize = 0;
            break;
        case DXFER_FROM_DEVICE:
            wrk.inbufsize = 0;
            if (iop->dxfer_len > MAX_DXFER_LEN)
                return -EINVAL;
            wrk.outbufsize = iop->dxfer_len;
            break;
        case DXFER_TO_DEVICE:
            if (iop->dxfer_len > MAX_DXFER_LEN)
                return -EINVAL;
            memcpy(wrk.buff + buff_offset, iop->dxferp, iop->dxfer_len);
            wrk.inbufsize = iop->dxfer_len;
            wrk.outbufsize = 0;
            break;
        default:
            pout("do_scsi_cmnd_io: bad dxfer_dir\n");
            return -EINVAL;
    }
    iop->resp_sense_len = 0;
    iop->scsi_status = 0;
    iop->resid = 0;
    status = ioctl(dev_fd, SCSI_IOCTL_SEND_COMMAND, &wrk);
    if (-1 == status) {
        if (report)
            pout("  SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
                 errno, strerror(errno));
        return -errno;
    }
    if (0 == status) {
        if (report > 0)
            pout("  status=0\n");
        if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
            memcpy(iop->dxferp, wrk.buff, iop->dxfer_len);
            if (report > 1) {
                int trunc = (iop->dxfer_len > 256) ? 1 : 0;

                pout("  Incoming data, len=%d%s:\n", (int)iop->dxfer_len,
                     (trunc ? " [only first 256 bytes shown]" : ""));
                dStrHex((const char*)iop->dxferp, 
			(trunc ? 256 : iop->dxfer_len) , 1);
            }
        }
        return 0;
    }
    iop->scsi_status = status & 0x7e; /* bits 0 and 7 used to be for vendors */
    if (LSCSI_DRIVER_SENSE == ((status >> 24) & 0xf))
        iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
    len = (SEND_IOCTL_RESP_SENSE_LEN < iop->max_sense_len) ?
                SEND_IOCTL_RESP_SENSE_LEN : iop->max_sense_len;
    if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) && 
        iop->sensep && (len > 0)) {
        memcpy(iop->sensep, wrk.buff, len);
        iop->resp_sense_len = len;
        if (report > 1) {
            pout("  >>> Sense buffer, len=%d:\n", (int)len);
            dStrHex((const char *)wrk.buff, len , 1);
        }
    }
    if (report) {
        if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
            pout("  status=%x: sense_key=%x asc=%x ascq=%x\n", status & 0xff,
                 wrk.buff[2] & 0xf, wrk.buff[12], wrk.buff[13]);
        }
        else
            pout("  status=0x%x\n", status);
    }
    if (iop->scsi_status > 0)
        return 0;
    else {
        if (report > 0)
            pout("  ioctl status=0x%x but scsi status=0, fail with EIO\n", 
                 status);
        return -EIO;      /* give up, assume no device there */
    }
}

/* SCSI command transmission interface function, linux version.
 * Returns 0 if SCSI command successfully launched and response
 * received. Even when 0 is returned the caller should check 
 * scsi_cmnd_io::scsi_status for SCSI defined errors and warnings
 * (e.g. CHECK CONDITION). If the SCSI command could not be issued
 * (e.g. device not present or timeout) or some other problem
 * (e.g. timeout) then returns a negative errno value */
int do_scsi_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
{
    int res;

    /* implementation relies on static sg_io_state variable. If not
     * previously set tries the SG_IO ioctl. If that succeeds assume
     * that SG_IO ioctl functional. If it fails with an errno value
     * other than ENODEV (no device) or permission then assume 
     * SCSI_IOCTL_SEND_COMMAND is the only option. */
    switch (sg_io_state) {
    case SG_IO_PRESENT_UNKNOWN:
        /* ignore report argument */
	if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, 1))) {
	    sg_io_state = SG_IO_PRESENT_YES;
	    return 0;
	} else if ((-ENODEV == res) || (-EACCES == res) || (-EPERM == res))
	    return res;		/* wait until we see a device */
        sg_io_state = SG_IO_PRESENT_NO;
	/* drop through by design */
    case SG_IO_PRESENT_NO:
	return sisc_cmnd_io(dev_fd, iop, report);
    case SG_IO_PRESENT_YES:
	return sg_io_cmnd_io(dev_fd, iop, report, 0);
    default:
	pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state); 
	sg_io_state = SG_IO_PRESENT_UNKNOWN;
        return -EIO; 	/* report error and reset state */
    }
}

// >>>>>> End of general SCSI specific linux code


// prototype
void printwarning(smart_command_set command);

// PURPOSE
//   This is an interface routine meant to isolate the OS dependent
//   parts of the code, and to provide a debugging interface.  Each
//   different port and OS needs to provide it's own interface.  This
//   is the linux interface to the 3ware 3w-xxxx driver.  It allows ATA
//   commands to be passed through the SCSI driver.
// DETAILED DESCRIPTION OF ARGUMENTS
//   fd: is the file descriptor provided by open()
//   disknum is the disk number (0 to 15) in the RAID array
//   escalade_type indicates the type of controller type, and if scsi or char interface is used
//   command: defines the different operations.
//   select: additional input data if needed (which log, which type of
//           self-test).
//   data:   location to write output data, if needed (512 bytes).
//   Note: not all commands use all arguments.
// RETURN VALUES
//  -1 if the command failed
//   0 if the command succeeded,
//   STATUS_CHECK routine: 
//  -1 if the command failed
//   0 if the command succeeded and disk SMART status is "OK"
//   1 if the command succeeded and disk SMART status is "FAILING"


/* 512 is the max payload size: increase if needed */
#define BUFFER_LEN_678K      ( sizeof(TW_Ioctl)                  ) // 1044 unpacked, 1041 packed
#define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1        ) // 1539 unpacked, 1536 packed
#define BUFFER_LEN_9000      ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
#define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )

int escalade_command_interface(int fd, int disknum, int escalade_type, smart_command_set command, int select, char *data){

  // return value and buffer for ioctl()
  int  ioctlreturn, readdata=0;

  // Used by both the SCSI and char interfaces
  TW_Passthru *passthru=NULL;
  char ioctl_buffer[TW_IOCTL_BUFFER_SIZE];

  // only used for SCSI device interface
  TW_Ioctl   *tw_ioctl=NULL;
  TW_Output *tw_output=NULL;

  // only used for 6000/7000/8000 char device interface
  TW_New_Ioctl *tw_ioctl_char=NULL;

  // only used for 9000 character device interface
  TW_Ioctl_Buf_Apache *tw_ioctl_apache=NULL;
  
  memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);

  if (escalade_type==CONTROLLER_3WARE_9000_CHAR) {
    tw_ioctl_apache                               = (TW_Ioctl_Buf_Apache *)ioctl_buffer;
    tw_ioctl_apache->driver_command.control_code  = TW_IOCTL_FIRMWARE_PASS_THROUGH;
    tw_ioctl_apache->driver_command.buffer_length = 512; /* payload size */
    passthru                                      = (TW_Passthru *)&(tw_ioctl_apache->firmware_command.command.oldcommand);
  }
  else if (escalade_type==CONTROLLER_3WARE_678K_CHAR) {
    tw_ioctl_char                                 = (TW_New_Ioctl *)ioctl_buffer;
    tw_ioctl_char->data_buffer_length             = 512;
    passthru                                      = (TW_Passthru *)&(tw_ioctl_char->firmware_command);
  }
  else if (escalade_type==CONTROLLER_3WARE_678K) {
    tw_ioctl                                      = (TW_Ioctl *)ioctl_buffer;
    tw_ioctl->cdb[0]                              = TW_IOCTL;
    tw_ioctl->opcode                              = TW_ATA_PASSTHRU;
    tw_ioctl->input_length                        = 512; // correct even for non-data commands
    tw_ioctl->output_length                       = 512; // correct even for non-data commands
    tw_output                                     = (TW_Output *)tw_ioctl;
    passthru                                      = (TW_Passthru *)&(tw_ioctl->input_data);
  }
  else {
    pout("Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
         "Please contact " PACKAGE_BUGREPORT "\n", escalade_type, disknum);
    errno=ENOSYS;
    return -1;
  }

  // Same for (almost) all commands - but some reset below
  passthru->byte0.opcode  = TW_OP_ATA_PASSTHRU;
  passthru->request_id    = 0xFF;
  passthru->byte3.aport   = disknum;
  passthru->byte3.host_id = 0;
  passthru->status        = 0;           
  passthru->flags         = 0x1;
  passthru->drive_head    = 0x0;
  passthru->sector_num    = 0;

  // All SMART commands use this CL/CH signature.  These are magic
  // values from the ATA specifications.
  passthru->cylinder_lo   = 0x4F;
  passthru->cylinder_hi   = 0xC2;
  
  // SMART ATA COMMAND REGISTER value
  passthru->command       = ATA_SMART_CMD;
  
  // Is this a command that reads or returns 512 bytes?
  // passthru->param values are:
  // 0x0 - non data command without TFR write check,
  // 0x8 - non data command with TFR write check,
  // 0xD - data command that returns data to host from device
  // 0xF - data command that writes data from host to device
  // passthru->size values are 0x5 for non-data and 0x07 for data
  if (command == READ_VALUES     ||
      command == READ_THRESHOLDS ||
      command == READ_LOG        ||
      command == IDENTIFY        ||
      command == WRITE_LOG ) {
    readdata=1;
    passthru->byte0.sgloff = 0x5;
    passthru->size         = 0x7;
    passthru->param        = 0xD;
    passthru->sector_count = 0x1;
    // For 64-bit to work correctly, up the size of the command packet
    // in dwords by 1 to account for the 64-bit single sgl 'address'
    // field. Note that this doesn't agree with the typedefs but it's
    // right (agree with kernel driver behavior/typedefs).
    if (escalade_type==CONTROLLER_3WARE_9000_CHAR && sizeof(long)==8)
      passthru->size++;
  }
  else {
    // Non data command -- but doesn't use large sector 
    // count register values.  
    passthru->byte0.sgloff = 0x0;
    passthru->size         = 0x5;
    passthru->param        = 0x8;
    passthru->sector_count = 0x0;
  }
  
  // Now set ATA registers depending upon command
  switch (command){
  case CHECK_POWER_MODE:
    passthru->command     = ATA_CHECK_POWER_MODE;
    passthru->features    = 0;
    passthru->cylinder_lo = 0;
    passthru->cylinder_hi = 0;
    break;
  case READ_VALUES:
    passthru->features = ATA_SMART_READ_VALUES;
    break;
  case READ_THRESHOLDS:
    passthru->features = ATA_SMART_READ_THRESHOLDS;
    break;
  case READ_LOG:
    passthru->features = ATA_SMART_READ_LOG_SECTOR;
    // log number to return
    passthru->sector_num  = select;
    break;
  case WRITE_LOG:
    if (escalade_type == CONTROLLER_3WARE_9000_CHAR)
      memcpy((unsigned char *)tw_ioctl_apache->data_buffer, data, 512);
    else if (escalade_type == CONTROLLER_3WARE_678K_CHAR)
      memcpy((unsigned char *)tw_ioctl_char->data_buffer,   data, 512);
    else {
      // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
      // memcpy(tw_output->output_data, data, 512);
      printwarning(command);
      errno=ENOTSUP;
      return -1;
    }
    readdata=0;
    passthru->features     = ATA_SMART_WRITE_LOG_SECTOR;
    passthru->sector_count = 1;
    passthru->sector_num   = select;
    passthru->param        = 0xF;  // PIO data write
    break;
  case IDENTIFY:
    // ATA IDENTIFY DEVICE
    passthru->command     = ATA_IDENTIFY_DEVICE;
    passthru->features    = 0;
    passthru->cylinder_lo = 0;
    passthru->cylinder_hi = 0;
    break;
  case PIDENTIFY:
    // 3WARE controller can NOT have packet device internally
    pout("WARNING - NO DEVICE FOUND ON 3WARE CONTROLLER (disk %d)\n", disknum);
    pout("Note: /dev/sdX many need to be replaced with /dev/tweN or /dev/twaN\n");
    errno=ENODEV;
    return -1;
  case ENABLE:
    passthru->features = ATA_SMART_ENABLE;
    break;
  case DISABLE:
    passthru->features = ATA_SMART_DISABLE;
    break;
  case AUTO_OFFLINE:
    passthru->features     = ATA_SMART_AUTO_OFFLINE;
    // Enable or disable?
    passthru->sector_count = select;
    break;
  case AUTOSAVE:
    passthru->features     = ATA_SMART_AUTOSAVE;
    // Enable or disable?
    passthru->sector_count = select;
    break;
  case IMMEDIATE_OFFLINE:
    passthru->features    = ATA_SMART_IMMEDIATE_OFFLINE;
    // What test type to run?
    passthru->sector_num  = select;
    break;
  case STATUS_CHECK:
    passthru->features = ATA_SMART_STATUS;
    break;
  case STATUS:
    // This is JUST to see if SMART is enabled, by giving SMART status
    // command. But it doesn't say if status was good, or failing.
    // See below for the difference.
    passthru->features = ATA_SMART_STATUS;
    break;
  default:
    pout("Unrecognized command %d in linux_3ware_command_interface(disk %d)\n"
         "Please contact " PACKAGE_BUGREPORT "\n", command, disknum);
    errno=ENOSYS;
    return -1;
  }

  // Now send the command down through an ioctl()
  if (escalade_type==CONTROLLER_3WARE_9000_CHAR)
    ioctlreturn=ioctl(fd, TW_IOCTL_FIRMWARE_PASS_THROUGH, tw_ioctl_apache);
  else if (escalade_type==CONTROLLER_3WARE_678K_CHAR)
    ioctlreturn=ioctl(fd, TW_CMD_PACKET_WITH_DATA, tw_ioctl_char);
  else
    ioctlreturn=ioctl(fd, SCSI_IOCTL_SEND_COMMAND, tw_ioctl);
  
  // Deal with the different error cases
  if (ioctlreturn) {
    if (CONTROLLER_3WARE_678K==escalade_type && ((command==AUTO_OFFLINE || command==AUTOSAVE) && select)){
      // error here is probably a kernel driver whose version is too old
      printwarning(command);
      errno=ENOTSUP;
    }
    if (!errno)
      errno=EIO;
    return -1;
  }
  
  // The passthru structure is valid after return from an ioctl if:
  // - we are using the character interface OR 
  // - we are using the SCSI interface and this is a NON-READ-DATA command
  // For SCSI interface, note that we set passthru to a different
  // value after ioctl().
  if (CONTROLLER_3WARE_678K==escalade_type) {
    if (readdata)
      passthru=NULL;
    else
      passthru=(TW_Passthru *)&(tw_output->output_data);
  }

  // See if the ATA command failed.  Now that we have returned from
  // the ioctl() call, if passthru is valid, then:
  // - passthru->status contains the 3ware controller STATUS
  // - passthru->command contains the ATA STATUS register
  // - passthru->features contains the ATA ERROR register
  //
  // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
  // If bit 0 (error bit) is set, then ATA ERROR register is valid.
  // While we *might* decode the ATA ERROR register, at the moment it
  // doesn't make much sense: we don't care in detail why the error
  // happened.
  
  if (passthru && (passthru->status || (passthru->command & 0x21))) {
    errno=EIO;
    return -1;
  }
  
  // If this is a read data command, copy data to output buffer
  if (readdata) {
    if (escalade_type==CONTROLLER_3WARE_9000_CHAR)
      memcpy(data, (unsigned char *)tw_ioctl_apache->data_buffer, 512);
    else if (escalade_type==CONTROLLER_3WARE_678K_CHAR)
      memcpy(data, (unsigned char *)tw_ioctl_char->data_buffer, 512);
    else
      memcpy(data, tw_output->output_data, 512);
  }

  // For STATUS_CHECK, we need to check register values
  if (command==STATUS_CHECK) {
    
    // To find out if the SMART RETURN STATUS is good or failing, we
    // need to examine the values of the Cylinder Low and Cylinder
    // High Registers.
    
    unsigned short cyl_lo=passthru->cylinder_lo;
    unsigned short cyl_hi=passthru->cylinder_hi;
    
    // If values in Cyl-LO and Cyl-HI are unchanged, SMART status is good.
    if (cyl_lo==0x4F && cyl_hi==0xC2)
      return 0;
    
    // If values in Cyl-LO and Cyl-HI are as follows, SMART status is FAIL
    if (cyl_lo==0xF4 && cyl_hi==0x2C)
      return 1;
    
    // Any other values mean that something has gone wrong with the command
    if (CONTROLLER_3WARE_678K==escalade_type) {
      printwarning(command);
      errno=ENOSYS;
      return 0;
    }
    else {
      errno=EIO;
      return -1;
    }
  }
  
  // copy sector count register (one byte!) to return data
  if (command==CHECK_POWER_MODE)
    *data=*(char *)&(passthru->sector_count);
  
  // look for nonexistent devices/ports
  if (command==IDENTIFY && !nonempty((unsigned char *)data, 512)) {
    errno=ENODEV;
    return -1;
  }
  
  return 0;
}



int marvell_command_interface(int device, 
                              smart_command_set command, 
                              int select, 
                              char *data) {  
  typedef struct {  
    int  inlen;
    int  outlen;
    char cmd[540];
  } mvsata_scsi_cmd;
  
  int copydata = 0;
  mvsata_scsi_cmd  smart_command;
  unsigned char *buff = (unsigned char *)&smart_command.cmd[6];
  // See struct hd_drive_cmd_hdr in hdreg.h
  // buff[0]: ATA COMMAND CODE REGISTER
  // buff[1]: ATA SECTOR NUMBER REGISTER
  // buff[2]: ATA FEATURES REGISTER
  // buff[3]: ATA SECTOR COUNT REGISTER
  
  // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
  memset(&smart_command, 0, sizeof(smart_command));
  smart_command.inlen = 540;
  smart_command.outlen = 540;
  smart_command.cmd[0] = 0xC;  //Vendor-specific code
  smart_command.cmd[4] = 6;     //command length
  
  buff[0] = ATA_SMART_CMD;
  switch (command){
  case CHECK_POWER_MODE:
    buff[0]=ATA_CHECK_POWER_MODE;
    break;
  case READ_VALUES:
    buff[2]=ATA_SMART_READ_VALUES;
    copydata=buff[3]=1;
    break;
  case READ_THRESHOLDS:
    buff[2]=ATA_SMART_READ_THRESHOLDS;
    copydata=buff[1]=buff[3]=1;
    break;
  case READ_LOG:
    buff[2]=ATA_SMART_READ_LOG_SECTOR;
    buff[1]=select;
    copydata=buff[3]=1;
    break;
  case IDENTIFY:
    buff[0]=ATA_IDENTIFY_DEVICE;
    copydata=buff[3]=1;
    break;
  case PIDENTIFY:
    buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
    copydata=buff[3]=1;
    break;
  case ENABLE:
    buff[2]=ATA_SMART_ENABLE;
    buff[1]=1;
    break;
  case DISABLE:
    buff[2]=ATA_SMART_DISABLE;
    buff[1]=1;
    break;
  case STATUS:
  case STATUS_CHECK:
    // this command only says if SMART is working.  It could be
    // replaced with STATUS_CHECK below.
    buff[2] = ATA_SMART_STATUS;
    break;
  case AUTO_OFFLINE:
    buff[2]=ATA_SMART_AUTO_OFFLINE;
    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
    break;
  case AUTOSAVE:
    buff[2]=ATA_SMART_AUTOSAVE;
    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
    break;
  case IMMEDIATE_OFFLINE:
    buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
    buff[1]=select;
    break;
  default:
    pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command);
    exit(1);
    break;
  }  
  // There are two different types of ioctls().  The HDIO_DRIVE_TASK
  // one is this:
  // We are now doing the HDIO_DRIVE_CMD type ioctl.
  if (ioctl(device, SCSI_IOCTL_SEND_COMMAND, (void *)&smart_command))
      return -1;

  if (command==CHECK_POWER_MODE) {
    // LEON -- CHECK THIS PLEASE.  THIS SHOULD BE THE SECTOR COUNT
    // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3].  Bruce
    data[0]=buff[3];
    return 0;
  }

  // Always succeed on a SMART status, as a disk that failed returned  
  // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
  if (command == STATUS)
    return 0;
  //Data returned is starting from 0 offset  
  if (command == STATUS_CHECK)
  {
    // Cyl low and Cyl high unchanged means "Good SMART status"
    if (buff[4] == 0x4F && buff[5] == 0xC2)
      return 0;    
    // These values mean "Bad SMART status"
    if (buff[4] == 0xF4 && buff[5] == 0x2C)
      return 1;    
    // We haven't gotten output that makes sense; print out some debugging info
    syserror("Error SMART Status command failed");
    pout("Please get assistance from %s\n",PACKAGE_BUGREPORT);
    pout("Register values returned from SMART Status command are:\n");
    pout("CMD =0x%02x\n",(int)buff[0]);
    pout("FR =0x%02x\n",(int)buff[1]);
    pout("NS =0x%02x\n",(int)buff[2]);
    pout("SC =0x%02x\n",(int)buff[3]);
    pout("CL =0x%02x\n",(int)buff[4]);
    pout("CH =0x%02x\n",(int)buff[5]);
    pout("SEL=0x%02x\n",(int)buff[6]);
    return -1;   
  }  

  if (copydata)
    memcpy(data, buff, 512);
  return 0; 
}


// Utility function for printing warnings
void printwarning(smart_command_set command){
  static int printed[4]={0,0,0,0};
  const char* message=
    "can not be passed through the 3ware 3w-xxxx driver.  This can be fixed by\n"
    "applying a simple 3w-xxxx driver patch that can be found here:\n"
    PACKAGE_HOMEPAGE "\n"
    "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";

  if (command==AUTO_OFFLINE && !printed[0]) {
    printed[0]=1;
    pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message);
  } 
  else if (command==AUTOSAVE && !printed[1]) {
    printed[1]=1;
    pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message);
  }
  else if (command==STATUS_CHECK && !printed[2]) {
    printed[2]=1;
    pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message);
  }
  else if (command==WRITE_LOG && !printed[3])  {
    printed[3]=1;
    pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
  }
  
  return;
}

// Guess device type (ata or scsi) based on device name (Linux
// specific) SCSI device name in linux can be sd, sr, scd, st, nst,
// osst, nosst and sg.
static const char * lin_dev_prefix = "/dev/";
static const char * lin_dev_ata_disk_plus = "h";
static const char * lin_dev_ata_devfs_disk_plus = "ide/";
static const char * lin_dev_scsi_devfs_disk_plus = "scsi/";
static const char * lin_dev_scsi_disk_plus = "s";
static const char * lin_dev_scsi_tape1 = "ns";
static const char * lin_dev_scsi_tape2 = "os";
static const char * lin_dev_scsi_tape3 = "nos";
static const char * lin_dev_3ware_9000_char = "twa";
static const char * lin_dev_3ware_678k_char = "twe";

int guess_device_type(const char * dev_name) {
  int len;
  int dev_prefix_len = strlen(lin_dev_prefix);
  
  // if dev_name null, or string length zero
  if (!dev_name || !(len = strlen(dev_name)))
    return CONTROLLER_UNKNOWN;
  
  // Remove the leading /dev/... if it's there
  if (!strncmp(lin_dev_prefix, dev_name, dev_prefix_len)) {
    if (len <= dev_prefix_len)
      // if nothing else in the string, unrecognized
      return CONTROLLER_UNKNOWN;
    // else advance pointer to following characters
    dev_name += dev_prefix_len;
  }
  
  // form /dev/h* or h*
  if (!strncmp(lin_dev_ata_disk_plus, dev_name,
               strlen(lin_dev_ata_disk_plus)))
    return CONTROLLER_ATA;
  
  // form /dev/ide/* or ide/*
  if (!strncmp(lin_dev_ata_devfs_disk_plus, dev_name,
               strlen(lin_dev_ata_devfs_disk_plus)))
    return CONTROLLER_ATA;

  // form /dev/s* or s*
  if (!strncmp(lin_dev_scsi_disk_plus, dev_name,
               strlen(lin_dev_scsi_disk_plus)))
    return CONTROLLER_SCSI;

  // form /dev/scsi/* or scsi/*
  if (!strncmp(lin_dev_scsi_devfs_disk_plus, dev_name,
               strlen(lin_dev_scsi_devfs_disk_plus)))
    return CONTROLLER_SCSI;
  
  // form /dev/ns* or ns*
  if (!strncmp(lin_dev_scsi_tape1, dev_name,
               strlen(lin_dev_scsi_tape1)))
    return CONTROLLER_SCSI;
  
  // form /dev/os* or os*
  if (!strncmp(lin_dev_scsi_tape2, dev_name,
               strlen(lin_dev_scsi_tape2)))
    return CONTROLLER_SCSI;
  
  // form /dev/nos* or nos*
  if (!strncmp(lin_dev_scsi_tape3, dev_name,
               strlen(lin_dev_scsi_tape3)))
    return CONTROLLER_SCSI;

  // form /dev/twa*
  if (!strncmp(lin_dev_3ware_9000_char, dev_name,
               strlen(lin_dev_3ware_9000_char)))
    return CONTROLLER_3WARE_9000_CHAR;

  // form /dev/twe*
  if (!strncmp(lin_dev_3ware_678k_char, dev_name,
               strlen(lin_dev_3ware_678k_char)))
    return CONTROLLER_3WARE_678K_CHAR;

  // we failed to recognize any of the forms
  return CONTROLLER_UNKNOWN;
}


#if 0

[ed@firestorm ed]$ ls -l  /dev/discs
total 0
lr-xr-xr-x    1 root     root           30 Dec 31  1969 disc0 -> ../ide/host2/bus0/target0/lun0/
lr-xr-xr-x    1 root     root           30 Dec 31  1969 disc1 -> ../ide/host2/bus1/target0/lun0/
[ed@firestorm ed]$ ls -l  dev/ide/host*/bus*/target*/lun*/disc
ls: dev/ide/host*/bus*/target*/lun*/disc: No such file or directory
[ed@firestorm ed]$ ls -l  /dev/ide/host*/bus*/target*/lun*/disc
brw-------    1 root     root      33,   0 Dec 31  1969 /dev/ide/host2/bus0/target0/lun0/disc
brw-------    1 root     root      34,   0 Dec 31  1969 /dev/ide/host2/bus1/target0/lun0/disc
[ed@firestorm ed]$ ls -l  /dev/ide/c*b*t*u*
ls: /dev/ide/c*b*t*u*: No such file or directory
[ed@firestorm ed]$ 
Script done on Fri Nov  7 13:46:28 2003

#endif