os_win32.cpp 111 KB
Newer Older
1
/*
chrfranke's avatar
chrfranke committed
2
 * os_win32.cpp
3
4
5
 *
 * Home page of code is: http://smartmontools.sourceforge.net
 *
6
 * Copyright (C) 2004-10 Christian Franke <smartmontools-support@lists.sourceforge.net>
7
8
9
10
11
12
13
 *
 * 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
14
 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
15
16
17
18
 *
 */

#include "config.h"
19
#include "int64.h"
20
#include "atacmds.h"
21
#include "extern.h"
22
extern smartmonctrl * con; // con->permissive,reportataioctl
23
24
#include "scsicmds.h"
#include "utility.h"
25
26
27

#include "dev_interface.h"
#include "dev_ata_cmd_set.h"
28

29
#include <errno.h>
30

31
#ifdef _DEBUG
32
#include <assert.h>
33
#else
34
#undef assert
35
#define assert(x) /* */
36
#endif
37

38
39
40
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stddef.h> // offsetof()
41
#include <io.h> // access()
42

43
44
45
46
#ifdef __CYGWIN__
#include <cygwin/version.h> // CYGWIN_VERSION_DLL_MAJOR
#endif

47
48
49
50
51
52
// Macro to check constants at compile time using a dummy typedef
#define ASSERT_CONST(c, n) \
  typedef char assert_const_##c[((c) == (n)) ? 1 : -1]
#define ASSERT_SIZEOF(t, n) \
  typedef char assert_sizeof_##t[(sizeof(t) == (n)) ? 1 : -1]

53
54
55
56
57
58
59
60
61
62
63
64
const char * os_win32_cpp_cvsid = "$Id$";

// Disable Win9x/ME specific code if no longer supported by compiler.
#ifndef WIN9X_SUPPORT
  #if defined(CYGWIN_VERSION_DLL_MAJOR) && (CYGWIN_VERSION_DLL_MAJOR >= 1007)
    // Win9x/ME support was dropped in Cygwin 1.7
  #elif defined(_MSC_VER) && (_MSC_VER >= 1500)
    // Win9x/ME support was dropped in MSVC9 (cl.exe 15.0)
  #else
    #define WIN9X_SUPPORT 1
  #endif
#endif
65

66
67
68
69
70
71
72
73
/////////////////////////////////////////////////////////////////////////////

namespace os_win32 { // no need to publish anything, name provided for Doxygen

#ifdef _MSC_VER
#pragma warning(disable:4250)
#endif

74
75
76
77
78
79
80
81
82
83
// Running on Win9x/ME ?
#if WIN9X_SUPPORT
// Set true in win9x_smart_interface ctor.
static bool win9x = false;
#else
// Never true (const allows compiler to remove dead code).
const  bool win9x = false;
#endif


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
class win_smart_device
: virtual public /*implements*/ smart_device
{
public:
  win_smart_device()
    : smart_device(never_called),
      m_fh(INVALID_HANDLE_VALUE)
    { }

  virtual ~win_smart_device() throw();

  virtual bool is_open() const;

  virtual bool close();

protected:
  /// Set handle for open() in derived classes.
  void set_fh(HANDLE fh)
    { m_fh = fh; }

  /// Return handle for derived classes.
  HANDLE get_fh() const
    { return m_fh; }

private:
  HANDLE m_fh; ///< File handle
};


/////////////////////////////////////////////////////////////////////////////

class win_ata_device
116
: public /*implements*/ ata_device,
117
118
119
120
121
122
123
124
125
  public /*extends*/ win_smart_device
{
public:
  win_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);

  virtual ~win_ata_device() throw();

  virtual bool open();

126
127
  virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out);

128
129
130
131
132
133
134
135
  virtual bool ata_identify_is_cached() const;

private:
  bool open(int phydrive, int logdrive, const char * options, int port);

  std::string m_options;
  bool m_usr_options; // options set by user?
  bool m_admin; // open with admin access?
136
  bool m_id_is_cached; // ata_identify_is_cached() return value.
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
  int m_drive, m_port;
  int m_smartver_state;
};


/////////////////////////////////////////////////////////////////////////////

class win_scsi_device
: public /*implements*/ scsi_device,
  virtual public /*extends*/ win_smart_device
{
public:
  win_scsi_device(smart_interface * intf, const char * dev_name, const char * req_type);

  virtual bool open();

  virtual bool scsi_pass_through(scsi_cmnd_io * iop);

private:
  bool open(int pd_num, int ld_num, int tape_num, int sub_addr);
};


/////////////////////////////////////////////////////////////////////////////

162
163
#if WIN9X_SUPPORT

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class win_aspi_device
: public /*implements*/ scsi_device
{
public:
  win_aspi_device(smart_interface * intf, const char * dev_name, const char * req_type);

  virtual bool is_open() const;

  virtual bool open();

  virtual bool close();

  virtual bool scsi_pass_through(scsi_cmnd_io * iop);

private:
  int m_adapter;
  unsigned char m_id;
};

183
#endif // WIN9X_SUPPORT
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

//////////////////////////////////////////////////////////////////////

class win_tw_cli_device
: public /*implements*/ ata_device_with_command_set
{
public:
  win_tw_cli_device(smart_interface * intf, const char * dev_name, const char * req_type);

  virtual bool is_open() const;

  virtual bool open();

  virtual bool close();

protected:
  virtual int ata_command_interface(smart_command_set command, int select, char * data);

private:
  bool m_ident_valid, m_smart_valid;
  ata_identify_device m_ident_buf;
  ata_smart_values m_smart_buf;
};


//////////////////////////////////////////////////////////////////////
// Platform specific interfaces

// Common to all windows flavors
class win_smart_interface
: public /*implements part of*/ smart_interface
{
public:
217
  virtual std::string get_os_version_str();
218

219
  virtual std::string get_app_examples(const char * appname);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

  virtual bool scan_smart_devices(smart_device_list & devlist, const char * type,
    const char * pattern = 0);

protected:
  virtual ata_device * get_ata_device(const char * name, const char * type);

//virtual scsi_device * get_scsi_device(const char * name, const char * type);

  virtual smart_device * autodetect_smart_device(const char * name);

  virtual bool ata_scan(smart_device_list & devlist) = 0;

  virtual bool scsi_scan(smart_device_list & devlist) = 0;
};

236
237
#if WIN9X_SUPPORT

238
239
240
241
// Win9x/ME reduced functionality
class win9x_smart_interface
: public /*extends*/ win_smart_interface
{
242
243
244
245
public:
  win9x_smart_interface()
    { win9x = true; }

246
247
248
249
250
251
252
253
protected:
  virtual scsi_device * get_scsi_device(const char * name, const char * type);

  virtual bool ata_scan(smart_device_list & devlist);

  virtual bool scsi_scan(smart_device_list & devlist);
};

254
255
#endif // WIN9X_SUPPORT

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// WinNT,2000,XP,...
class winnt_smart_interface
: public /*extends*/ win_smart_interface
{
protected:
  virtual scsi_device * get_scsi_device(const char * name, const char * type);

  virtual smart_device * autodetect_smart_device(const char * name);

  virtual bool ata_scan(smart_device_list & devlist);

  virtual bool scsi_scan(smart_device_list & devlist);
};


//////////////////////////////////////////////////////////////////////

273
274
275
// Running on 64-bit Windows as 32-bit app ?
static bool is_wow64()
{
276
277
278
279
280
281
282
283
284
285
286
  HMODULE hk = GetModuleHandleA("kernel32");
  if (!hk)
    return false;
  BOOL (WINAPI * IsWow64Process_p)(HANDLE, PBOOL) =
    (BOOL (WINAPI *)(HANDLE, PBOOL))GetProcAddress(hk, "IsWow64Process");
  if (!IsWow64Process_p)
    return false;
  BOOL w64 = FALSE;
  if (!IsWow64Process_p(GetCurrentProcess(), &w64))
    return false;
  return !!w64;
287
288
}

289
290
// Return info string about build host and OS version
std::string win_smart_interface::get_os_version_str()
291
{
292
  char vstr[sizeof(SMARTMONTOOLS_BUILD_HOST)-1+sizeof("-2003r2(64)-sp2.1")+13]
293
294
295
296
297
    = SMARTMONTOOLS_BUILD_HOST;
  if (vstr[1] < '6')
    vstr[1] = '6';
  char * const vptr = vstr+sizeof(SMARTMONTOOLS_BUILD_HOST)-1;
  const int vlen = sizeof(vstr)-sizeof(SMARTMONTOOLS_BUILD_HOST);
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
  assert(vptr == vstr+strlen(vstr) && vptr+vlen+1 == vstr+sizeof(vstr));

  OSVERSIONINFOEXA vi; memset(&vi, 0, sizeof(vi));
  vi.dwOSVersionInfoSize = sizeof(vi);
  if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
    memset(&vi, 0, sizeof(vi));
    vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
    if (!GetVersionExA((OSVERSIONINFOA *)&vi))
      return vstr;
  }

  if (vi.dwPlatformId > 0xff || vi.dwMajorVersion > 0xff || vi.dwMinorVersion > 0xff)
    return vstr;

  const char * w;
  switch (vi.dwPlatformId << 16 | vi.dwMajorVersion << 8 | vi.dwMinorVersion) {
    case VER_PLATFORM_WIN32_WINDOWS<<16|0x0400| 0:
      w = (vi.szCSDVersion[1] == 'B' ||
           vi.szCSDVersion[1] == 'C'     ? "95-osr2" : "95");    break;
    case VER_PLATFORM_WIN32_WINDOWS<<16|0x0400|10:
      w = (vi.szCSDVersion[1] == 'A'     ? "98se"    : "98");    break;
    case VER_PLATFORM_WIN32_WINDOWS<<16|0x0400|90: w = "me";     break;
  //case VER_PLATFORM_WIN32_NT     <<16|0x0300|51: w = "nt3.51"; break;
    case VER_PLATFORM_WIN32_NT     <<16|0x0400| 0: w = "nt4";    break;
    case VER_PLATFORM_WIN32_NT     <<16|0x0500| 0: w = "2000";   break;
    case VER_PLATFORM_WIN32_NT     <<16|0x0500| 1:
      w = (!GetSystemMetrics(87/*SM_MEDIACENTER*/) ?   "xp"
325
                                                   :   "xp-mc"); break;
326
    case VER_PLATFORM_WIN32_NT     <<16|0x0500| 2:
327
328
329
330
331
332
333
334
      w = (!GetSystemMetrics(89/*SM_SERVERR2*/)    ?   "2003"
                                                   :   "2003r2"); break;
    case VER_PLATFORM_WIN32_NT     <<16|0x0600| 0:
      w = (vi.wProductType == VER_NT_WORKSTATION   ?   "vista"
                                                   :   "2008" );  break;
    case VER_PLATFORM_WIN32_NT     <<16|0x0600| 1:
      w = (vi.wProductType == VER_NT_WORKSTATION   ?   "win7"
                                                   :   "2008r2"); break;
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    default: w = 0; break;
  }

  const char * w64 = (is_wow64() ? "(64)" : "");
  if (!w)
    snprintf(vptr, vlen, "-%s%lu.%lu%s",
      (vi.dwPlatformId==VER_PLATFORM_WIN32_NT ? "nt" : "9x"),
      vi.dwMajorVersion, vi.dwMinorVersion, w64);
  else if (vi.wServicePackMinor)
    snprintf(vptr, vlen, "-%s%s-sp%u.%u", w, w64, vi.wServicePackMajor, vi.wServicePackMinor);
  else if (vi.wServicePackMajor)
    snprintf(vptr, vlen, "-%s%s-sp%u", w, w64, vi.wServicePackMajor);
  else
    snprintf(vptr, vlen, "-%s%s", w, w64);
  return vstr;
350
351
}

352
// Return value for device detection functions
353
enum win_dev_type { DEV_UNKNOWN = 0, DEV_ATA, DEV_SCSI, DEV_USB };
354

355
356
static win_dev_type get_phy_drive_type(int drive);
static win_dev_type get_log_drive_type(int drive);
357
358
static bool get_usb_id(int drive, unsigned short & vendor_id,
                       unsigned short & product_id);
359

360
static const char * ata_get_def_options(void);
361

362
363
364

static int is_permissive()
{
365
366
367
368
369
370
  if (!con->permissive) {
    pout("To continue, add one or more '-T permissive' options.\n");
    return 0;
  }
  con->permissive--;
  return 1;
371
372
}

373
// return number for drive letter, -1 on error
374
// "[A-Za-z]:([/\\][.]?)?" => 0-25
375
376
377
// Accepts trailing '"' to fix broken "X:\" parameter passing from .bat files
static int drive_letter(const char * s)
{
378
379
380
381
382
  return (   (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))
          && s[1] == ':'
          && (!s[2] || (   strchr("/\\\"", s[2])
                        && (!s[3] || (s[3] == '.' && !s[4])))              ) ?
          (s[0] & 0x1f) - 1 : -1);
383
384
385
}

// Skip trailing "/dev/", do not allow "/dev/X:"
386
387
static const char * skipdev(const char * s)
{
388
  return (!strncmp(s, "/dev/", 5) && drive_letter(s+5) < 0 ? s+5 : s);
389
390
}

391
392
393
394
395
396
397
398
ata_device * win_smart_interface::get_ata_device(const char * name, const char * type)
{
  const char * testname = skipdev(name);
  if (!strncmp(testname, "tw_cli", 6))
    return new win_tw_cli_device(this, name, type);
  return new win_ata_device(this, name, type);
}

399
400
#ifdef WIN9X_SUPPORT

401
402
403
404
scsi_device * win9x_smart_interface::get_scsi_device(const char * name, const char * type)
{
  return new win_aspi_device(this, name, type);
}
405

406
407
#endif

408
409
410
411
scsi_device * winnt_smart_interface::get_scsi_device(const char * name, const char * type)
{
  const char * testname = skipdev(name);
  if (!strncmp(testname, "scsi", 4))
412
#if WIN9X_SUPPORT
413
    return new win_aspi_device(this, name, type);
414
415
416
#else
    return (set_err(EINVAL, "ASPI interface not supported"), (scsi_device *)0);
#endif
417
418
419
  return new win_scsi_device(this, name, type);
}

420
static win_dev_type get_dev_type(const char * name, int & phydrive)
421
{
422
  phydrive = -1;
423
424
425
426
427
428
429
430
431
  name = skipdev(name);
  if (!strncmp(name, "st", 2))
    return DEV_SCSI;
  if (!strncmp(name, "nst", 3))
    return DEV_SCSI;
  if (!strncmp(name, "tape", 4))
    return DEV_SCSI;

  int logdrive = drive_letter(name);
432
  if (logdrive >= 0) {
433
434
    win_dev_type type = get_log_drive_type(logdrive);
    return (type != DEV_UNKNOWN ? type : DEV_SCSI);
435
  }
436

437
  char drive[1+1] = "";
438
439
440
441
442
443
  if (sscanf(name, "sd%1[a-z]", drive) == 1) {
    phydrive = drive[0] - 'a';
    return get_phy_drive_type(phydrive);
  }

  phydrive = -1;
444
  if (sscanf(name, "pd%d", &phydrive) == 1 && phydrive >= 0)
445
    return get_phy_drive_type(phydrive);
446
  return DEV_UNKNOWN;
447
448
}

449
smart_device * win_smart_interface::autodetect_smart_device(const char * name)
450
{
451
452
453
  const char * testname = skipdev(name);
  if (!strncmp(testname, "hd", 2))
    return new win_ata_device(this, name, "");
454
#if WIN9X_SUPPORT
455
456
  if (!strncmp(testname, "scsi", 4))
    return new win_aspi_device(this, name, "");
457
#endif
458
459
460
461
  if (!strncmp(testname, "tw_cli", 6))
    return new win_tw_cli_device(this, name, "");
  return 0;
}
462

463
464
465
466
467
468
smart_device * winnt_smart_interface::autodetect_smart_device(const char * name)
{
  smart_device * dev = win_smart_interface::autodetect_smart_device(name);
  if (dev)
    return dev;

469
470
471
  int phydrive = -1;
  win_dev_type type = get_dev_type(name, phydrive);

472
473
474
475
  if (type == DEV_ATA)
    return new win_ata_device(this, name, "");
  if (type == DEV_SCSI)
    return new win_scsi_device(this, name, "");
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

  if (type == DEV_USB) {
    // Get USB bridge ID
    unsigned short vendor_id = 0, product_id = 0;
    if (!(phydrive >= 0 && get_usb_id(phydrive, vendor_id, product_id))) {
      set_err(EINVAL, "Unable to read USB device ID");
      return 0;
    }
    // Get type name for this ID
    const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id);
    if (!usbtype)
      return 0;
    // Return SAT/USB device for this type
    return get_sat_device(usbtype, new win_scsi_device(this, name, ""));
  }

492
  return 0;
493
494
495
}


496
497
498
// makes a list of ATA or SCSI devices for the DEVICESCAN directive
bool win_smart_interface::scan_smart_devices(smart_device_list & devlist,
  const char * type, const char * pattern /* = 0*/)
499
{
500
501
502
503
  if (pattern) {
    set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
    return false;
  }
504

505
506
507
  if (!type || !strcmp(type, "ata")) {
    if (!ata_scan(devlist))
      return false;
508
509
  }

510
511
512
513
514
  if (!type || !strcmp(type, "scsi")) {
    if (!scsi_scan(devlist))
      return false;
  }
  return true;
515
516
517
}


518
// get examples for smartctl
519
std::string win_smart_interface::get_app_examples(const char * appname)
520
{
521
  if (strcmp(appname, "smartctl"))
522
523
    return "";
  return "=================================================== SMARTCTL EXAMPLES =====\n\n"
chrfranke's avatar
chrfranke committed
524
525
526
527
528
529
530
531
         "  smartctl -a /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 -t 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 -a /dev/scsi21\n"
         "             (Prints all information for SCSI disk on ASPI adapter 2, ID 1)\n"
532
533
534
535
536
537
         "  smartctl -a /dev/sda\n"
         "             (Prints all information for SCSI disk on PhysicalDrive 0)\n"
         "  smartctl -a /dev/pd3\n"
         "             (Prints all information for SCSI disk on PhysicalDrive 3)\n"
         "  smartctl -a /dev/tape1\n"
         "             (Prints all information for SCSI tape on Tape 1)\n"
538
539
         "  smartctl -A /dev/hdb,3\n"
         "                (Prints Attributes for physical drive 3 on 3ware 9000 RAID)\n"
540
541
         "  smartctl -A /dev/tw_cli/c0/p1\n"
         "            (Prints Attributes for 3ware controller 0, port 1 using tw_cli)\n"
542
543
         "\n"
         "  ATA SMART access methods and ordering may be specified by modifiers\n"
544
         "  following the device name: /dev/hdX:[saicm], where\n"
545
         "  's': SMART_* IOCTLs,         'a': IOCTL_ATA_PASS_THROUGH,\n"
546
         "  'i': IOCTL_IDE_PASS_THROUGH, 'c': ATA via IOCTL_SCSI_PASS_THROUGH,\n"
547
         "  'f': IOCTL_STORAGE_*,        'm': IOCTL_SCSI_MINIPORT_*.\n"
548
      + strprintf(
549
         "  The default on this system is /dev/sdX:%s\n", ata_get_def_options()
550
        );
chrfranke's avatar
chrfranke committed
551
552
553
}


554
555
556
557
558
559
560
561
562
563
564
/////////////////////////////////////////////////////////////////////////////
// ATA Interface
/////////////////////////////////////////////////////////////////////////////

// SMART_* IOCTLs, also known as DFP_* (Disk Fault Protection)

#define FILE_READ_ACCESS       0x0001
#define FILE_WRITE_ACCESS      0x0002
#define METHOD_BUFFERED             0
#define CTL_CODE(DeviceType, Function, Method, Access) (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))

565
#define FILE_DEVICE_DISK       7
566
567
568
569
570
#define IOCTL_DISK_BASE        FILE_DEVICE_DISK

#define SMART_GET_VERSION \
  CTL_CODE(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS)

571
572
573
#define SMART_SEND_DRIVE_COMMAND \
  CTL_CODE(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)

574
575
576
#define SMART_RCV_DRIVE_DATA \
  CTL_CODE(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)

577
578
579
ASSERT_CONST(SMART_GET_VERSION       , 0x074080);
ASSERT_CONST(SMART_SEND_DRIVE_COMMAND, 0x07c084);
ASSERT_CONST(SMART_RCV_DRIVE_DATA    , 0x07c088);
580
581
582
583

#define SMART_CYL_LOW  0x4F
#define SMART_CYL_HI   0xC2

584

585
586
587
#pragma pack(1)

typedef struct _GETVERSIONOUTPARAMS {
588
589
590
591
592
593
  UCHAR  bVersion;
  UCHAR  bRevision;
  UCHAR  bReserved;
  UCHAR  bIDEDeviceMap;
  ULONG  fCapabilities;
  ULONG  dwReserved[4];
594
595
} GETVERSIONOUTPARAMS, *PGETVERSIONOUTPARAMS, *LPGETVERSIONOUTPARAMS;

596
597
ASSERT_SIZEOF(GETVERSIONOUTPARAMS, 24);

598
599
600
601

#define SMART_VENDOR_3WARE      0x13C1  // identifies 3ware specific parameters

typedef struct _GETVERSIONINPARAMS_EX {
602
603
604
605
606
607
608
609
610
  BYTE    bVersion;
  BYTE    bRevision;
  BYTE    bReserved;
  BYTE    bIDEDeviceMap;
  DWORD   fCapabilities;
  DWORD   dwDeviceMapEx;  // 3ware specific: RAID drive bit map
  WORD    wIdentifier;    // Vendor specific identifier
  WORD    wControllerId;  // 3ware specific: Controller ID (0,1,...)
  ULONG   dwReserved[2];
611
612
613
614
615
} GETVERSIONINPARAMS_EX, *PGETVERSIONINPARAMS_EX, *LPGETVERSIONINPARAMS_EX;

ASSERT_SIZEOF(GETVERSIONINPARAMS_EX, sizeof(GETVERSIONOUTPARAMS));


616
typedef struct _IDEREGS {
617
618
619
620
621
622
623
624
  UCHAR  bFeaturesReg;
  UCHAR  bSectorCountReg;
  UCHAR  bSectorNumberReg;
  UCHAR  bCylLowReg;
  UCHAR  bCylHighReg;
  UCHAR  bDriveHeadReg;
  UCHAR  bCommandReg;
  UCHAR  bReserved;
625
626
627
} IDEREGS, *PIDEREGS, *LPIDEREGS;

typedef struct _SENDCMDINPARAMS {
628
629
630
631
632
633
  ULONG  cBufferSize;
  IDEREGS  irDriveRegs;
  UCHAR  bDriveNumber;
  UCHAR  bReserved[3];
  ULONG  dwReserved[4];
  UCHAR  bBuffer[1];
634
635
} SENDCMDINPARAMS, *PSENDCMDINPARAMS, *LPSENDCMDINPARAMS;

636
637
ASSERT_SIZEOF(SENDCMDINPARAMS, 32+1);

638
typedef struct _SENDCMDINPARAMS_EX {
639
640
641
642
643
644
645
  DWORD   cBufferSize;
  IDEREGS irDriveRegs;
  BYTE    bDriveNumber;
  BYTE    bPortNumber;   // 3ware specific: port number
  WORD    wIdentifier;   // Vendor specific identifier
  DWORD   dwReserved[4];
  BYTE    bBuffer[1];
646
647
648
649
650
} SENDCMDINPARAMS_EX, *PSENDCMDINPARAMS_EX, *LPSENDCMDINPARAMS_EX;

ASSERT_SIZEOF(SENDCMDINPARAMS_EX, sizeof(SENDCMDINPARAMS));


651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/* DRIVERSTATUS.bDriverError constants (just for info, not used)
#define SMART_NO_ERROR                    0
#define SMART_IDE_ERROR                   1
#define SMART_INVALID_FLAG                2
#define SMART_INVALID_COMMAND             3
#define SMART_INVALID_BUFFER              4
#define SMART_INVALID_DRIVE               5
#define SMART_INVALID_IOCTL               6
#define SMART_ERROR_NO_MEM                7
#define SMART_INVALID_REGISTER            8
#define SMART_NOT_SUPPORTED               9
#define SMART_NO_IDE_DEVICE               10
*/

typedef struct _DRIVERSTATUS {
666
667
668
669
  UCHAR  bDriverError;
  UCHAR  bIDEError;
  UCHAR  bReserved[2];
  ULONG  dwReserved[2];
670
671
672
} DRIVERSTATUS, *PDRIVERSTATUS, *LPDRIVERSTATUS;

typedef struct _SENDCMDOUTPARAMS {
673
674
675
  ULONG  cBufferSize;
  DRIVERSTATUS  DriverStatus;
  UCHAR  bBuffer[1];
676
677
} SENDCMDOUTPARAMS, *PSENDCMDOUTPARAMS, *LPSENDCMDOUTPARAMS;

678
679
ASSERT_SIZEOF(SENDCMDOUTPARAMS, 16+1);

680
681
682
683
684
685
686
#pragma pack()


/////////////////////////////////////////////////////////////////////////////

static void print_ide_regs(const IDEREGS * r, int out)
{
687
688
689
  pout("%s=0x%02x,%s=0x%02x, SC=0x%02x, SN=0x%02x, CL=0x%02x, CH=0x%02x, SEL=0x%02x\n",
  (out?"STS":"CMD"), r->bCommandReg, (out?"ERR":" FR"), r->bFeaturesReg,
  r->bSectorCountReg, r->bSectorNumberReg, r->bCylLowReg, r->bCylHighReg, r->bDriveHeadReg);
690
691
}

692
693
static void print_ide_regs_io(const IDEREGS * ri, const IDEREGS * ro)
{
694
695
696
697
  pout("    Input : "); print_ide_regs(ri, 0);
  if (ro) {
    pout("    Output: "); print_ide_regs(ro, 1);
  }
698
}
699
700
701

/////////////////////////////////////////////////////////////////////////////

702
703
// call SMART_GET_VERSION, return device map or -1 on error

704
static int smart_get_version(HANDLE hdevice, GETVERSIONINPARAMS_EX * ata_version_ex = 0)
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
  GETVERSIONOUTPARAMS vers; memset(&vers, 0, sizeof(vers));
  const GETVERSIONINPARAMS_EX & vers_ex = (const GETVERSIONINPARAMS_EX &)vers;
  DWORD num_out;

  if (!DeviceIoControl(hdevice, SMART_GET_VERSION,
    NULL, 0, &vers, sizeof(vers), &num_out, NULL)) {
    if (con->reportataioctl)
      pout("  SMART_GET_VERSION failed, Error=%ld\n", GetLastError());
    errno = ENOSYS;
    return -1;
  }
  assert(num_out == sizeof(GETVERSIONOUTPARAMS));

  if (con->reportataioctl > 1) {
    pout("  SMART_GET_VERSION suceeded, bytes returned: %lu\n"
         "    Vers = %d.%d, Caps = 0x%lx, DeviceMap = 0x%02x\n",
      num_out, vers.bVersion, vers.bRevision,
      vers.fCapabilities, vers.bIDEDeviceMap);
    if (vers_ex.wIdentifier == SMART_VENDOR_3WARE)
      pout("    Identifier = %04x(3WARE), ControllerId=%u, DeviceMapEx = 0x%08lx\n",
      vers_ex.wIdentifier, vers_ex.wControllerId, vers_ex.dwDeviceMapEx);
  }

  if (ata_version_ex)
    *ata_version_ex = vers_ex;

  // TODO: Check vers.fCapabilities here?
  return vers.bIDEDeviceMap;
734
735
736
}


737
738
// call SMART_* ioctl

739
static int smart_ioctl(HANDLE hdevice, int drive, IDEREGS * regs, char * data, unsigned datasize, int port)
740
{
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
  SENDCMDINPARAMS inpar;
  SENDCMDINPARAMS_EX & inpar_ex = (SENDCMDINPARAMS_EX &)inpar;

  unsigned char outbuf[sizeof(SENDCMDOUTPARAMS)-1 + 512];
  const SENDCMDOUTPARAMS * outpar;
  DWORD code, num_out;
  unsigned int size_out;
  const char * name;

  memset(&inpar, 0, sizeof(inpar));
  inpar.irDriveRegs = *regs;
  // drive is set to 0-3 on Win9x only
  inpar.irDriveRegs.bDriveHeadReg = 0xA0 | ((drive & 1) << 4);
  inpar.bDriveNumber = drive;

  if (port >= 0) {
    // Set RAID port
    inpar_ex.wIdentifier = SMART_VENDOR_3WARE;
    inpar_ex.bPortNumber = port;
  }

762
  if (datasize == 512) {
763
764
765
    code = SMART_RCV_DRIVE_DATA; name = "SMART_RCV_DRIVE_DATA";
    inpar.cBufferSize = size_out = 512;
  }
766
  else if (datasize == 0) {
767
768
769
770
771
772
773
    code = SMART_SEND_DRIVE_COMMAND; name = "SMART_SEND_DRIVE_COMMAND";
    if (regs->bFeaturesReg == ATA_SMART_STATUS)
      size_out = sizeof(IDEREGS); // ioctl returns new IDEREGS as data
      // Note: cBufferSize must be 0 on Win9x
    else
      size_out = 0;
  }
774
775
776
777
  else {
    errno = EINVAL;
    return -1;
  }
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

  memset(&outbuf, 0, sizeof(outbuf));

  if (!DeviceIoControl(hdevice, code, &inpar, sizeof(SENDCMDINPARAMS)-1,
    outbuf, sizeof(SENDCMDOUTPARAMS)-1 + size_out, &num_out, NULL)) {
    // CAUTION: DO NOT change "regs" Parameter in this case, see ata_command_interface()
    long err = GetLastError();
    if (con->reportataioctl && (err != ERROR_INVALID_PARAMETER || con->reportataioctl > 1)) {
      pout("  %s failed, Error=%ld\n", name, err);
      print_ide_regs_io(regs, NULL);
    }
    errno = (   err == ERROR_INVALID_FUNCTION/*9x*/
             || err == ERROR_INVALID_PARAMETER/*NT/2K/XP*/
             || err == ERROR_NOT_SUPPORTED ? ENOSYS : EIO);
    return -1;
  }
  // NOTE: On Win9x, inpar.irDriveRegs now contains the returned regs

  outpar = (const SENDCMDOUTPARAMS *)outbuf;

  if (outpar->DriverStatus.bDriverError) {
    if (con->reportataioctl) {
      pout("  %s failed, DriverError=0x%02x, IDEError=0x%02x\n", name,
        outpar->DriverStatus.bDriverError, outpar->DriverStatus.bIDEError);
      print_ide_regs_io(regs, NULL);
    }
    errno = (!outpar->DriverStatus.bIDEError ? ENOSYS : EIO);
    return -1;
  }

  if (con->reportataioctl > 1) {
    pout("  %s suceeded, bytes returned: %lu (buffer %lu)\n", name,
      num_out, outpar->cBufferSize);
    print_ide_regs_io(regs, (regs->bFeaturesReg == ATA_SMART_STATUS ?
      (const IDEREGS *)(outpar->bBuffer) : NULL));
  }

  if (datasize)
    memcpy(data, outpar->bBuffer, 512);
  else if (regs->bFeaturesReg == ATA_SMART_STATUS) {
818
    if (nonempty(outpar->bBuffer, sizeof(IDEREGS)))
819
820
821
822
823
824
825
826
827
      *regs = *(const IDEREGS *)(outpar->bBuffer);
    else {  // Workaround for driver not returning regs
      if (con->reportataioctl)
        pout("  WARNING: driver does not return ATA registers in output buffer!\n");
      *regs = inpar.irDriveRegs;
    }
  }

  return 0;
828
829
830
831
832
}


/////////////////////////////////////////////////////////////////////////////

833
// IDE PASS THROUGH (2000, XP, undocumented)
834
835
836
837
838
839
840
841
842
843
//
// Based on WinATA.cpp, 2002 c't/Matthias Withopf
// ftp://ftp.heise.de/pub/ct/listings/0207-218.zip

#define FILE_DEVICE_CONTROLLER  4
#define IOCTL_SCSI_BASE         FILE_DEVICE_CONTROLLER

#define IOCTL_IDE_PASS_THROUGH \
  CTL_CODE(IOCTL_SCSI_BASE, 0x040A, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)

844
845
ASSERT_CONST(IOCTL_IDE_PASS_THROUGH, 0x04d028);

846
847
848
#pragma pack(1)

typedef struct {
849
850
851
  IDEREGS IdeReg;
  ULONG   DataBufferSize;
  UCHAR   DataBuffer[1];
852
853
} ATA_PASS_THROUGH;

854
855
ASSERT_SIZEOF(ATA_PASS_THROUGH, 12+1);

856
857
858
859
860
861
#pragma pack()


/////////////////////////////////////////////////////////////////////////////

static int ide_pass_through_ioctl(HANDLE hdevice, IDEREGS * regs, char * data, unsigned datasize)
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
{
  if (datasize > 512) {
    errno = EINVAL;
    return -1;
  }
  unsigned int size = sizeof(ATA_PASS_THROUGH)-1 + datasize;
  ATA_PASS_THROUGH * buf = (ATA_PASS_THROUGH *)VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
  DWORD num_out;
  const unsigned char magic = 0xcf;

  if (!buf) {
    errno = ENOMEM;
    return -1;
  }

  buf->IdeReg = *regs;
  buf->DataBufferSize = datasize;
  if (datasize)
    buf->DataBuffer[0] = magic;

  if (!DeviceIoControl(hdevice, IOCTL_IDE_PASS_THROUGH,
    buf, size, buf, size, &num_out, NULL)) {
    long err = GetLastError();
    if (con->reportataioctl) {
      pout("  IOCTL_IDE_PASS_THROUGH failed, Error=%ld\n", err);
      print_ide_regs_io(regs, NULL);
    }
    VirtualFree(buf, 0, MEM_RELEASE);
    errno = (err == ERROR_INVALID_FUNCTION || err == ERROR_NOT_SUPPORTED ? ENOSYS : EIO);
    return -1;
  }

  // Check ATA status
  if (buf->IdeReg.bCommandReg/*Status*/ & 0x01) {
    if (con->reportataioctl) {
      pout("  IOCTL_IDE_PASS_THROUGH command failed:\n");
      print_ide_regs_io(regs, &buf->IdeReg);
    }
    VirtualFree(buf, 0, MEM_RELEASE);
    errno = EIO;
    return -1;
  }

  // Check and copy data
  if (datasize) {
    if (   num_out != size
        || (buf->DataBuffer[0] == magic && !nonempty(buf->DataBuffer+1, datasize-1))) {
      if (con->reportataioctl) {
        pout("  IOCTL_IDE_PASS_THROUGH output data missing (%lu, %lu)\n",
          num_out, buf->DataBufferSize);
        print_ide_regs_io(regs, &buf->IdeReg);
      }
      VirtualFree(buf, 0, MEM_RELEASE);
      errno = EIO;
      return -1;
    }
    memcpy(data, buf->DataBuffer, datasize);
  }

  if (con->reportataioctl > 1) {
    pout("  IOCTL_IDE_PASS_THROUGH suceeded, bytes returned: %lu (buffer %lu)\n",
      num_out, buf->DataBufferSize);
    print_ide_regs_io(regs, &buf->IdeReg);
  }
  *regs = buf->IdeReg;

  // Caution: VirtualFree() fails if parameter "dwSize" is nonzero
  VirtualFree(buf, 0, MEM_RELEASE);
  return 0;
931
932
933
}


934
935
936
937
938
/////////////////////////////////////////////////////////////////////////////

// ATA PASS THROUGH (Win2003, XP SP2)

#define IOCTL_ATA_PASS_THROUGH \
939
  CTL_CODE(IOCTL_SCSI_BASE, 0x040B, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
940
941
942
943

ASSERT_CONST(IOCTL_ATA_PASS_THROUGH, 0x04d02c);

typedef struct _ATA_PASS_THROUGH_EX {
944
945
946
947
948
949
950
951
952
953
954
955
  USHORT  Length;
  USHORT  AtaFlags;
  UCHAR  PathId;
  UCHAR  TargetId;
  UCHAR  Lun;
  UCHAR  ReservedAsUchar;
  ULONG  DataTransferLength;
  ULONG  TimeOutValue;
  ULONG  ReservedAsUlong;
  ULONG/*_PTR*/ DataBufferOffset;
  UCHAR  PreviousTaskFile[8];
  UCHAR  CurrentTaskFile[8];
956
957
958
959
960
961
962
963
} ATA_PASS_THROUGH_EX, *PATA_PASS_THROUGH_EX;

ASSERT_SIZEOF(ATA_PASS_THROUGH_EX, 40);

#define ATA_FLAGS_DRDY_REQUIRED 0x01
#define ATA_FLAGS_DATA_IN       0x02
#define ATA_FLAGS_DATA_OUT      0x04
#define ATA_FLAGS_48BIT_COMMAND 0x08
964
965
#define ATA_FLAGS_USE_DMA       0x10
#define ATA_FLAGS_NO_MULTIPLE   0x20 // Vista
966
967
968
969


/////////////////////////////////////////////////////////////////////////////

970
971
972
973
974
975
976
977
978
// Warning:
// IOCTL_ATA_PASS_THROUGH[_DIRECT] can only handle one interrupt/DRQ data
// transfer per command. Therefore, multi-sector transfers are only supported
// for the READ/WRITE MULTIPLE [EXT] commands. Other commands like READ/WRITE SECTORS
// or READ/WRITE LOG EXT work only with single sector transfers.
// The latter are supported on Vista (only) through new ATA_FLAGS_NO_MULTIPLE.
// See:
// http://social.msdn.microsoft.com/Forums/en-US/storageplatformata/thread/eb408507-f221-455b-9bbb-d1069b29c4da

979
static int ata_pass_through_ioctl(HANDLE hdevice, IDEREGS * regs, IDEREGS * prev_regs, char * data, int datasize)
980
{
981
982
  const int max_sectors = 32; // TODO: Allocate dynamic buffer

983
984
985
  typedef struct {
    ATA_PASS_THROUGH_EX apt;
    ULONG Filler;
986
    UCHAR ucDataBuf[max_sectors * 512];
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  } ATA_PASS_THROUGH_EX_WITH_BUFFERS;

  const unsigned char magic = 0xcf;

  ATA_PASS_THROUGH_EX_WITH_BUFFERS ab; memset(&ab, 0, sizeof(ab));
  ab.apt.Length = sizeof(ATA_PASS_THROUGH_EX);
  //ab.apt.PathId = 0;
  //ab.apt.TargetId = 0;
  //ab.apt.Lun = 0;
  ab.apt.TimeOutValue = 10;
  unsigned size = offsetof(ATA_PASS_THROUGH_EX_WITH_BUFFERS, ucDataBuf);
  ab.apt.DataBufferOffset = size;

  if (datasize > 0) {
For faster browsing, not all history is shown. View entire blame