4 * Home page of code is: http://www.smartmontools.org
6 * Copyright (C) 2004-8 Geoffrey Keating <geoffk@geoffk.org>
7 * Copyright (C) 2014 Alex Samorukov <samm@os2.kiev.ua>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2, or (at your option)
14 * You should have received a copy of the GNU General Public License
15 * along with smartmontools. If not, see <http://www.gnu.org/licenses/>.
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/mach_init.h>
25 #include <sys/utsname.h>
26 #include <IOKit/IOCFPlugIn.h>
27 #include <IOKit/IOKitLib.h>
28 #include <IOKit/IOReturn.h>
29 #include <IOKit/IOBSD.h>
30 #include <IOKit/storage/IOBlockStorageDevice.h>
31 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
32 #include <IOKit/storage/IOMedia.h>
33 #include <IOKit/storage/ata/IOATAStorageDefines.h>
34 #include <IOKit/storage/ata/ATASMARTLib.h>
35 #include <CoreFoundation/CoreFoundation.h>
43 #include "os_darwin.h"
44 #include "dev_interface.h"
46 #define ARGUSED(x) ((void)(x))
47 // Needed by '-V' option (CVS versioning) of smartd/smartctl
48 const char *os_darwin_cpp_cvsid
="$Id: os_darwin.cpp 4552 2017-10-11 10:11:35Z samm2 $" \
49 ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_DARWIN_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID
;
51 // examples for smartctl
52 static const char smartctl_examples
[] =
53 "=================================================== SMARTCTL EXAMPLES =====\n\n"
54 " smartctl -a disk0 (Prints all SMART information)\n\n"
55 " smartctl -t long /dev/disk0 (Executes extended disk self-test)\n\n"
56 #ifdef HAVE_GETOPT_LONG
57 " smartctl --smart=on --saveauto=on /dev/rdisk0 (Enables SMART on first disk)\n\n"
58 " smartctl --attributes --log=selftest --quietmode=errorsonly /dev/disk0\n"
59 " (Prints Self-Test & Attribute errors)\n\n"
61 " smartctl -s on -S on /dev/rdisk0 (Enables SMART on first disk)\n\n"
62 " smartctl -A -l selftest -q errorsonly /dev/disk0\n"
63 " (Prints Self-Test & Attribute errors)\n\n"
65 " smartctl -a IOService:/MacRISC2PE/pci@f4000000/AppleMacRiscPCI/ata-6@D/AppleKauaiATA/ATADeviceNub@0/IOATABlockStorageDriver/IOATABlockStorageDevice\n"
66 " (You can use IOService: ...)\n\n"
67 " smartctl -c IODeviceTree:/pci@f4000000/ata-6@D/@0:0\n"
68 " (... Or IODeviceTree:)\n"
72 // Information that we keep about each device.
76 IOCFPlugInInterface
**plugin
;
77 IOATASMARTInterface
**smartIf
; // ATA devices
78 IONVMeSMARTInterface
**smartIfNVMe
;
81 const char * dev_darwin_cpp_cvsid
= "$Id: os_darwin.cpp 4552 2017-10-11 10:11:35Z samm2 $"
82 DEV_INTERFACE_H_CVSID
;
84 /////////////////////////////////////////////////////////////////////////////
86 namespace os
{ // No need to publish anything, name provided for Doxygen
88 /////////////////////////////////////////////////////////////////////////////
89 /// Implement shared open/close routines with old functions.
91 class darwin_smart_device
92 : virtual public /*implements*/ smart_device
95 explicit darwin_smart_device(const char * mode
)
96 : smart_device(never_called
),
97 m_fd(-1), m_mode(mode
) { }
99 virtual ~darwin_smart_device() throw();
101 virtual bool is_open() const;
105 virtual bool close();
108 /// Return filedesc for derived classes.
113 int m_fd
; ///< filedesc, -1 if not open.
114 const char * m_mode
; ///< Mode string for deviceopen().
118 darwin_smart_device::~darwin_smart_device() throw()
121 darwin_smart_device::close();
124 bool darwin_smart_device::is_open() const
129 // Determine whether 'dev' is a SMART-capable device.
130 static bool is_smart_capable (io_object_t dev
, const char * type
) {
131 CFTypeRef smartCapableKey
= NULL
;
132 CFDictionaryRef diskChars
;
134 // If the device has kIOPropertySMARTCapableKey, then it's capable,
135 // no matter what it looks like.
136 if (!strcmp("ATA", type
)) {
137 smartCapableKey
= IORegistryEntryCreateCFProperty
138 (dev
, CFSTR (kIOPropertySMARTCapableKey
),
139 kCFAllocatorDefault
, 0);
142 else if (!strcmp("NVME", type
)) {
143 smartCapableKey
= IORegistryEntryCreateCFProperty
144 (dev
, CFSTR (kIOPropertyNVMeSMARTCapableKey
),
145 kCFAllocatorDefault
, 0);
150 CFRelease (smartCapableKey
);
154 // If it's an kIOATABlockStorageDeviceClass then we're successful
155 // only if its ATA features indicate it supports SMART.
156 // This will be broken for NVMe, however it is not needed
157 if (IOObjectConformsTo (dev
, kIOATABlockStorageDeviceClass
)
158 && (diskChars
= (CFDictionaryRef
)IORegistryEntryCreateCFProperty
159 (dev
, CFSTR (kIOPropertyDeviceCharacteristicsKey
),
160 kCFAllocatorDefault
, kNilOptions
)) != NULL
)
162 CFNumberRef diskFeatures
= NULL
;
163 UInt32 ataFeatures
= 0;
165 if (CFDictionaryGetValueIfPresent (diskChars
, CFSTR ("ATA Features"),
166 (const void **)&diskFeatures
))
167 CFNumberGetValue (diskFeatures
, kCFNumberLongType
,
169 CFRelease (diskChars
);
171 CFRelease (diskFeatures
);
173 return (ataFeatures
& kIOATAFeatureSMART
) != 0;
178 bool darwin_smart_device::open()
180 // Acceptable device names are:
189 const char *pathname
= get_dev_name();
190 char *type
= const_cast<char*>(m_mode
);
192 if (!(strcmp("ATA", type
) || strcmp("NVME", type
)))
198 // Find a free device number.
199 for (devnum
= 0; devnum
< sizeof (devices
) / sizeof (devices
[0]); devnum
++)
200 if (! devices
[devnum
].ioob
)
202 if (devnum
== sizeof (devices
) / sizeof (devices
[0]))
209 if (strncmp (pathname
, "/dev/rdisk", 10) == 0)
210 devname
= pathname
+ 6;
211 else if (strncmp (pathname
, "/dev/disk", 9) == 0)
212 devname
= pathname
+ 5;
213 else if (strncmp (pathname
, "disk", 4) == 0)
214 // allow user to just say 'disk0'
217 // Find the device. This part should be the same for the NVMe and ATA
220 CFMutableDictionaryRef matcher
;
221 matcher
= IOBSDNameMatching (kIOMasterPortDefault
, 0, devname
);
222 disk
= IOServiceGetMatchingService (kIOMasterPortDefault
, matcher
);
226 disk
= IORegistryEntryFromPath (kIOMasterPortDefault
, pathname
);
233 // Find a SMART-capable driver which is a parent of this device.
234 while (! is_smart_capable (disk
, type
))
237 io_object_t prevdisk
= disk
;
239 // Find this device's parent and try again.
240 err
= IORegistryEntryGetParentEntry (disk
, kIOServicePlane
, &disk
);
241 if (err
!= kIOReturnSuccess
|| ! disk
)
244 IOObjectRelease (prevdisk
);
249 devices
[devnum
].ioob
= disk
;
254 devices
[devnum
].plugin
= NULL
;
255 devices
[devnum
].smartIf
= NULL
;
256 devices
[devnum
].smartIfNVMe
= NULL
;
258 CFUUIDRef pluginType
= NULL
;
259 CFUUIDRef smartInterfaceId
= NULL
;
260 void ** SMARTptr
= NULL
;
262 if (!strcmp("ATA", type
)) {
263 pluginType
= kIOATASMARTUserClientTypeID
;
264 smartInterfaceId
= kIOATASMARTInterfaceID
;
265 SMARTptr
= (void **)&devices
[devnum
].smartIf
;
267 else if (!strcmp("NVME", type
)) {
268 pluginType
= kIONVMeSMARTUserClientTypeID
;
269 smartInterfaceId
= kIONVMeSMARTInterfaceID
;
270 SMARTptr
= (void **)&devices
[devnum
].smartIfNVMe
;
273 // Create an interface to the ATA SMART library.
274 if (IOCreatePlugInInterfaceForService (disk
,
276 kIOCFPlugInInterfaceID
,
277 &devices
[devnum
].plugin
,
278 &dummy
) == kIOReturnSuccess
)
279 (*devices
[devnum
].plugin
)->QueryInterface
280 (devices
[devnum
].plugin
,
281 CFUUIDGetUUIDBytes ( smartInterfaceId
),
284 return set_err(ENOSYS
, "IOCreatePlugInInterfaceForService failed");
290 set_err((errno
==ENOENT
|| errno
==ENOTDIR
) ? ENODEV
: errno
);
296 bool darwin_smart_device::close()
298 int fd
= m_fd
; m_fd
= -1;
299 if (devices
[fd
].smartIf
)
300 (*devices
[fd
].smartIf
)->Release (devices
[fd
].smartIf
);
301 if (devices
[fd
].smartIfNVMe
)
302 (*devices
[fd
].smartIfNVMe
)->Release (devices
[fd
].smartIfNVMe
);
303 if (devices
[fd
].plugin
)
304 IODestroyPlugInInterface (devices
[fd
].plugin
);
305 IOObjectRelease (devices
[fd
].ioob
);
306 devices
[fd
].ioob
= MACH_PORT_NULL
;
310 // makes a list of ATA or SCSI devices for the DEVICESCAN directive of
311 // smartd. Returns number N of devices, or -1 if out of
312 // memory. Allocates N+1 arrays: one of N pointers (devlist); the
313 // other N arrays each contain null-terminated character strings. In
314 // the case N==0, no arrays are allocated because the array of 0
315 // pointers has zero length, equivalent to calling malloc(0).
316 static int make_device_names (char*** devlist
, const char* name
) {
319 io_object_t device
= MACH_PORT_NULL
;
323 if (!(strcmp("ATA", name
) || strcmp("NVME", name
))) {
327 err
= IOServiceGetMatchingServices
328 (kIOMasterPortDefault
, IOServiceMatching (kIOBlockStorageDeviceClass
), &i
);
329 if (err
!= kIOReturnSuccess
)
332 // Count the devices.
334 while ((device
= IOIteratorNext (i
)) != MACH_PORT_NULL
) {
335 if (is_smart_capable (device
, name
))
337 IOObjectRelease (device
);
340 // Create an array of service names.
344 *devlist
= (char**)calloc (result
, sizeof (char *));
346 while ((device
= IOIteratorNext (i
)) != MACH_PORT_NULL
) {
347 if (is_smart_capable (device
, name
))
350 IORegistryEntryGetPath(device
, kIOServicePlane
, devName
);
351 (*devlist
)[index
] = strdup (devName
);
352 if (! (*devlist
)[index
])
356 IOObjectRelease (device
);
363 if (device
!= MACH_PORT_NULL
)
364 IOObjectRelease (device
);
368 for (index
= 0; index
< result
; index
++)
369 if ((*devlist
)[index
])
370 free ((*devlist
)[index
]);
373 if(!result
) // no devs found
379 /////////////////////////////////////////////////////////////////////////////
380 /// Implement standard ATA support
382 class darwin_ata_device
383 : public /*implements*/ ata_device
,
384 public /*extends*/ darwin_smart_device
387 darwin_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
388 virtual bool ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
);
391 // virtual int ata_command_interface(smart_command_set command, int select, char * data);
394 darwin_ata_device::darwin_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
)
395 : smart_device(intf
, dev_name
, "ata", req_type
),
396 darwin_smart_device("ATA")
400 bool darwin_ata_device::ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
)
402 if (!ata_cmd_is_ok(in
,
403 true, // data_out_support
404 true, // multi_sector_support
405 false) // not supported by API
410 char * data
= (char *)in
.buffer
;
412 IOATASMARTInterface
**ifp
= devices
[fd
].smartIf
;
413 IOATASMARTInterface
*smartIf
;
415 int timeoutCount
= 5;
421 clear_err(); errno
= 0;
423 switch (in
.in_regs
.command
) {
424 case ATA_IDENTIFY_DEVICE
:
427 err
= smartIf
->GetATAIdentifyData (ifp
, data
, 512, &dummy
);
428 if (err
!= kIOReturnSuccess
&& err
!= kIOReturnTimeout
429 && err
!= kIOReturnNotResponding
)
430 printf ("identify failed: %#x\n", (unsigned) rc
);
431 if (err
== kIOReturnSuccess
&& isbigendian())
434 /* The system has already byte-swapped, undo it. */
435 for (i
= 0; i
< 256; i
+=2)
440 case ATA_IDENTIFY_PACKET_DEVICE
:
441 case ATA_CHECK_POWER_MODE
:
446 switch (in
.in_regs
.features
) {
447 case ATA_SMART_READ_VALUES
:
448 err
= smartIf
->SMARTReadData (ifp
, (ATASMARTData
*)data
);
450 case ATA_SMART_READ_THRESHOLDS
:
451 err
= smartIf
->SMARTReadDataThresholds (ifp
,
452 (ATASMARTDataThresholds
*)data
);
454 case ATA_SMART_READ_LOG_SECTOR
:
455 err
= smartIf
->SMARTReadLogAtAddress (ifp
, in
.in_regs
.lba_low
, data
, 512 * in
.in_regs
.sector_count
);
457 case ATA_SMART_WRITE_LOG_SECTOR
:
458 err
= smartIf
->SMARTWriteLogAtAddress (ifp
, in
.in_regs
.lba_low
, data
, 512 * in
.in_regs
.sector_count
);
460 case ATA_SMART_ENABLE
:
461 case ATA_SMART_DISABLE
:
462 err
= smartIf
->SMARTEnableDisableOperations (ifp
, in
.in_regs
.features
== ATA_SMART_ENABLE
);
464 case ATA_SMART_STATUS
:
465 if (in
.out_needed
.lba_high
) // statuscheck
468 err
= smartIf
->SMARTReturnStatus (ifp
, &is_failing
);
469 if (err
== kIOReturnSuccess
&& is_failing
) {
470 err
= -1; // thresholds exceeded condition
471 out
.out_regs
.lba_high
= 0x2c; out
.out_regs
.lba_mid
= 0xf4;
474 out
.out_regs
.lba_high
= 0xc2; out
.out_regs
.lba_mid
= 0x4f;
479 case ATA_SMART_AUTOSAVE
:
480 err
= smartIf
->SMARTEnableDisableAutosave (ifp
,
481 (in
.in_regs
.sector_count
== 241 ? true : false));
483 case ATA_SMART_IMMEDIATE_OFFLINE
:
484 select
= in
.in_regs
.lba_low
;
485 if (select
!= SHORT_SELF_TEST
&& select
!= EXTEND_SELF_TEST
)
488 return set_err(ENOSYS
, "Unsupported SMART self-test mode");
490 err
= smartIf
->SMARTExecuteOffLineImmediate (ifp
,
491 select
== EXTEND_SELF_TEST
);
493 case ATA_SMART_AUTO_OFFLINE
:
494 return set_err(ENOSYS
, "SMART command not supported");
496 return set_err(ENOSYS
, "Unknown SMART command");
500 return set_err(ENOSYS
, "Non-SMART commands not implemented");
502 } while ((err
== kIOReturnTimeout
|| err
== kIOReturnNotResponding
)
503 && timeoutCount
-- > 0);
504 if (err
== kIOReturnExclusiveAccess
)
506 rc
= err
== kIOReturnSuccess
? 0 : -1;
515 /////////////////////////////////////////////////////////////////////////////
516 /// Implement platform interface
518 class darwin_smart_interface
519 : public /*implements*/ smart_interface
522 virtual std::string
get_os_version_str();
524 virtual std::string
get_app_examples(const char * appname
);
526 virtual bool scan_smart_devices(smart_device_list
& devlist
, const char * type
,
527 const char * pattern
= 0);
530 virtual ata_device
* get_ata_device(const char * name
, const char * type
);
532 virtual scsi_device
* get_scsi_device(const char * name
, const char * type
);
534 virtual nvme_device
* get_nvme_device(const char * name
, const char * type
,
537 virtual smart_device
* autodetect_smart_device(const char * name
);
541 /////////////////////////////////////////////////////////////////////////////
544 class darwin_nvme_device
545 : public /*implements*/ nvme_device
,
546 public /*extends*/ darwin_smart_device
549 darwin_nvme_device(smart_interface
* intf
, const char * dev_name
,
550 const char * req_type
, unsigned nsid
);
552 virtual bool nvme_pass_through(const nvme_cmd_in
& in
, nvme_cmd_out
& out
);
555 darwin_nvme_device::darwin_nvme_device(smart_interface
* intf
, const char * dev_name
,
556 const char * req_type
, unsigned nsid
)
557 : smart_device(intf
, dev_name
, "nvme", req_type
),
559 darwin_smart_device("NVME")
563 bool darwin_nvme_device::nvme_pass_through(const nvme_cmd_in
& in
, nvme_cmd_out
& out
)
567 IONVMeSMARTInterface
**ifp
= devices
[fd
].smartIfNVMe
;
568 IONVMeSMARTInterface
*smartIfNVMe
;
570 unsigned int page
= in
.cdw10
& 0xff;
575 // currently only GetIdentifyData and SMARTReadData are supported
577 case smartmontools::nvme_admin_identify
:
578 err
= smartIfNVMe
->GetIdentifyData(ifp
, (struct nvme_id_ctrl
*) in
.buffer
, in
.nsid
); // FIXME
580 case smartmontools::nvme_admin_get_log_page
:
582 err
= smartIfNVMe
->SMARTReadData(ifp
, (struct nvme_smart_log
*) in
.buffer
);
583 else /* GetLogPage() is not working yet */
584 return set_err(ENOSYS
, "NVMe admin command:0x%02x/page:0x%02x is not supported",
588 return set_err(ENOSYS
, "NVMe admin command 0x%02x is not supported", in
.opcode
);
592 //////////////////////////////////////////////////////////////////////
594 std::string
darwin_smart_interface::get_os_version_str()
596 // now we are just getting darwin runtime version, to get OSX version more things needs to be done, see
597 // http://stackoverflow.com/questions/11072804/how-do-i-determine-the-os-version-at-runtime-in-os-x-or-ios-without-using-gesta
598 struct utsname osname
;
600 return strprintf("%s %s %s", osname
.sysname
, osname
.release
, osname
.machine
);
603 std::string
darwin_smart_interface::get_app_examples(const char * appname
)
605 if (!strcmp(appname
, "smartctl"))
606 return smartctl_examples
;
607 return ""; // ... so don't print again.
610 ata_device
* darwin_smart_interface::get_ata_device(const char * name
, const char * type
)
612 return new darwin_ata_device(this, name
, type
);
615 scsi_device
* darwin_smart_interface::get_scsi_device(const char *, const char *)
617 return 0; // scsi devices are not supported [yet]
620 nvme_device
* darwin_smart_interface::get_nvme_device(const char * name
, const char * type
,
623 return new darwin_nvme_device(this, name
, type
, nsid
);
626 smart_device
* darwin_smart_interface::autodetect_smart_device(const char * name
)
627 { // TODO - refactor as a function
628 // Acceptable device names are:
634 const char *devname
= NULL
;
637 if (strncmp (name
, "/dev/rdisk", 10) == 0)
639 else if (strncmp (name
, "/dev/disk", 9) == 0)
641 else if (strncmp (name
, "disk", 4) == 0)
642 // allow user to just say 'disk0'
644 // Find the device. This part should be the same for the NVMe and ATA
646 CFMutableDictionaryRef matcher
;
647 matcher
= IOBSDNameMatching (kIOMasterPortDefault
, 0, devname
);
648 disk
= IOServiceGetMatchingService (kIOMasterPortDefault
, matcher
);
651 disk
= IORegistryEntryFromPath (kIOMasterPortDefault
, name
);
656 io_registry_entry_t tmpdisk
=disk
;
659 while (! is_smart_capable (tmpdisk
, "ATA"))
662 io_object_t prevdisk
= tmpdisk
;
664 // Find this device's parent and try again.
665 err
= IORegistryEntryGetParentEntry (tmpdisk
, kIOServicePlane
, &tmpdisk
);
666 if (err
!= kIOReturnSuccess
|| ! tmpdisk
)
668 IOObjectRelease (prevdisk
);
673 return new darwin_ata_device(this, name
, "");
675 while (! is_smart_capable (tmpdisk
, "NVME"))
678 io_object_t prevdisk
= tmpdisk
;
680 // Find this device's parent and try again.
681 err
= IORegistryEntryGetParentEntry (tmpdisk
, kIOServicePlane
, &tmpdisk
);
682 if (err
!= kIOReturnSuccess
|| ! tmpdisk
)
684 IOObjectRelease (prevdisk
);
689 return new darwin_nvme_device(this, name
, "", 0);
691 // try ATA as a last option, for compatibility
692 return new darwin_ata_device(this, name
, "");
695 static void free_devnames(char * * devnames
, int numdevs
)
697 for (int i
= 0; i
< numdevs
; i
++)
702 bool darwin_smart_interface::scan_smart_devices(smart_device_list
& devlist
,
703 const char * type
, const char * pattern
/*= 0*/)
706 set_err(EINVAL
, "DEVICESCAN with pattern not implemented yet");
711 char * * atanames
= 0; int numata
= 0;
712 if (!type
|| !strcmp(type
, "ata")) {
713 numata
= make_device_names(&atanames
, "ATA");
719 char * * nvmenames
= 0; int numnvme
= 0;
721 #ifdef WITH_NVME_DEVICESCAN // TODO: Remove when NVMe support is no longer EXPERIMENTAL
726 !strcmp(type
, "nvme")) {
727 numnvme
= make_device_names(&nvmenames
, "NVME");
738 for (i
= 0; i
< numata
; i
++) {
739 ata_device
* atadev
= get_ata_device(atanames
[i
], type
);
741 devlist
.push_back(atadev
);
743 free_devnames(atanames
, numata
);
745 for (i
= 0; i
< numnvme
; i
++) {
746 nvme_device
* nvmedev
= get_nvme_device(nvmenames
[i
], type
, 0); // default nsid
748 devlist
.push_back(nvmedev
);
750 free_devnames(nvmenames
, numnvme
);
758 /////////////////////////////////////////////////////////////////////////////
759 /// Initialize platform interface and register with smi()
761 void smart_interface::init()
763 static os::darwin_smart_interface the_interface
;
764 smart_interface::set(&the_interface
);