-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAppleRAIDMirrorSet.cpp
More file actions
1056 lines (808 loc) · 36 KB
/
AppleRAIDMirrorSet.cpp
File metadata and controls
1056 lines (808 loc) · 36 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
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
/*
* Copyright (c) 2001-2007 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "AppleRAID.h"
#define super AppleRAIDSet
OSDefineMetaClassAndStructors(AppleRAIDMirrorSet, AppleRAIDSet);
AppleRAIDSet * AppleRAIDMirrorSet::createRAIDSet(AppleRAIDMember * firstMember)
{
AppleRAIDMirrorSet *raidSet = new AppleRAIDMirrorSet;
IOLog1("AppleRAIDMirrorSet::createRAIDSet(%p) called, new set = %p *********\n", firstMember, raidSet);
while (raidSet){
if (!raidSet->init()) break;
if (!raidSet->initWithHeader(firstMember->getHeader(), true)) break;
if (raidSet->resizeSet(raidSet->getMemberCount())) return raidSet;
break;
}
if (raidSet) raidSet->release();
return 0;
}
bool AppleRAIDMirrorSet::init()
{
IOLog1("AppleRAIDMirrorSet::init() called\n");
if (super::init() == false) return false;
arRebuildThreadCall = 0;
arSetCompleteThreadCall = 0;
arExpectingLiveAdd = 0;
arMaxReadRequestFactor = 32; // with the default 32KB blocksize -> 1 MB
queue_init(&arFailedRequestQueue);
setProperty(kAppleRAIDLevelNameKey, kAppleRAIDLevelNameMirror);
arAllocateRequestMethod = OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDSet::allocateRAIDRequest);
return true;
}
bool AppleRAIDMirrorSet::initWithHeader(OSDictionary * header, bool firstTime)
{
if (super::initWithHeader(header, firstTime) == false) return false;
setProperty(kAppleRAIDSetAutoRebuildKey, header->getObject(kAppleRAIDSetAutoRebuildKey));
setProperty(kAppleRAIDSetTimeoutKey, header->getObject(kAppleRAIDSetTimeoutKey));
// arQuickRebuildBitSize = 0; //XXX
// schedule a timeout to start up degraded sets
if (firstTime) startSetCompleteTimer();
return true;
}
void AppleRAIDMirrorSet::free(void)
{
if (arRebuildThreadCall) thread_call_free(arRebuildThreadCall);
arRebuildThreadCall = 0;
if (arSetCompleteThreadCall) thread_call_free(arSetCompleteThreadCall);
arSetCompleteThreadCall = 0;
if (arLastSeek) IODelete(arLastSeek, UInt64, arLastAllocCount);
if (arSkippedIOCount) IODelete(arSkippedIOCount, UInt64, arLastAllocCount);
assert(queue_empty(&arFailedRequestQueue));
super::free();
}
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
IOBufferMemoryDescriptor * AppleRAIDMirrorSet::readPrimaryMetaData(AppleRAIDMember * member)
{
IOBufferMemoryDescriptor * primaryBuffer = super::readPrimaryMetaData(member);
// XXX
return primaryBuffer;
}
IOReturn AppleRAIDMirrorSet::writePrimaryMetaData(IOBufferMemoryDescriptor * primaryBuffer)
{
// XXX
return super::writePrimaryMetaData(primaryBuffer);
}
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
bool AppleRAIDMirrorSet::addMember(AppleRAIDMember * member)
{
if (arExpectingLiveAdd) {
// for mirrors the set is not paused for adding while adding new
// members, mark it as a spare here to avoid having it marked broken
member->changeMemberState(kAppleRAIDMemberStateSpare, true);
}
if (super::addMember(member) == false) return false;
// set block count = member block count
OSNumber * number = OSDynamicCast(OSNumber, member->getHeaderProperty(kAppleRAIDChunkCountKey));
if (!number) return false;
arSetBlockCount = number->unsigned64BitValue();
arSetMediaSize = arSetBlockCount * arSetBlockSize;
if (arOpenLevel == kIOStorageAccessNone) startSetCompleteTimer();
return true;
}
bool AppleRAIDMirrorSet::removeMember(AppleRAIDMember * member, IOOptionBits options)
{
if (!super::removeMember(member, options)) return false;
// if the set is not currently in use act like we are still gathering members
if (arOpenLevel == kIOStorageAccessNone) {
startSetCompleteTimer();
arController->restartSet(this, false);
}
return true;
}
bool AppleRAIDMirrorSet::resizeSet(UInt32 newMemberCount)
{
UInt32 oldMemberCount = arMemberCount;
// if downsizing, just hold on to the extra space
if (arLastAllocCount < newMemberCount) {
if (arLastSeek) IODelete(arLastSeek, UInt64, arLastAllocCount);
arLastSeek = IONew(UInt64, newMemberCount);
if (!arLastSeek) return false;
if (arSkippedIOCount) IODelete(arSkippedIOCount, UInt64, arLastAllocCount);
arSkippedIOCount = IONew(UInt64, newMemberCount);
if (!arSkippedIOCount) return false;
}
bzero(arLastSeek, sizeof(UInt64) * newMemberCount);
bzero(arSkippedIOCount, sizeof(UInt64) * newMemberCount);
if (super::resizeSet(newMemberCount) == false) return false;
if (oldMemberCount && arMemberCount > oldMemberCount) arExpectingLiveAdd += arMemberCount - oldMemberCount;
return true;
}
UInt32 AppleRAIDMirrorSet::nextSetState(void)
{
UInt32 nextState = super::nextSetState();
if (nextState == kAppleRAIDSetStateOnline) {
if (arActiveCount < arMemberCount) {
nextState = kAppleRAIDSetStateDegraded;
}
}
return nextState;
}
OSDictionary * AppleRAIDMirrorSet::getSetProperties(void)
{
OSDictionary * props = super::getSetProperties();
if (props) {
props->setObject(kAppleRAIDSetAutoRebuildKey, getProperty(kAppleRAIDSetAutoRebuildKey));
props->setObject(kAppleRAIDSetTimeoutKey, getProperty(kAppleRAIDSetTimeoutKey));
// props->setObject(kAppleRAIDSetQuickRebuildKey, kOSBooleanTrue); // XXX
}
return props;
}
bool AppleRAIDMirrorSet::startSet(void)
{
IOLog1("AppleRAIDMirrorSet::startSet() - parallel read request max %lld bytes.\n", getSmallestMaxByteCount());
arMaxReadRequestFactor = getSmallestMaxByteCount() / arSetBlockSize;
if (super::startSet() == false) return false;
if (getSetState() == kAppleRAIDSetStateDegraded) {
if (getSpareCount()) rebuildStart();
} else {
// clear the timeout once the set is complete
arSetCompleteTimeout = kARSetCompleteTimeoutNone;
}
return true;
}
bool AppleRAIDMirrorSet::publishSet(void)
{
if (arExpectingLiveAdd) {
IOLog1("AppleRAIDMirror::publishSet() publish ignored.\n");
return false;
}
return super::publishSet();
}
bool AppleRAIDMirrorSet::isSetComplete(void)
{
if (super::isSetComplete()) return true;
// if timeout is still active return false
if (arSetCompleteTimeout) return false;
// set specific checks
return arActiveCount != 0;
}
bool AppleRAIDMirrorSet::bumpOnError(void)
{
return true;
}
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
void AppleRAIDMirrorSet::activeReadMembers(AppleRAIDMember ** activeMembers, UInt64 byteStart, UInt32 byteCount)
{
// this code try's to do three things:
// 1) send large single sequential i/o requests to each disk (arMaxReadRequestFactor)
// 2) send i/o requests to the disk with the smallest seek distance (arLastSeek)
// 3) balance the number of i/o requests between the available drives (arSkippedIOCount)
//
// this code completely ignores the effects of writes on the head position since writes move
// the heads on all disks. if the disk is doing track caching then ignoring the writes can
// still get us to a disk that may have that data already cached.
//
// note that arLastSeek is the last previously scheduled head position, the head may not
// be anywhere near there yet, hence this code can schedule multiple future i/o requests
#define isOnline(member) ((UInt32)(member) >= 0x1000)
#define isOffline(member) ((UInt32)(member) < 0x1000)
UInt64 distances[arMemberCount];
for (UInt32 index = 0; index < arMemberCount; index++) {
AppleRAIDMember * member = arMembers[index];
if (member) {
UInt32 memberState = member->getMemberState();
if (memberState == kAppleRAIDMemberStateOpen || memberState == kAppleRAIDMemberStateClosing) {
// UInt64 distance = (arLastSeek[index] <= byteStart) ? (byteStart - arLastSeek[index]) : 0xfffffffffffffffeULL; // elevator
UInt64 distance = max(arLastSeek[index], byteStart) - min(arLastSeek[index], byteStart);
// if (arSkippedIOCount[index] >= (arMaxReadRequestFactor / 2)) distance = 0;
if (arSkippedIOCount[index] >= 12) distance = 1;
UInt32 sort = index;
while (sort) {
if (isOnline((uintptr_t)activeMembers[sort-1]) && distance > distances[sort-1]) break;
activeMembers[sort] = activeMembers[sort-1];
distances[sort] = distances[sort-1];
sort--;
}
activeMembers[sort] = member;
distances[sort] = distance;
continue;
}
}
activeMembers[index] = (AppleRAIDMember *)index;
distances[index] = 0xffffffffffffffffULL;
}
assert((arActiveCount != arMemberCount) ? (isOffline((uintptr_t)activeMembers[arActiveCount])) : (isOnline((uintptr_t)activeMembers[arMemberCount-1])));
// adjust last seeked to pointers and skipped counts
UInt64 balancedBlockCount = arSetBlockSize * arMaxReadRequestFactor;
UInt64 perMemberCount = byteCount / balancedBlockCount / arActiveCount * balancedBlockCount;
UInt64 count = 0;
for (UInt32 virtualIndex = 0; virtualIndex < arActiveCount; virtualIndex++) {
AppleRAIDMember * member = activeMembers[virtualIndex];
if (isOffline((uintptr_t)member)) break;
UInt32 memberIndex = member->getMemberIndex();
count = perMemberCount ? min(byteCount, perMemberCount) : min(byteCount, balancedBlockCount);
if (count) {
byteStart += count;
byteCount -= count;
arLastSeek[memberIndex] = byteStart;
arSkippedIOCount[memberIndex] = 0;
} else {
arSkippedIOCount[memberIndex]++;
}
}
assert(byteCount == 0);
#ifdef DEBUG2
static UInt32 sumCount = 0, skippedSum0 = 0, skippedSum1 = 0, overflowCount = 0;
static UInt64 averageSeekSum = 0;
skippedSum0 += arSkippedIOCount[0];
skippedSum1 += arSkippedIOCount[1];
averageSeekSum += distances[0];
if (perMemberCount) overflowCount++;
if (sumCount++ >= 99) {
printf("skip0=%ld skip1=%ld, over=%ld, lastseek0=%llx lastseek1=%llx, avseek=%llx\n",
skippedSum0, skippedSum1, overflowCount,
arLastSeek[0], arLastSeek[1], averageSeekSum/100);
sumCount = skippedSum0 = skippedSum1 = overflowCount = 0;
averageSeekSum = 0;
}
#endif
}
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
void AppleRAIDMirrorSet::completeRAIDRequest(AppleRAIDStorageRequest *storageRequest)
{
UInt32 cnt;
UInt64 byteCount;
UInt64 expectedByteCount;
IOReturn status;
bool isWrite;
isWrite = (storageRequest->srMemoryDescriptorDirection == kIODirectionOut);
byteCount = 0;
expectedByteCount = isWrite ? storageRequest->srByteCount * storageRequest->srActiveCount : storageRequest->srByteCount;
status = kIOReturnSuccess;
// Collect the status and byte count for each member.
for (cnt = 0; cnt < arMemberCount; cnt++) {
// Ignore missing members.
if (arMembers[cnt] == 0) continue;
// rebuilding members
if (arMembers[cnt]->getMemberState() == kAppleRAIDMemberStateRebuilding) {
if (!isWrite) {
assert(storageRequest->srRequestByteCounts[cnt] == 0);
continue;
}
if (storageRequest->srRequestStatus[cnt] != kIOReturnSuccess ||
storageRequest->srRequestByteCounts[cnt] != storageRequest->srByteCount) {
// This will terminate the rebuild thread
arMembers[cnt]->changeMemberState(kAppleRAIDMemberStateBroken);
IOLog("AppleRAID::completeRAIDRequest - write error 0x%x detected during rebuild for set \"%s\" (%s) on member %s, set byte offset = %llu.\n",
storageRequest->srRequestStatus[cnt], getSetNameString(), getUUIDString(),
arMembers[cnt]->getUUIDString(), storageRequest->srByteStart);
}
continue;
}
// offline members
if (arMembers[cnt]->getMemberState() != kAppleRAIDMemberStateOpen) {
IOLogRW("AppleRAIDMirrorSet::completeRAIDRequest - [%u] tbc 0x%llx, sbc 0x%llx bc 0x%llx, member %p, member state %u\n",
(uint32_t)cnt, storageRequest->srByteCount, storageRequest->srRequestByteCounts[cnt],
byteCount, arMembers[cnt], (uint32_t)arMembers[cnt]->getMemberState());
status = kIOReturnIOError;
continue;
}
// failing members
if (storageRequest->srRequestStatus[cnt] != kIOReturnSuccess) {
IOLog("AppleRAID::completeRAIDRequest - error 0x%x detected for set \"%s\" (%s), member %s, set byte offset = %llu.\n",
storageRequest->srRequestStatus[cnt], getSetNameString(), getUUIDString(),
arMembers[cnt]->getUUIDString(), storageRequest->srByteStart);
status = storageRequest->srRequestStatus[cnt];
// mark this member to be removed
arMembers[cnt]->changeMemberState(kAppleRAIDMemberStateClosing);
continue;
}
byteCount += storageRequest->srRequestByteCounts[cnt];
IOLogRW("AppleRAIDMirrorSet::completeRAIDRequest - [%u] tbc 0x%llx, sbc 0x%llx bc 0x%llx, member %p\n",
(uint32_t)cnt, storageRequest->srByteCount, storageRequest->srRequestByteCounts[cnt],
byteCount, arMembers[cnt]);
}
// Return an underrun error if the byte count is not complete.
// dkreadwrite should clip any requests beyond our published size
// however we still see underruns with pulled disks (bug?)
if (status == kIOReturnSuccess) {
if (byteCount != expectedByteCount) {
IOLog("AppleRAID::completeRAIDRequest - underrun detected on set = \"%s\" (%s)\n", getSetNameString(), getUUIDString());
IOLog1("AppleRAID::completeRAIDRequest - total expected = 0x%llx (0x%llx), actual = 0x%llx\n",
expectedByteCount, storageRequest->srByteCount, byteCount);
status = kIOReturnUnderrun;
byteCount = 0;
} else {
// fix up write byte count
byteCount = storageRequest->srByteCount;
}
} else {
IOLog1("AppleRAID::completeRAIDRequest - error detected\n");
UInt32 stillAliveCount = 0;
for (cnt = 0; cnt < arMemberCount; cnt++) {
if (arMembers[cnt] == 0) continue;
if (arMembers[cnt]->getMemberState() == kAppleRAIDMemberStateOpen) {
stillAliveCount++;
}
}
// if we haven't lost the entire set, retry the failed requests
if (stillAliveCount) {
bool recoveryActive = queue_empty(&arFailedRequestQueue) != true;
arStorageRequestsPending--;
queue_enter(&arFailedRequestQueue, storageRequest, AppleRAIDStorageRequest *, fCommandChain);
arSetCommandGate->commandWakeup(&arStorageRequestPool, /* oneThread */ false);
// kick off the recovery thread if it isn't already active
if (!recoveryActive) {
recoverStart();
}
return;
} else {
// or let the recovery thread finish off the set
recoverStart();
}
byteCount = 0;
}
storageRequest->srMemoryDescriptor->release();
returnRAIDRequest(storageRequest);
// Call the clients completion routine, bad status is returned here.
IOStorage::complete(&storageRequest->srClientsCompletion, status, byteCount);
}
void AppleRAIDMirrorSet::getRecoverQueue(queue_head_t *oldRequestQueue, queue_head_t *newRequestQueue)
{
queue_new_head(oldRequestQueue, newRequestQueue, AppleRAIDStorageRequest *, fCommandChain);
queue_init(oldRequestQueue);
}
bool AppleRAIDMirrorSet::recover()
{
// this is on a separate thread
// the set is paused.
// move failed i/o queue now in case we lose the set
queue_head_t safeFailedRequestQueue;
IOCommandGate::Action getRecoverQMethod = OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::getRecoverQueue);
arSetCommandGate->runAction(getRecoverQMethod, &arFailedRequestQueue, &safeFailedRequestQueue);
// remove the bad members and rebuild the set
bool stillHere = super::recover();
// the set no longer paused.
IOLog1("AppleRAIDMirrorSet::recover() entered.\n");
// requeue any previously failed i/o's
while (!queue_empty(&safeFailedRequestQueue)) {
AppleRAIDStorageRequest * oldStorageRequest;
queue_remove_first(&safeFailedRequestQueue, oldStorageRequest, AppleRAIDStorageRequest *, fCommandChain);
IOLog1("AppleRAIDMirrorSet::recover() requeuing request %p\n", oldStorageRequest);
IOService *client;
UInt64 byteStart;
IOMemoryDescriptor *buffer;
IOStorageCompletion completion;
oldStorageRequest->extractRequest(&client, &byteStart, &buffer, &completion);
oldStorageRequest->release();
if (stillHere) {
AppleRAIDStorageRequest * newStorageRequest;
arSetCommandGate->runAction(arAllocateRequestMethod, &newStorageRequest);
if (newStorageRequest) {
// retry failed request
if (buffer->getDirection() == kIODirectionOut) {
newStorageRequest->write(client, byteStart, buffer, NULL, &completion);
} else {
newStorageRequest->read(client, byteStart, buffer, NULL, &completion);
}
continue;
}
}
// give up, return an error
IOStorage::complete(&completion, kIOReturnIOError, 0);
}
IOLog1("AppleRAIDMirrorSet::recover exiting\n");
return true;
}
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
void AppleRAIDMirrorSet::startSetCompleteTimer()
{
IOLog1("AppleRAIDMirrorSet::startSetCompleteTimer(%p) - timer %s running.\n",
this, arSetCompleteTimeout ? "is already" : "was not");
// prevent timer from firing with no backing object
retain();
// once the set is live, arSetCompleteTimeout must stay zero
OSNumber * number = OSDynamicCast(OSNumber, getProperty(kAppleRAIDSetTimeoutKey));
if (number) arSetCompleteTimeout = number->unsigned32BitValue();
if (!arSetCompleteTimeout) arSetCompleteTimeout = kARSetCompleteTimeoutDefault;
// set up the timer (first time only)
if (!arSetCompleteThreadCall) {
thread_call_func_t setCompleteMethod = OSMemberFunctionCast(thread_call_func_t, this, &AppleRAIDMirrorSet::setCompleteTimeout);
arSetCompleteThreadCall = thread_call_allocate(setCompleteMethod, (thread_call_param_t)this);
}
// start timer
AbsoluteTime deadline;
clock_interval_to_deadline(arSetCompleteTimeout, kSecondScale, &deadline);
// an overlapping timer request will cancel the earlier request
bool overlap = thread_call_enter_delayed(arSetCompleteThreadCall, deadline);
if (overlap) release();
}
void AppleRAIDMirrorSet::setCompleteTimeout(void)
{
IOLog1("AppleRAIDMirrorSet::setCompleteTimeout(%p) - the timeout is %sactive.\n", this, arSetCompleteTimeout ? "":"in");
// this code is outside the global lock and the workloop
// to simplify handling race conditions with cancelling the timeout
// we always let it fire and only release the set here.
arSetCompleteTimeout = kARSetCompleteTimeoutNone;
arController->degradeSet(this);
release();
}
void AppleRAIDMirrorSet::rebuildStart(void)
{
IOLog1("AppleRAIDMirrorSet::rebuildStart(%p) - entered\n", this);
// are we already rebuilding a member
if (arRebuildingMember) return;
// sanity checks
if (getSpareCount() == 0) return;
if (arActiveCount == 0) return;
// find a missing member that can be replaced
UInt32 memberIndex;
for (memberIndex = 0; memberIndex < arMemberCount; memberIndex++) {
if (arMembers[memberIndex] == 0) {
break;
}
}
if (memberIndex >= arMemberCount) return;
// find a spare that is usable
AppleRAIDMember * target = 0;
bool autoRebuild = OSDynamicCast(OSBoolean, getProperty(kAppleRAIDSetAutoRebuildKey)) == kOSBooleanTrue;
OSCollectionIterator * iter = OSCollectionIterator::withCollection(arSpareMembers);
if (!iter) return;
while (AppleRAIDMember * candidate = (AppleRAIDMember *)iter->getNextObject()) {
if (candidate->isBroken()) {
IOLog1("AppleRAIDMirrorSet::rebuildStart(%p) - skipping candidate %p, it is broken.\n", this, candidate);
continue;
}
// live adds have priority over regular spares
if (arExpectingLiveAdd) {
OSNumber * number = OSDynamicCast(OSNumber, candidate->getHeaderProperty(kAppleRAIDMemberIndexKey));
if (!number) continue;
UInt32 candidateIndex = number->unsigned32BitValue();
if (arMembers[candidateIndex]) continue;
memberIndex = candidateIndex;
candidate->changeMemberState(kAppleRAIDMemberStateSpare);
arExpectingLiveAdd--;
} else {
// if autorebuild is not on, only use current spares
if (!autoRebuild) {
if (candidate->isSpare()) {
OSNumber * number = OSDynamicCast(OSNumber, candidate->getHeaderProperty(kAppleRAIDSequenceNumberKey));
if (!number) continue;
UInt32 sequenceNumber = number->unsigned32BitValue();
if (sequenceNumber != getSequenceNumber()) {
IOLog1("AppleRAIDMirrorSet::rebuildStart(%p) - skipping candidate %p, expired seq num %d.\n",
this, candidate, (int)sequenceNumber);
continue;
}
} else {
IOLog1("AppleRAIDMirrorSet::rebuildStart(%p) - skipping candidate %p, autorebuild is off.\n", this, candidate);
continue;
}
}
}
arSpareMembers->removeObject(candidate); // must break, this breaks iter
target = candidate;
break;
}
iter->release();
if (!target) return;
// pull the spare uuid out of the spare uuid list, only for v2 headers
OSArray * spareUUIDs = OSDynamicCast(OSArray, getProperty(kAppleRAIDSparesKey));
if (spareUUIDs) spareUUIDs = OSArray::withArray(spareUUIDs);
if (spareUUIDs) {
UInt32 spareCount = spareUUIDs ? spareUUIDs->getCount() : 0;
for (UInt32 i = 0; i < spareCount; i++) {
OSString * uuid = OSDynamicCast(OSString, spareUUIDs->getObject(i));
if (uuid && uuid->isEqualTo(target->getUUID())) {
spareUUIDs->removeObject(i);
}
}
setProperty(kAppleRAIDSparesKey, spareUUIDs);
spareUUIDs->release();
}
// if this member was part of the set, rebuild it at it's old index
OSArray * memberUUIDs = OSDynamicCast(OSArray, getProperty(kAppleRAIDMembersKey));
if (memberUUIDs) memberUUIDs = OSArray::withArray(memberUUIDs);
if (memberUUIDs) {
UInt32 memberCount = memberUUIDs ? memberUUIDs->getCount() : 0;
for (UInt32 i = 0; i < memberCount; i++) {
OSString * uuid = OSDynamicCast(OSString, memberUUIDs->getObject(i));
if (uuid && uuid->isEqualTo(target->getUUID())) {
if (arMembers[i] == NULL) {
memberIndex = i;
break;
}
IOLog("AppleRAIDMirrorSet::rebuildStart() - spare already active at index = %d?\n", (int)memberIndex);
assert(0); // this should never happen
return;
}
}
}
target->setMemberIndex(memberIndex);
target->setHeaderProperty(kAppleRAIDSequenceNumberKey, getSequenceNumber(), 32);
IOLog1("AppleRAIDMirrorSet::rebuildStart(%p) - found a target %p for index = %d\n", this, target, (int)memberIndex);
// let any current i/o's finish before reconfiguring the mirror as writes then are expected to go to the rebuilding member.
arSetCommandGate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::pauseSet), (void *)false);
arRebuildingMember = target;
// add member to set at the index we are rebuilding
// note that arActiveCount is not bumped
if (memberUUIDs) {
memberUUIDs->replaceObject(memberIndex, target->getUUID());
setProperty(kAppleRAIDMembersKey, memberUUIDs);
memberUUIDs->release();
}
arMembers[memberIndex] = target;
arMembers[memberIndex]->changeMemberState(kAppleRAIDMemberStateRebuilding);
arSetCommandGate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::unpauseSet));
if (!arRebuildThreadCall) {
thread_call_func_t rebuildMethod = OSMemberFunctionCast(thread_call_func_t, this, &AppleRAIDMirrorSet::rebuild);
arRebuildThreadCall = thread_call_allocate(rebuildMethod, (thread_call_param_t)this);
}
// the rebuild runs outside the workloop and global raid lock
// if the whole set goes, it has no idea, this keeps the set
// from disappearing underneath the rebuild
retain();
if (arRebuildThreadCall) (void)thread_call_enter(arRebuildThreadCall);
}
// *** this in not inside the workloop ***
void AppleRAIDMirrorSet::rebuild()
{
IOLog1("AppleRAIDMirrorSet::rebuild(%p) - entered\n", this);
AppleRAIDMember * target = arRebuildingMember;
AppleRAIDMember * source = 0;
bool targetOpen = false;
bool sourceOpen = false;
UInt32 sourceIndex = 0;
IOBufferMemoryDescriptor * rebuildBuffer = 0;
UInt64 offset = 0;
IOReturn rc;
// the rebuild is officially started
messageClients(kAppleRAIDMessageSetChanged);
// all failures need to call rebuildComplete
while (true) {
// XXX this code should be double buffered
// there is a race between the code that kicks off this thread and this thread.
// the other thread is updating the raid headers and if the set is not opened
// it closes the members when it is done. since there is no open/close counting
// that causes problems in this code by closing the member underneath us.
// since the other thread is holding the global lock if we also try to grab the
// lock this code will block until the headers are updated.
gAppleRAIDGlobals.lock();
// shake your head in disgust
gAppleRAIDGlobals.unlock();
// allocate copy buffers
rebuildBuffer = IOBufferMemoryDescriptor::withCapacity(arSetBlockSize, kIODirectionNone);
if (rebuildBuffer == 0) break;
// Open the target member
targetOpen = target->open(this, 0, kIOStorageAccessReaderWriter);
if (!targetOpen) break;
// clear the on disk spare state and reset the sequence number
target->setHeaderProperty(kAppleRAIDMemberTypeKey, kAppleRAIDMembersKey);
target->setHeaderProperty(kAppleRAIDSequenceNumberKey, 0, 32);
target->writeRAIDHeader();
offset = arBaseOffset;
clock_sec_t oldTime = 0;
while (offset < arSetMediaSize) {
IOLog2("AppleRAIDMirrorSet::rebuild(%p) - offset = %llu bs=%llu\n", this, offset, arSetBlockSize);
// if the set is idle pause regular i/o
IOCommandGate::Action pauseMethod = OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::pauseSet);
while (arSetCommandGate->runAction(pauseMethod, (void *)true) == false) {
IOSleep(100);
}
// check if we failed during normal i/o
if (target->getMemberState() != kAppleRAIDMemberStateRebuilding) break;
// find a source drive, also check if it changed
// the set is paused here, this should be safe
if (!sourceOpen || !arMembers[sourceIndex]) {
if (sourceOpen) close(this, 0);
sourceOpen = false;
for (sourceIndex = 0; sourceIndex < arMemberCount; sourceIndex++) {
if (arMembers[sourceIndex] == target) continue;
if ((source = arMembers[sourceIndex])) break;
}
if (!source) break;
sourceOpen = open(this, 0, kIOStorageAccessReader);
if (!sourceOpen) break;
}
// Fill the read buffer
rebuildBuffer->setDirection(kIODirectionIn);
rc = source->IOStorage::read((IOService *)this, offset, rebuildBuffer);
if (rc) {
IOLog("AppleRAIDMirrorSet::rebuild() - read failed with 0x%x on member %s, member byte offset = %llu\n",
rc, source->getUUIDString(), offset);
break;
}
rebuildBuffer->setDirection(kIODirectionOut);
rc = target->IOStorage::write((IOService *)this, offset, rebuildBuffer);
if (rc) {
// give up
IOLog("AppleRAIDMirrorSet::rebuild() - write failed with 0x%x on member %s, member byte offset = %llu\n",
rc, target->getUUIDString(), offset);
break;
}
arSetCommandGate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::unpauseSet));
// update rebuild status once a second
clock_sec_t newTime;
clock_usec_t dontcare;
clock_get_system_microtime(&newTime, &dontcare);
if (newTime != oldTime) {
oldTime = newTime;
OSNumber * bytesCompleted = OSDynamicCast(OSNumber, target->getProperty(kAppleRAIDRebuildStatus));
if (bytesCompleted) {
// avoids a race with getMemberProperties
bytesCompleted->setValue(offset);
} else {
bytesCompleted = OSNumber::withNumber(offset, 64);
if (bytesCompleted) {
target->setProperty(kAppleRAIDRebuildStatus, bytesCompleted);
bytesCompleted->release();
}
}
}
// keep requests aligned (header != block size)
if ((offset % arSetBlockSize) != 0) offset = (offset / arSetBlockSize) * arSetBlockSize;
offset += arSetBlockSize;
}
break;
}
// rebuilding member state changes: spare -> rebuilding -> rebuilding (open) -> closed -> open or broken
// clean up
if (rebuildBuffer) {
rebuildBuffer->release();
rebuildBuffer = 0;
}
if (sourceOpen) close(this, 0);
if (targetOpen) target->close(this, 0);
// if the target state went back to spare that means the member is being removed from the set
bool aborting = target->getMemberState() == kAppleRAIDMemberStateSpare;
if (aborting) target->changeMemberState(kAppleRAIDMemberStateBroken);
if (arSetIsPaused) arSetCommandGate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::unpauseSet));
if (aborting) {
// calling rebuildComplete hangs on the global lock, just bail out
arRebuildingMember = 0;
} else {
bool success = offset >= arSetMediaSize;
IOCommandGate::Action rebuildCompleteMethod = OSMemberFunctionCast(IOCommandGate::Action, this, &AppleRAIDMirrorSet::rebuildComplete);
arSetCommandGate->runAction(rebuildCompleteMethod, (void *)success);
}
if (getSpareCount()) {
gAppleRAIDGlobals.lock();
rebuildStart();
gAppleRAIDGlobals.unlock();
}
// just in case the set's status does not need to change
messageClients(kAppleRAIDMessageSetChanged);
release();
}
void AppleRAIDMirrorSet::rebuildComplete(bool rebuiltComplete)
{
AppleRAIDMember * target = arRebuildingMember;
UInt32 memberIndex = target->getMemberIndex();
// this is running in the workloop
// target is closed
pauseSet(false);
// clear rebuild progress from target
target->removeProperty(kAppleRAIDRebuildStatus);
// remove from set
this->detach(arMembers[memberIndex]);
arMembers[memberIndex] = 0;
gAppleRAIDGlobals.lock();
// add member back into the raid set, update raid headers
if (rebuiltComplete && upgradeMember(target)) {
arController->restartSet(this, true);
IOLog("AppleRAIDMirrorSet::rebuild complete for set \"%s\" (%s).\n", getSetNameString(), getUUIDString());
} else {
IOLog("AppleRAIDMirrorSet::rebuild: copy failed for set \"%s\" (%s).\n", getSetNameString(), getUUIDString());
// just leave this member in the set's member uuid list
// but mark member as broken
target->changeMemberState(kAppleRAIDMemberStateBroken);
// and toss it back in the spare pile
addSpare(target);
}
gAppleRAIDGlobals.unlock();
unpauseSet();
// kick off next rebuild (if needed)
arRebuildingMember = 0;
}
AppleRAIDMemoryDescriptor * AppleRAIDMirrorSet::allocateMemoryDescriptor(AppleRAIDStorageRequest *storageRequest, UInt32 memberIndex)
{
return AppleRAIDMirrorMemoryDescriptor::withStorageRequest(storageRequest, memberIndex);
}
// AppleRAIDMirrorMemoryDescriptor
// AppleRAIDMirrorMemoryDescriptor
// AppleRAIDMirrorMemoryDescriptor
#undef super
#define super AppleRAIDMemoryDescriptor
OSDefineMetaClassAndStructors(AppleRAIDMirrorMemoryDescriptor, AppleRAIDMemoryDescriptor);
AppleRAIDMemoryDescriptor *
AppleRAIDMirrorMemoryDescriptor::withStorageRequest(AppleRAIDStorageRequest *storageRequest, UInt32 memberIndex)
{
AppleRAIDMemoryDescriptor *memoryDescriptor = new AppleRAIDMirrorMemoryDescriptor;
if (memoryDescriptor != 0) {
if (!memoryDescriptor->initWithStorageRequest(storageRequest, memberIndex)) {
memoryDescriptor->release();
memoryDescriptor = 0;
}
}
return memoryDescriptor;
}
bool AppleRAIDMirrorMemoryDescriptor::initWithStorageRequest(AppleRAIDStorageRequest *storageRequest, UInt32 memberIndex)
{
if (!super::initWithStorageRequest(storageRequest, memberIndex)) return false;
mdSetBlockSize = storageRequest->srSetBlockSize;
return true;
}
bool AppleRAIDMirrorMemoryDescriptor::configureForMemoryDescriptor(IOMemoryDescriptor *memoryDescriptor, UInt64 byteStart, UInt32 activeIndex)
{
UInt32 byteCount = memoryDescriptor->getLength();
UInt32 blockCount, memberBlockCount;
UInt64 setBlockStop, memberBlockStart;
UInt32 extraBlocks, setBlockStopOffset;
UInt32 startIndex, virtualIndex;
UInt32 activeCount = mdStorageRequest->srActiveCount;
_flags = (_flags & ~kIOMemoryDirectionMask) | memoryDescriptor->getDirection();
if (_flags & kIODirectionOut) {
mdMemberByteStart = byteStart;