forked from cellularmitosis/ADC-reference-library-2009-july
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlisting3.html
More file actions
executable file
·681 lines (553 loc) · 27.7 KB
/
Copy pathlisting3.html
File metadata and controls
executable file
·681 lines (553 loc) · 27.7 KB
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>SMARTQuery - /windowSMARTs.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/HardwareDrivers/index.html">Hardware & Drivers</a> > <a href="../../samplecode/HardwareDrivers/idxMassStorageDevices-date.html">Storage</a> > <A HREF="javascript:location.replace('index.html');">SMARTQuery</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">SMARTQuery</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/windowSMARTs.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/main.m</option>
<option value="listing2.html">/windowSMARTs.h</option>
<option value="listing3.html">/windowSMARTs.m</option></select>
</p>
</form>
<p><strong><a href="SMARTQuery.zip">Download Sample</a></strong> (“SMARTQuery.zip”, 35.0K)<BR>
<strong><a href="SMARTQuery.dmg">Download Sample</a></strong> (“SMARTQuery.dmg”, 92.0K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox"> /*
File:<windowSMARTs.m>
Abstract: <A demonstration of how to use S.M.A.R.T. monitoring>
Version: <1.0>
Disclaimer: IMPORTANT: This Apple software is supplied to you by
Apple Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2007 Apple Inc. All Rights Reserved.
*/
#import "windowSMARTs.h"
#include <ctype.h>
#include <stdio.h>
#include <sys/param.h>
#include <sys/time.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <mach/mach_init.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOReturn.h>
#include <IOKit/storage/ata/ATASMARTLib.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
#include <CoreFoundation/CoreFoundation.h>
#define kATADefaultSectorSize 512
@implementation windowSMARTs
#if defined(__BIG_ENDIAN__)
#define SwapASCIIHostToBig(x,y)
#elif defined(__LITTLE_ENDIAN__)
#define SwapASCIIHostToBig(x,y) SwapASCIIString( ( UInt16 * ) x,y)
#else
#error Unknown endianness.
#endif
// This constant comes from the SMART specification. Only 30 values are allowed in any of the structures.
#define kSMARTAttributeCount 30
typedef struct IOATASmartAttribute
{
UInt8 attributeId;
UInt16 flag;
UInt8 current;
UInt8 worst;
UInt8 rawvalue[6];
UInt8 reserv;
} __attribute__ ((packed)) IOATASmartAttribute;
typedef struct IOATASmartVendorSpecificData
{
UInt16 revisonNumber;
IOATASmartAttribute vendorAttributes [kSMARTAttributeCount];
} __attribute__ ((packed)) IOATASmartVendorSpecificData;
/* Vendor attribute of SMART Threshold */
typedef struct IOATASmartThresholdAttribute
{
UInt8 attributeId;
UInt8 ThresholdValue;
UInt8 Reserved[10];
} __attribute__ ((packed)) IOATASmartThresholdAttribute;
typedef struct IOATASmartVendorSpecificDataThresholds
{
UInt16 revisonNumber;
IOATASmartThresholdAttribute ThresholdEntries [kSMARTAttributeCount];
} __attribute__ ((packed)) IOATASmartVendorSpecificDataThresholds;
void SwapASCIIString(UInt16 *buffer, UInt16 length)
{
int index;
for ( index = 0; index < length / 2; index ++ ) {
buffer[index] = OSSwapInt16 ( buffer[index] );
}
}
-(int) VerifyIdentifyData: (UInt16 *) buffer
{
UInt8 checkSum = -1;
UInt32 index = 0;
UInt8 * ptr = ( UInt8 * ) buffer;
require_string(((buffer[255] & 0x00FF) == kChecksumValidCookie), ErrorExit, "WARNING: Identify data checksum cookie not found");
checkSum = 0;
for (index = 0; index < 512; index++)
checkSum += ptr[index];
ErrorExit:
return checkSum;
}
- (BOOL) PrintIdentifyData: ( IOATASMARTInterface **) smartInterface withResultsDict:(NSMutableDictionary *) smartResultsDict
{
IOReturn error = kIOReturnSuccess;
UInt8 * buffer = NULL;
UInt32 length = kATADefaultSectorSize;
UInt16 * words = NULL;
int checksum = 0;
BOOL isSMARTSupported = NO;
buffer = (UInt8 *) malloc(kATADefaultSectorSize);
require_string((buffer != NULL), ErrorExit, "malloc(kATADefaultSectorSize) failed");
bzero(buffer, kATADefaultSectorSize);
error = (*smartInterface)->GetATAIdentifyData( smartInterface,
buffer,
kATADefaultSectorSize,
&length );
require_string((error == kIOReturnSuccess), ErrorExit, "GetATAIdentifyData failed");
checksum = [self VerifyIdentifyData:( UInt16 * ) buffer];
require_string((checksum == 0), ErrorExit, "Identify data verified. Checksum is NOT correct");
// Terminate the strings with 0's
// This changes the identify data, so we MUST do this part last.
buffer[94] = 0;
buffer[40] = 0;
// Model number runs from byte 54 to 93 inclusive - byte 94 is set to
// zero to terminate that string.
SwapASCIIHostToBig (&buffer[54], 40);
[smartResultsDict setObject:[NSString stringWithCString:(char *)&buffer[54] encoding:NSUTF8StringEncoding] forKey:kWindowSMARTsModelKeyString];
// Now that we have made a deep copy of the model string, poke a 0 into byte 54
// in order to terminate the fw-vers string which runs from bytes 46 to 53 inclusive.
buffer[54] = 0;
SwapASCIIHostToBig (&buffer[46], 8);
[smartResultsDict setObject:[NSString stringWithCString:(char *)&buffer[46] encoding:NSUTF8StringEncoding] forKey:kWindowSMARTsFirmwareKeyString];
SwapASCIIHostToBig (&buffer[20], 20);
[smartResultsDict setObject:[NSString stringWithCString:(char *)&buffer[20] encoding:NSUTF8StringEncoding] forKey:kWindowSMARTsSerialNumberKeyString];
words = (UInt16 *) buffer;
isSMARTSupported = words[kATAIdentifyCommandSetSupported] & kATASupportsSMARTMask;
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsSMARTMask] forKey:kWindowSMARTsSMARTSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsWriteCacheMask] forKey:kWindowSMARTsWriteCacheSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsPowerManagementMask] forKey:kWindowSMARTsPMSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsCompactFlashMask] forKey:kWindowSMARTsCFSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsAdvancedPowerManagementMask] forKey:kWindowSMARTsAPMSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupports48BitAddressingMask] forKey:kWindowSMARTs48BitAddressingSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsFlushCacheMask] forKey:kWindowSMARTsFlushCacheCommandSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[kATAIdentifyCommandSetSupported] & kATASupportsFlushCacheExtendedMask] forKey:kWindowSMARTsFlushCacheExtCommandSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithInt:(words[kATAIdentifyQueueDepth] & 0x001F) + 1] forKey:kWindowSMARTsQueueDepthKeyString];
if ((words[76] != 0) && (words[76] != 0xFFFF)) {
[smartResultsDict setObject:[NSNumber numberWithBool:words[76] & (1 << 8)] forKey:kWindowSMARTsNCQSupportKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[78] & (1 << 3)] forKey:kWindowSMARTsDeviceInitiatedPMKeyString];
[smartResultsDict setObject:[NSNumber numberWithBool:words[76] & (1 << 9)] forKey:kWindowSMARTsHostInitiatedPMKeyString];
[smartResultsDict setObject:[NSNumber numberWithFloat:( words[76] & (1 << 2) ) ? 3.0 : 1.5] forKey:kWindowSMARTsInterfaceSpeedKeyString];
}
if (((words[kATAIdentifyCommandSetSupported2] & (1 << 1)) == 0) && ((words[76] & (1 << 8)) == 0)) {
require_string((words[kATAIdentifyQueueDepth] != 0), ErrorExit, "\n WARNING! Found inconsistency with queue depth!\n\n");
}
ErrorExit:
if (buffer)
free(buffer);
return isSMARTSupported;
}
-(void) PrintSMARTData:(IOATASMARTInterface **) smartInterface withResultsDict:(NSMutableDictionary *) smartResultsDict
{
IOReturn error = kIOReturnSuccess;
Boolean conditionExceeded = false;
ATASMARTData smartData;
IOATASmartVendorSpecificData smartDataVendorSpecifics;
ATASMARTDataThresholds smartThresholds;
IOATASmartVendorSpecificDataThresholds smartThresholdVendorSpecifics;
ATASMARTLogDirectory smartLogDirectory;
bzero(&smartData, sizeof(smartData));
bzero(&smartDataVendorSpecifics, sizeof(smartDataVendorSpecifics));
bzero(&smartThresholds, sizeof(smartThresholds));
bzero(&smartThresholdVendorSpecifics, sizeof(smartThresholdVendorSpecifics));
bzero(&smartLogDirectory, sizeof(smartLogDirectory));
// Default the results for safety.
[smartResultsDict setObject:[NSNumber numberWithBool:NO] forKey:kWindowSMARTsDeviceOkKeyString];
// Start by enabling S.M.A.R.T. reporting for this disk.
error = (*smartInterface)->SMARTEnableDisableOperations(smartInterface, true);
require_string((error == kIOReturnSuccess), ErrorExit, "SMARTEnableDisableOperations failed");
error = (*smartInterface)->SMARTEnableDisableAutosave(smartInterface, true);
require_string((error == kIOReturnSuccess), ErrorExit, "SMARTEnableDisableAutosave failed");
// In most cases, this value will be all that you require. As most of the
// S.M.A.R.T reporting attributes are vendor-specific, the only part you can
// always count on being implemented and accurate is the overall T.E.C
// (Threshold Exceeded Condition) status report.
error = (*smartInterface)->SMARTReturnStatus(smartInterface, &conditionExceeded);
require_string((error == kIOReturnSuccess), ErrorExit, "SMARTReturnStatus failed" );
if (!conditionExceeded)
[smartResultsDict setObject:[NSNumber numberWithBool:YES] forKey:kWindowSMARTsDeviceOkKeyString];
// NOTE:
// The rest of the diagnostics gathering involves using portions of the API that is considered
// optional for a drive vendor to implement. Most vendors now do, but be warned not to rely
// on it. In particular, the attribute codes are usually considered vendor specific and
// proprietary, although some codes (ie. drive temperature) are almost always present.
// Ask the device to start collecting S.M.A.R.T. data immediately. We are not asking
// for an extended test to be performed at this point
error = (*smartInterface)->SMARTExecuteOffLineImmediate (smartInterface, false);
if (error != kIOReturnSuccess)
printf("SMARTExecuteOffLineImmediate failed: %s(%x)\n", mach_error_string(error), error);
// Next, a demonstration of how to extract the raw S.M.A.R.T. data attributes.
// A drive can report up to 30 of these, but all are optional. Normal values
// vary by vendor, although the property used for this demonstration always
// reports in degrees celcius
error = (*smartInterface)->SMARTReadData(smartInterface, &smartData);
if (error != kIOReturnSuccess) {
printf("SMARTReadData failed: %s(%x)\n", mach_error_string(error), error);
} else {
error = (*smartInterface)->SMARTValidateReadData(smartInterface, &smartData);
if (error != kIOReturnSuccess) {
printf("SMARTValidateReadData failed for attributes: %s(%x)\n", mach_error_string(error), error);
} else {
smartDataVendorSpecifics = *((IOATASmartVendorSpecificData *)&(smartData.vendorSpecific1));
int currentAttributeIndex = 0;
for (currentAttributeIndex = 0; currentAttributeIndex < kSMARTAttributeCount; currentAttributeIndex++) {
IOATASmartAttribute currentAttribute = smartDataVendorSpecifics.vendorAttributes[currentAttributeIndex];
// Grab and use the drive temperature if it's present. Don't freak out if it isn't, as
// this is an optional behaviour although most drives do support this.
if (currentAttribute.attributeId == kWindowSMARTsDriveTempAttribute) {
UInt8 temp = currentAttribute.rawvalue[0];
[smartResultsDict setObject:[NSNumber numberWithUnsignedInt:temp] forKey:kWindowSMARTsDeviceTempKeyString];
break;
}
}
}
}
// Now, grab the corresponding threshold value(s) for the data attributes we have. A
// threshold of zero for temperature indicates that this is not used as part of the
// T.E.C. calculations.
error = (*smartInterface)->SMARTReadDataThresholds(smartInterface, &smartThresholds);
if (error != kIOReturnSuccess) {
printf("SMARTReadDataThresholds failed for threshold data: %s(%x)\n", mach_error_string(error), error);
} else {
// The validation scheme used by S.M.A.R.T. is a checksum byte added to the end to make
// the entire block add to 0x00. This validation works for both the attribute data and
// the threshold data, although the prototype for SMARTValidateReadData takes a pointer
// to a ATASMARTData structure. As a result, we can safely call it here with a typecast.
error = (*smartInterface)->SMARTValidateReadData(smartInterface, (ATASMARTData *)&smartThresholds);
if (error != kIOReturnSuccess) {
printf("SMARTValidateReadData failed for threshold data: %s(%x)\n", mach_error_string(error), error);
} else {
smartThresholdVendorSpecifics = *((IOATASmartVendorSpecificDataThresholds *)&(smartThresholds.vendorSpecific1));
int currentAttributeIndex = 0;
for (currentAttributeIndex = 0; currentAttributeIndex < kSMARTAttributeCount; currentAttributeIndex++) {
IOATASmartThresholdAttribute currentAttribute = smartThresholdVendorSpecifics.ThresholdEntries[currentAttributeIndex];
// Grab and use the drive temperature if it's present. Don't freak out if it isn't, as
// this is an optional behaviour although most drives do support this
if (currentAttribute.attributeId == kWindowSMARTsDriveTempAttribute) {
UInt8 temp = currentAttribute.ThresholdValue;
[smartResultsDict setObject:[NSNumber numberWithUnsignedInt:temp] forKey:kWindowSMARTsDeviceTempThresholdKeyString];
}
}
}
}
ErrorExit:
// Now that we're done, shut down the S.M.A.R.T. If we don't, storage takes a big performance hit.
// We should be able to ignore any error conditions here safely
error = (*smartInterface)->SMARTEnableDisableAutosave(smartInterface, false);
error = (*smartInterface)->SMARTEnableDisableOperations(smartInterface, false);
}
- (io_service_t) GetDeviceObject: (io_service_t) object
{
io_service_t service = IO_OBJECT_NULL;
io_service_t temp = IO_OBJECT_NULL;
io_service_t parent = IO_OBJECT_NULL;
IOReturn status = kIOReturnSuccess;
NSMutableDictionary *property = nil;
property = (NSMutableDictionary *) IORegistryEntrySearchCFProperty (
object,
kIOServicePlane,
CFSTR(kIOPropertySMARTCapableKey),
kCFAllocatorDefault,
kNilOptions );
if (property) {
IOObjectRetain(object);
service = object;
[property release];
goto Exit;
}
status = IORegistryEntryGetParentEntry (object, kIOServicePlane, &parent);
require_string((status == kIOReturnSuccess), Exit, "IORegistryGetParentEntry failed");
while (true) {
temp = parent;
property = (NSMutableDictionary *) IORegistryEntrySearchCFProperty (
temp,
kIOServicePlane,
CFSTR(kIOPropertySMARTCapableKey),
kCFAllocatorDefault,
kNilOptions );
if (property) {
service = temp;
[property release];
break;
}
status = IORegistryEntryGetParentEntry(temp, kIOServicePlane, &parent);
IOObjectRelease(temp);
if (status != kIOReturnSuccess)
break;
}
Exit:
return service;
}
- (IOReturn) PerformSMARTUnitTest:(io_service_t) object
{
io_service_t service = IO_OBJECT_NULL;
IOCFPlugInInterface ** cfPlugInInterface = NULL;
IOATASMARTInterface ** smartInterface = NULL;
SInt32 score = 0;
HRESULT herr = S_OK;
IOReturn err = kIOReturnSuccess;
NSMutableDictionary * smartResultsDict = [[NSMutableDictionary alloc] initWithCapacity:16];
// Under 10.4.8 and higher, we can use the presence of the "SMART Capable" key to find the top-most entry
// in the registry for each device and query that.
service = [self GetDeviceObject: object];
#if 0
// If you know you're going to be running only on 10.4.8 or higher, you could do this
require_string((service != IO_OBJECT_NULL), ErrorExit, "unable to obtain service using [self GetDeviceObject]");
#else
// As a fall-back, this will help you work on pre-10.4.8 systems as well.
if (!service)
service = object;
#endif
err = IOCreatePlugInInterfaceForService ( service,
kIOATASMARTUserClientTypeID,
kIOCFPlugInInterfaceID,
&cfPlugInInterface,
&score );
require_string ( ( err == kIOReturnSuccess ), ErrorExit,
"IOCreatePlugInInterfaceForService failed" );
herr = ( *cfPlugInInterface )->QueryInterface (
cfPlugInInterface,
CFUUIDGetUUIDBytes ( kIOATASMARTInterfaceID ),
( LPVOID ) &smartInterface );
require_string ( ( herr == S_OK ), DestroyPlugIn,
"QueryInterface failed" );
// Grab any identifying data we can on this device and then, if it supports S.M.A.R.T.,
// qurey the S.M.A.R.T. monitoring subsystem for status information
if ([self PrintIdentifyData:smartInterface withResultsDict:smartResultsDict])
[self PrintSMARTData:smartInterface withResultsDict:smartResultsDict];
[foundDevices addObject:smartResultsDict];
[smartResultsDict release];
( *smartInterface )->Release ( smartInterface );
smartInterface = NULL;
DestroyPlugIn:
IODestroyPlugInInterface ( cfPlugInInterface );
cfPlugInInterface = NULL;
ErrorExit:
return err;
}
- (id) init
{
self = [super init];
if (self) {
foundDevices = [[NSMutableArray alloc] initWithCapacity:64];
if (!foundDevices) {
[self dealloc];
self = nil;
}
}
return self;
}
-(void) awakeFromNib
{
IOReturn error = kIOReturnSuccess;
NSMutableDictionary *matchingDict = [[NSMutableDictionary alloc] initWithCapacity:8];
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] initWithCapacity:8];
io_iterator_t iter = IO_OBJECT_NULL;
io_object_t obj = IO_OBJECT_NULL;
//
// Note: We are setting up a matching dictionary which looks like the following:
//
// <dict>
// <key>IOPropertyMatch</key>
// <dict>
// <key>SMART Capable</key>
// <true/>
// </dict>
// </dict>
//
// Create a dictionary with the "SMART Capable" key = true
[subDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithCString:kIOPropertySMARTCapableKey]];
// Add the dictionary to the main dictionary with the key "IOPropertyMatch" to
// narrow the search to the above dictionary.
[matchingDict setObject:subDict forKey:[NSString stringWithCString:kIOPropertyMatchKey]];
[subDict release];
subDict = NULL;
// Remember - this call eats one reference to the matching dictionary. In this case, removing the need to release it later
error = IOServiceGetMatchingServices (kIOMasterPortDefault, (CFDictionaryRef)matchingDict, &iter);
if (error != kIOReturnSuccess) {
printf("Error finding SMART Capable disks: %s(%x)\n", mach_error_string(error), error);
} else {
while ((obj = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
error = [self PerformSMARTUnitTest:obj];
IOObjectRelease(obj);
}
}
// OK, now if that search was unable to locate any devices, then either we don't have any or
// we're running on a system older than 10.4.8. This method will work for older installs
// NOTE: This will locate all ATA storage devices, including ones that do not support S.M.A.R.T.
// You will need to check the indentification data for the ATA Supports SMART bit. This is
// Done above in PrintIdentifyData and the result stored in the dicitonary for this device as
// "SMART Supported"
if ([foundDevices count] == 0) {
iter = IO_OBJECT_NULL;
matchingDict = (NSMutableDictionary *)IOServiceMatching("IOATABlockStorageDevice");
// Remember - this call eats one reference to the matching dictionary. In this case, removing the need to release it later
error = IOServiceGetMatchingServices (kIOMasterPortDefault, (CFDictionaryRef)matchingDict, &iter);
if (error != kIOReturnSuccess) {
printf("Error finding SMART Capable disks the old way: %s(%x)\n", mach_error_string(error), error);
} else {
while ((obj = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
error = [self PerformSMARTUnitTest:obj];
IOObjectRelease(obj);
}
}
}
IOObjectRelease(iter);
iter = IO_OBJECT_NULL;
[deviceArrayController setContent:foundDevices];
}
- (void) dealloc
{
[foundDevices release];
[super dealloc];
}
@end
</pre>
<!--googleoff: index -->
</td>
</tr>
</table>
<!-- END WIDE COLUMN -->
<!-- END MAIN CONTENT -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div style="width: 100%; height: 1px; background-color: #919699; margin-top: 5px; margin-bottom: 15px"></div></td>
</tr>
<tr>
<td align="center"><br/>
<table border="0" cellpadding="0" cellspacing="0" class="graybox">
<tr>
<th>Did this document help you?</th>
</tr>
<tr>
<td>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=1&url=/samplecode/SMARTQuery/listing3.html%3Fid%3DDTS10004291-1.0&media=dvd" target=_new>Yes</a>: Tell us what works for you.</div>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=2&url=/samplecode/SMARTQuery/listing3.html%3Fid%3DDTS10004291-1.0&media=dvd" target=_new>It’s good, but:</a> Report typos, inaccuracies, and so forth.</div>
<div><a href="http://developer.apple.com/feedback/?v=3&url=/samplecode/SMARTQuery/listing3.html%3Fid%3DDTS10004291-1.0&media=dvd" target=_new>It wasn’t helpful</a>: Tell us what would have helped.</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- START BOTTOM APPLE NAVIGATION -->
<!--#include virtual="/includes/footer"-->
<!-- END BOTTOM APPLE NAVIGATION -->
<!-- START CENTER CLOSE -->
</center>
<!-- END CENTER CLOSE -->
</body>
</html>