Repository navigation
Expand file tree
/
Copy pathIOMediaBSDClient.cpp
More file actions
3990 lines (3104 loc) · 126 KB
/
Copy pathIOMediaBSDClient.cpp
File metadata and controls
3990 lines (3104 loc) · 126 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) 1998-2014 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The 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, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <sys/types.h> // (miscfs/devfs/devfs.h, ...)
#include <miscfs/devfs/devfs.h> // (devfs_make_node, ...)
#include <sys/buf.h> // (buf_t, ...)
#include <sys/fcntl.h> // (FWRITE, ...)
#include <sys/ioccom.h> // (IOCGROUP, ...)
#include <sys/proc.h> // (proc_is64bit, ...)
#include <sys/stat.h> // (S_ISBLK, ...)
#include <sys/systm.h> // (DEV_BSIZE, ...)
#include <sys/kdebug.h> // (FSDBG_CODE, ...)
#include <libkern/OSMalloc.h>
#include <IOKit/assert.h>
#include <IOKit/IOBSD.h>
#include <IOKit/IODeviceTreeSupport.h>
#include <IOKit/IOLib.h>
#include <IOKit/IOKitKeys.h>
#include <IOKit/IOMemoryDescriptor.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOSubMemoryDescriptor.h>
#include <IOKit/storage/IOBlockStorageDevice.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/storage/IOMediaBSDClient.h>
///w:start
#if !TARGET_OS_EMBEDDED
#include <IOKit/pwr_mgt/RootDomain.h>
#endif /* !TARGET_OS_EMBEDDED */
///w:stop
#define super IOService
OSDefineMetaClassAndStructors(IOMediaBSDClient, IOService)
const UInt32 kMinorsAddCountBits = 6;
const UInt32 kMinorsAddCountMask = (1 << kMinorsAddCountBits) - 1;
const UInt32 kMinorsAddCount = (1 << kMinorsAddCountBits);
const UInt32 kMinorsMaxCountBits = 16;
const UInt32 kMinorsMaxCount = (1 << kMinorsMaxCountBits);
const UInt32 kMinorsBucketCount = kMinorsMaxCount / kMinorsAddCount;
const UInt32 kAnchorsAddCount = 2;
const UInt32 kAnchorsMaxCount = kMinorsMaxCount;
#define kMsgNoWhole "%s: No whole media found for media \"%s\".\n", getName()
#define kMsgNoLocation "%s: No location is found for media \"%s\".\n", getName()
#define MAX_PROVISION_EXTENTS_COUNT (PAGE_SIZE/sizeof(IOStorageProvisionExtent))
#define MAX_UNMAP_EXTENTS_COUNT 8
extern "C"
{
int dkclose(dev_t dev, int flags, int devtype, proc_t proc);
int dkioctl(dev_t dev, u_long cmd, caddr_t data, int flags, proc_t proc);
int dkioctl_bdev(dev_t dev, u_long cmd, caddr_t data, int flags, proc_t proc);
int dkioctl_cdev(dev_t dev, u_long cmd, caddr_t data, int flags, proc_t proc);
int dkopen(dev_t dev, int flags, int devtype, proc_t proc);
int dkread(dev_t dev, uio_t uio, int flags);
int dksize(dev_t dev);
void dkstrategy(buf_t bp);
int dkwrite(dev_t dev, uio_t uio, int flags);
} // extern "C"
static struct bdevsw bdevswFunctions =
{
/* d_open */ dkopen,
/* d_close */ dkclose,
/* d_strategy */ dkstrategy,
/* d_ioctl */ dkioctl_bdev,
/* d_dump */ eno_dump,
/* d_psize */ dksize,
/* d_type */ D_DISK
};
struct cdevsw cdevswFunctions =
{
/* d_open */ dkopen,
/* d_close */ dkclose,
/* d_read */ dkread,
/* d_write */ dkwrite,
/* d_ioctl */ dkioctl_cdev,
/* d_stop */ eno_stop,
/* d_reset */ eno_reset,
/* d_ttys */ 0,
/* d_select */ eno_select,
/* d_mmap */ eno_mmap,
/* d_strategy */ eno_strat,
/* d_getc */ eno_getc,
/* d_putc */ eno_putc,
/* d_type */ D_DISK
};
struct dio { dev_t dev; uio_t uio; void * drvdata; };
typedef struct dio * dio_t;
typedef void * dkr_t; /* dkreadwrite request */
typedef enum { DKRTYPE_BUF, DKRTYPE_DIO } dkrtype_t;
static int dkreadwrite(dkr_t dkr, dkrtype_t dkrtype);
static void dkreadwritecompletion(void *, void *, IOReturn, UInt64);
inline int32_t getminor(dev_t dev)
{
return minor(dev);
}
const UInt32 kInvalidAnchorID = (UInt32) (-1);
struct AnchorSlot
{
UInt32 isAssigned:1; // (slot is occupied)
UInt32 isObsolete:1; // (slot is to be removed once references gone)
IOService * anchor; // (anchor object)
void * key; // (anchor key)
IONotifier * notifier; // (anchor termination notification, post-stop)
};
class AnchorTable
{
protected:
AnchorSlot * _table;
UInt32 _tableCount;
static IOReturn anchorWasNotified( void * target,
void * parameter,
UInt32 messageType,
IOService * provider,
void * messageArgument,
vm_size_t messageArgumentSize );
public:
AnchorTable();
~AnchorTable();
UInt32 insert(IOService * anchor, void * key);
UInt32 locate(IOService * anchor);
UInt32 locate(IOService * anchor, void * key);
void obsolete(UInt32 anchorID);
void remove(UInt32 anchorID);
UInt32 update(IOService * anchor, void * key);
bool isObsolete(UInt32 anchorID);
};
const UInt32 kInvalidMinorID = (UInt32) (-1);
struct MinorSlot
{
UInt32 isAssigned:1; // (slot is occupied)
UInt32 isObsolete:1; // (slot is to be removed, close pending)
UInt32 isOrphaned:1; // (slot is in open flux, close pending)
UInt32 isVirtual:1; // (slot is virtual disk, such as disk images)
UInt32 anchorID; // (minor's associated anchor ID)
IOMediaBSDClient * client; // (minor's media bsd client object)
IOMedia * media; // (minor's media object)
char * name; // (minor's name, private allocation)
UInt64 bdevBlockSize; // (block device's preferred block size)
void * bdevNode; // (block device's devfs node)
UInt32 bdevOpen; // (block device's open count)
IOStorageAccess bdevOpenLevel; // (block device's open level)
void * cdevNode; // (character device's devfs node)
UInt32 cdevOpen; // (character device's open count)
IOStorageAccess cdevOpenLevel; // (character device's open level)
#if TARGET_OS_EMBEDDED
IOStorageOptions cdevOptions;
#endif /* TARGET_OS_EMBEDDED */
};
class MinorTable
{
protected:
class
{
public:
MinorSlot ** buckets;
inline MinorSlot & operator[](const int i)
{
return (buckets[i >> kMinorsAddCountBits])[i & kMinorsAddCountMask];
}
} _table;
UInt32 _tableCount;
public:
MinorTable();
~MinorTable();
UInt32 insert( IOMedia * media,
UInt32 anchorID,
IOMediaBSDClient * client,
char * slicePath );
UInt32 update( IOMedia * media,
UInt32 anchorID,
IOMediaBSDClient * client,
char * slicePath );
UInt32 locate(IOMedia * media);
void obsolete(UInt32 minorID);
void remove(UInt32 minorID);
bool isObsolete(UInt32 minorID);
MinorSlot * getMinor(UInt32 minorID);
UInt32 getOpenCountForAnchorID(UInt32 anchorID);
bool hasReferencesToAnchorID(UInt32 anchorID, bool excludeOrphans);
};
const UInt32 kInvalidMajorID = (UInt32) (-1);
class IOMediaBSDClientGlobals
{
protected:
AnchorTable * _anchors; // (table of anchors)
MinorTable * _minors; // (table of minors)
UInt32 _majorID; // (major ID)
IOLock * _openLock; // (lock for opens, closes)
IOLock * _stateLock; // (lock for state, tables)
///w:start
#if !TARGET_OS_EMBEDDED
thread_call_t _assertionCall;
IOPMDriverAssertionID _assertionID;
IOLock * _assertionLock;
AbsoluteTime _assertionTime;
#endif /* !TARGET_OS_EMBEDDED */
OSMallocTag _iostorageMallocTag;
///w:stop
public:
IOMediaBSDClientGlobals();
~IOMediaBSDClientGlobals();
AnchorTable * getAnchors();
MinorTable * getMinors();
MinorSlot * getMinor(UInt32 minorID);
UInt32 getMajorID();
bool isValid();
void lockOpen();
void unlockOpen();
void lockState();
void unlockState();
///w:start
#if !TARGET_OS_EMBEDDED
thread_call_t getAssertionCall();
IOPMDriverAssertionID getAssertionID();
void setAssertionID(IOPMDriverAssertionID assertionID);
AbsoluteTime getAssertionTime();
void setAssertionTime(AbsoluteTime assertionTime);
void lockAssertion();
void unlockAssertion();
#endif /* !TARGET_OS_EMBEDDED */
OSMallocTag getIOStorageMallocTag();
///w:stop
};
static IOMediaBSDClientGlobals gIOMediaBSDClientGlobals;
bool IOMediaBSDClient::init(OSDictionary * properties)
{
//
// Initialize this object's minimal state.
//
// Ask our superclass' opinion.
if ( super::init(properties) == false ) return false;
// Determine whether our minimal global state has been initialized.
if ( gIOMediaBSDClientGlobals.isValid() == false ) return false;
// Initialize this object's minimal state.
_anchors = gIOMediaBSDClientGlobals.getAnchors();
_minors = gIOMediaBSDClientGlobals.getMinors();
return true;
}
void IOMediaBSDClient::free()
{
//
// Free all of this object's outstanding resources.
//
super::free();
}
bool IOMediaBSDClient::start(IOService * provider)
{
//
// This method is called once we have been attached to the provider object.
//
IOMedia * media = (IOMedia *) provider;
// Ask our superclass' opinion.
if ( super::start(provider) == false ) return false;
// Disable access to tables.
gIOMediaBSDClientGlobals.lockState();
// Create bdevsw and cdevsw nodes for the new media object.
createNodes(media);
// Enable access to tables.
gIOMediaBSDClientGlobals.unlockState();
// Register this object so it can be found via notification requests. It is
// not being registered to have I/O Kit attempt to have drivers match on it,
// which is the reason most other services are registered -- that's not the
// intention of this registerService call.
registerService();
return true;
}
bool IOMediaBSDClient::terminate(IOOptionBits options)
{
//
// This method is called when we are to terminate from the provider object.
//
UInt32 minorID;
// Ask our superclass' opinion.
if ( super::terminate(options) == false ) return false;
// Disable access to tables.
gIOMediaBSDClientGlobals.lockState();
// Find the minor assigned to this media.
minorID = gIOMediaBSDClientGlobals.getMinors()->locate(getProvider());
if ( minorID != kInvalidMinorID )
{
MinorSlot * minor;
minor = gIOMediaBSDClientGlobals.getMinors()->getMinor(minorID);
// Remove the minor from the minor table. If an open is still
// outstanding, we mark the minor as obsolete for removal when
// the close comes in later.
if ( minor->bdevOpen || minor->cdevOpen )
{
gIOMediaBSDClientGlobals.getMinors()->obsolete(minorID);
}
else
{
gIOMediaBSDClientGlobals.getMinors()->remove(minorID);
}
}
// Enable access to tables.
gIOMediaBSDClientGlobals.unlockState();
return true;
}
IOMedia * IOMediaBSDClient::getWholeMedia( IOMedia * media,
UInt32 * slicePathSize,
char * slicePath )
{
//
// Find the whole media that roots this media tree. A null return value
// indicates no whole media was found or a malformed tree was detected.
//
// If slicePathSize is non-zero, the size required to fit the slice path
// (including the zero terminator) is passed back as a result.
//
// If slicePathSize and slicePath are both non-zero, the slice path will
// be written into the slicePath buffer. The value slicePathSize points
// to must be the size of the slicePath buffer, which is used for sanity
// checking in this method.
//
// This method assumes that the table (and termination) lock is held.
//
UInt32 depth = 1;
UInt32 position = sizeof('\0');
IOService * service = 0;
assert(slicePath == 0 || slicePathSize != 0);
// Search the registry for the parent whole media for this media.
for ( service = media; service; service = service->getProvider() )
{
if ( OSDynamicCast(IOMedia, service) ) // (is it a media?)
{
if ( ((IOMedia *)service)->isWhole() ) // (is it a whole media?)
{
if ( slicePath ) // (are we building the slice path?)
{
slicePath[*slicePathSize - 1] = 0; // (zero terminate path)
if ( position < *slicePathSize ) // (need to move path?)
{
memmove( slicePath, // (move path to start of buffer)
slicePath + (*slicePathSize - position),
position );
}
}
else if ( slicePathSize ) // (report size req'd for slice path?)
{
*slicePathSize = position;
}
return (IOMedia *)service; // (return the whole media)
}
// Determine whether this non-whole media has a location value. It
// must, by definition of a non-whole media, but if it does not, we
// should return an error condition.
const char * location = service->getLocation();
if ( location == 0 ) // (no location on non-whole media?)
{
if ( service == media ) IOLog(kMsgNoLocation, media->getName());
return 0;
}
// Otherwise, it's a valid non-whole media: we compute the required
// size for the slice path or build the slice path, if so requested.
// Note that the slice path is built backwards from the ends of the
// supplied buffer to the beginning of the buffer.
position += sizeof('s') + strlen(location);
if ( slicePath ) // (build the slice path?)
{
char * path = slicePath + *slicePathSize - position;
if ( position > *slicePathSize ) { assert(0); return 0; }
*path = 's';
strncpy(path + sizeof('s'), location, strlen(location));
}
depth += 1;
}
}
// If we've fallen through, then the whole media was never found.
if ( depth == 1 ) IOLog(kMsgNoWhole, media->getName());
return 0;
}
bool IOMediaBSDClient::createNodes(IOMedia * media)
{
//
// Create bdevsw and cdevsw nodes for the given media object.
//
// This method assumes that the table (and termination) lock is held.
//
IOService * anchor;
AnchorTable * anchors = gIOMediaBSDClientGlobals.getAnchors();
UInt32 anchorID;
bool anchorNew = false;
UInt32 majorID = gIOMediaBSDClientGlobals.getMajorID();
MinorTable * minors = gIOMediaBSDClientGlobals.getMinors();
UInt32 minorID;
char * slicePath = 0;
UInt32 slicePathSize;
IOMedia * whole;
//
// Find the anchor that roots this media tree. The anchor is defined as the
// parent of the whole media that roots this media tree. It is an important
// object to us because this object stays in place when media is ejected, so
// we can continue to maintain the "unit number" of the "drive" such that if
// media is re-inserted, it will show up under the same "unit number". You
// can think of the typical anchor as being the drive, if it helps, although
// it could be one of many other kinds of drivers (eg. a RAID scheme).
//
whole = getWholeMedia(media, &slicePathSize);
if ( whole == 0 ) return false;
anchor = whole->getProvider();
if ( anchor == 0 ) return false;
//
// Determine whether the anchor already exists in the anchor table (obsolete
// occurences are skipped in the search, as appropriate, since those anchor
// IDs are to be removed soon). If the anchor does not exist, insert it into
// anchor table.
//
anchorID = anchors->locate(anchor, whole);
if ( anchorID == kInvalidAnchorID )
{
//
// The anchor and key pair does not exist in the table, however we still
// have more to check. The anchor might in fact exist in the table, but
// have a different key. If such a slot exists, and it isn't referenced
// in the minor table, we reuse the slot.
//
anchorID = anchors->update(anchor, whole);
}
if ( anchorID == kInvalidAnchorID )
{
anchorID = anchors->insert(anchor, whole); // (get new anchor ID)
if ( anchorID == kInvalidAnchorID ) return false;
anchorNew = true;
}
//
// Allocate space for and build the slice path for the device node names.
//
slicePath = (char *) IOMalloc(slicePathSize);
if ( slicePath == 0 ) goto createNodesErr;
whole = getWholeMedia(media, &slicePathSize, slicePath);
assert(whole);
//
// Insert the new media into our minor table (we're almost done :-).
//
minorID = minors->update(media, anchorID, this, slicePath);
if ( minorID == kInvalidMinorID )
{
minorID = minors->insert(media, anchorID, this, slicePath);
if ( minorID == kInvalidMinorID ) goto createNodesErr;
}
//
// Create the required properties on the media.
//
media->setProperty(kIOBSDNameKey, minors->getMinor(minorID)->name);
media->setProperty(kIOBSDUnitKey, anchorID, 32); // ("BSD Unit" )
media->setProperty(kIOBSDMajorKey, majorID, 32); // ("BSD Major")
media->setProperty(kIOBSDMinorKey, minorID, 32); // ("BSD Minor")
//
// Clean up outstanding resources.
//
IOFree(slicePath, slicePathSize);
return true; // (success)
createNodesErr:
if (anchorNew) anchors->remove(anchorID);
if (slicePath) IOFree(slicePath, slicePathSize);
return false; // (failure)
}
IOMedia * IOMediaBSDClient::getProvider() const
{
//
// Obtain this object's provider. We override the superclass's method to
// return a more specific subclass of IOService -- IOMedia. This method
// serves simply as a convenience to subclass developers.
//
return (IOMedia *) IOService::getProvider();
}
int IOMediaBSDClient::ioctl( dev_t dev,
u_long cmd,
caddr_t data,
int flags,
proc_t proc )
{
//
// Process a foreign ioctl.
//
return ENOTTY;
}
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 0);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 1);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 2);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 3);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 4);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 5);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 6);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 7);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 8);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 9);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 10);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 11);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 12);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 13);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 14);
OSMetaClassDefineReservedUnused(IOMediaBSDClient, 15);
// =============================================================================
// BSD Functions
typedef struct
{
user32_addr_t capacities;
uint32_t capacitiesCount;
uint8_t reserved0064[8];
} dk_format_capacities_32_t;
typedef struct
{
user64_addr_t capacities;
uint32_t capacitiesCount;
uint8_t reserved0096[4];
} dk_format_capacities_64_t;
typedef struct
{
user32_addr_t extents;
uint32_t extentsCount;
uint32_t options;
uint8_t reserved0096[4];
} dk_unmap_32_t;
typedef struct
{
user64_addr_t extents;
uint32_t extentsCount;
uint32_t options;
} dk_unmap_64_t;
typedef struct
{
user32_addr_t extents;
uint32_t extentsCount;
uint8_t tier;
uint8_t reserved0072[7];
} dk_set_tier_32_t;
typedef struct
{
user64_addr_t extents;
uint32_t extentsCount;
uint8_t tier;
uint8_t reserved0104[3];
} dk_set_tier_64_t;
static IOStorageAccess DK_ADD_ACCESS(IOStorageAccess a1, IOStorageAccess a2)
{
static UInt8 table[4][4] =
{ /* Rea, Wri, R|S, W|S */
/* Rea */ { 000, 001, 002, 003 },
/* Wri */ { 001, 001, 001, 001 },
/* R|S */ { 002, 001, 002, 003 },
/* W|S */ { 003, 001, 003, 003 }
};
if ( a1 == kIOStorageAccessNone ) return a2;
if ( a2 == kIOStorageAccessNone ) return a1;
a1 = (a1 - 1) >> 1;
a2 = (a2 - 1) >> 1;
if ( a1 > 003 ) return kIOStorageAccessNone;
if ( a2 > 003 ) return kIOStorageAccessNone;
return (table[a1][a2] << 1) + 1;
}
static bool DKIOC_IS_RESERVED(caddr_t data, uint32_t reserved)
{
UInt32 index;
for ( index = 0; index < sizeof(reserved) * 8; index++, reserved >>= 1 )
{
if ( (reserved & 1) )
{
if ( data[index] ) return true;
}
}
return false;
}
#define IOMEDIAWAITQUIET_IN_SECONDS ( 10*1000*1000*1000ULL )
static bool _IOMediaWaitQuietOrInactive( IOMedia * media )
{
bool quiet = false;
if ( media == NULL )
{
return quiet;
}
quiet = ( media->getBusyState() == 0 );
while ( !quiet )
{
//
// Do not wait while I/O Kit is working on terminate the stack
//
if ( media->isInactive() )
break;
//
// Every 10s, check if terminated, bail out if it is
//
media->waitQuiet( IOMEDIAWAITQUIET_IN_SECONDS );
quiet = ( media->getBusyState() == 0 );
}
//
// return TRUE if media is not busy
//
return quiet;
}
UInt64 _IOMediaBSDClientGetThrottleMask(IOMedia * media)
{
UInt64 mask;
mask = 0;
if ( media )
{
int error;
error = EAGAIN;
while ( error )
{
// Iterate through IOBlockStorageDevice objects.
IORegistryIterator * devices;
error = 0;
mask = 0;
devices = IORegistryIterator::iterateOver( media, gIOServicePlane, kIORegistryIterateParents );
if ( devices )
{
IORegistryEntry * device;
device = devices->getNextObjectRecursive( );
while ( device )
{
if ( OSDynamicCast( IOBlockStorageDevice, device ) )
{
// Iterate through IOMedia objects.
IORegistryIterator * services;
services = IORegistryIterator::iterateOver( device, gIOServicePlane );
if ( services )
{
IORegistryEntry * service;
service = services->getNextObjectRecursive( );
while ( service )
{
if ( OSDynamicCast( IOMedia, service ) )
{
// Obtain the BSD Unit property.
OSNumber * unit;
unit = OSDynamicCast( OSNumber, service->getProperty( kIOBSDUnitKey ) );
if ( unit )
{
mask |= 1 << ( unit->unsigned32BitValue( ) % 64 );
}
}
service = services->getNextObjectRecursive( );
}
if ( services->isValid( ) == false )
{
error = EAGAIN;
}
services->release( );
}
///w:start
OSNumber * number;
number = OSDynamicCast( OSNumber, device->getProperty( "throttle-unit" ) );
if ( number )
{
OSDictionary * dictionary;
dictionary = IOService::serviceMatching( kIOMediaClass );
if ( dictionary )
{
OSIterator * iterator;
dictionary->setObject( kIOBSDUnitKey, number );
iterator = IOService::getMatchingServices( dictionary );
if ( iterator )
{
OSObject * object;
object = iterator->getNextObject( );
if ( object )
{
mask |= _IOMediaBSDClientGetThrottleMask( ( IOMedia * ) object );
}
iterator->release( );
}
dictionary->release( );
}
}
///w:stop
devices->exitEntry( );
}
device = devices->getNextObjectRecursive( );
}
if ( devices->isValid( ) == false )
{
error = EAGAIN;
}
devices->release( );
}
}
}
return mask;
}
// Workaround for rdar://23244646, but limit removing the R/W hack to just an
// APFS boot container (concern HFS journal replay depends on the W upgrade).
// See rdar://23170211 and rdar://23265650 about removing it/this entirely.
static int _IOMedia_is_APFS(IOMedia *media)
{
IORegistryIterator * iter;
IORegistryEntry * entry;
bool apfs = false;
if ((iter = IORegistryIterator::iterateOver(media, gIOServicePlane, 0))) {
while ((entry = iter->getNextObject())) {
if (entry->metaCast("AppleAPFSContainer") != NULL) {
apfs = true;
break;
}
}
iter->release();
}
return apfs;
}
int dkopen(dev_t dev, int flags, int devtype, proc_t /* proc */)
{
//
// dkopen opens the device (called on each open).
//
IOStorageAccess access;
int error;
IOStorageAccess level;
IOStorageAccess levelOut;
IOMedia * media;
MinorSlot * minor;
assert(S_ISBLK(devtype) || S_ISCHR(devtype));
gIOMediaBSDClientGlobals.lockOpen(); // (disable access to opens, closes)
gIOMediaBSDClientGlobals.lockState(); // (disable access to state, tables)
access = kIOStorageAccessReader;
access |= (flags & FWRITE) ? kIOStorageAccessReaderWriter : 0;
access |= (flags & O_SHLOCK) ? kIOStorageAccessSharedLock : 0;
access |= (flags & O_EXLOCK) ? kIOStorageAccessExclusiveLock : 0;
error = 0;
media = 0;
minor = gIOMediaBSDClientGlobals.getMinor(getminor(dev));
//
// Process the open.
//
if ( minor == 0 ) // (is minor valid?)
{
error = ENXIO;
}
else if ( minor->isOrphaned ) // (is minor in flux?)
{
error = EBUSY;
}
else
{
///w:start
static int root = 0;
if ( root == 0 )
{
root = 1;
if ( minor->media->isWritable() && !_IOMedia_is_APFS(minor->media) )
{
access |= kIOStorageAccessReaderWriter;
}
}
///w:stop
level = DK_ADD_ACCESS(minor->bdevOpenLevel, minor->cdevOpenLevel);
levelOut = DK_ADD_ACCESS(level, access);
if ( levelOut == kIOStorageAccessNone ) // (is access valid?)
{
error = EBUSY;
}
else if ( (flags & FWRITE) ) // (is client a writer?)
{
if ( minor->media->isWritable() == false )
{
error = EACCES;
}
}
}
if ( error == 0 ) // (go?)
{