-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlisting5.html
executable file
·4098 lines (3328 loc) · 150 KB
/
listing5.html
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
<!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>MFSLives - /MFSLives.c</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/Darwin/index.html">Darwin</a> > <a href="../../samplecode/Darwin/idxFileManagement-date.html">File Management</a> > <A HREF="javascript:location.replace('index.html');">MFSLives</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">MFSLives</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>/MFSLives.c</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">/HashNode.c</option>
<option value="listing2.html">/HashNode.h</option>
<option value="listing3.html">/MFSCore.c</option>
<option value="listing4.html">/MFSCore.h</option>
<option value="listing5.html">/MFSLives.c</option>
<option value="listing6.html">/MFSLivesMountArgs.h</option>
<option value="listing7.html">/MFSLivesPseudoMount.c</option>
<option value="listing8.html">/MFSLivesPseudoMount.h</option>
<option value="listing9.html">/MFSLivesUtil.c</option>
<option value="listing10.html">/MountMFSLives.c</option>
<option value="listing11.html">/Read Me About MFSLives.txt</option>
<option value="listing12.html">/TableGenerator.c</option>
<option value="listing13.html">/TestMFSLives.c</option>
<option value="listing14.html">/UserSpaceKernel.c</option>
<option value="listing15.html">/UserSpaceKernel.h</option>
<option value="listing16.html">/utf8_decodestr.c</option>
<option value="listing17.html">/utf8_decodestr.h</option>
<option value="listing18.html">/VNodeAttr.h</option></select>
</p>
</form>
<p><strong><a href="MFSLives.zip">Download Sample</a></strong> (“MFSLives.zip”, 2.12M)<BR>
<strong><a href="MFSLives.dmg">Download Sample</a></strong> (“MFSLives.dmg”, 2.52M)</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: MFSLives.c
Contains: A VFS plug-in example for MFS volumes (original 400 KB floppies).
Written by: DTS
Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, 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 Computer, 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.
Change History (most recent first):
$Log: MFSLives.c,v $
Revision 1.3 2006/10/31 16:30:03
Updated some comments based on review feedback.
Revision 1.2 2006/10/09 13:11:41
Rewrite VNOPBlockmap to document and adopt pre- and post-conditions from kernel engineering.
Revision 1.1 2006/07/27 15:47:55
First checked in.
*/
/////////////////////////////////////////////////////////////////////
// Our helper modules
#include "MFSCore.h"
#include "HashNode.h"
#include "MFSLivesMountArgs.h"
// System interfaces
#include <kern/assert.h>
#include <libkern/libkern.h>
#include <libkern/OSMalloc.h>
#include <libkern/locks.h>
#include <mach/mach_types.h>
#include <sys/dirent.h>
#include <sys/disk.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/kernel_types.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/proc.h>
#include <sys/stat.h>
#include <sys/ubc.h>
#include <sys/unistd.h>
#include <sys/vnode.h>
#include <sys/vnode_if.h>
#include <sys/xattr.h>
/////////////////////////////////////////////////////////////////////
#pragma mark ***** Source Code Notes
/*
Bit Fields
----------
In places where I initialise a bit field, I include both the active bits
and the inactive bits (commented out). This lets you quickly see all of
the options that are available and the options that I've specifically enabled.
Terminology
-----------
Each volume is made up of a set of file system objects (fsobjs). These objects
are stored on disk (or in some other way, such as across the network). To speed
things up, the system caches information about these file system objects in
memory. The objects in this cache are called vnodes. The cache is managed by
the VFS layer and the VFS plug-in, working in concert.
This cache is /not/ the disk cache (in the traditional sense of the phrase).
A disk cache typically caches the contents of blocks on the disk. Here we're
referring to a cache of information about the file system objects on the volume.
Mac OS X does have a disk cache (called the Unified Buffer Cache, UBC), and this
example interacts with it when it needs to read directory blocks (using the
buf_meta_bread call) and when it reads files (using the cluster_read and
cluster_pagein calls).
A vnode is a virtual representation of a file system object. It's virtual in
the sense that it has no information about the concrete implementation of the
object on disk (or across the network). Rather, it's the handle which the
higher levels of the system use to learn about and manipulate a given file
system object. The only concrete information about the file system object
that stored in the vnode is a reference to the corresponding FSNode.
An FSNode is the in-memory representation of a file system object. An FSNode
is managed by the VFS plug-in, and contains all of the concrete information
needed to manage that file system object. For example, on HFS Plus the FSNode
would store the CNID of the file system object.
We don't use "inode" at all, for two reasons:
o Traditionally, the term "inode" has been used to describe both the
on-disk representation of a file system object /and/ the
in-memory representation of that object (if it's being cached in memory).
That's just confusing (-:
o The term "inode" implies a certain style of on-disk organisation, which is
not universally applicable (for an obvious example, consider a network
file system), and is certainly not applicable to MFS.
Traditionally there is a one-to-one correspondence between vnodes and FSNodes.
However, this not true in the presence of multi-fork files, where there is
one vnode for each fork but all of these refer to the same FSNode.
FSNode Hash
-----------
It's important to realise that the vnode cache is managed globally by the
VFS layer. The VFS plug-in is expected to following along with decisions
made by the VFS layer. However, vnodes are created by the VFS plug-ins,
as they respond to incoming requests.
The most common situation where a VFS plug-in needs to create a vnode is
in VNOPLookup. In this case, the plug-in has information about the file
system object in question (in this example, we have the file number) and
needs to create a vnode for to return as the result of the lookup.
The critical point is that the VFS plug-in MUST NOT create two vnodes
for the same file. Therefore the plug-in must maintain some data structure
that:
o can be accessed quickly based on the information in the file system
object's directory entry (that is, the file number)
o tells the VFS plug-in which file system objects are currently in memory
o can return the vnode, if any, associated with that FSNode
This is typically done using a hash table that indexes all of the FSNodes.
This is keyed by the file system object's raw device number (dev_t) and
inode number (file number in the case of MFS). Getting the mechanics of
this table right is the most difficult part of implementing a VFS plug-in.
In the case of MFSLives, I've moved all of this complexity into a reusable
module. See "HashNode.h" and "HashNode.c" for the details. There's lots
of cool comments in "HashNode.h".
MFS Core
--------
I've put all of the code that actually interprets MFS data structures into
a separate module. See "MFSCore.h" and "MFSCore.c" for the details,
including an explanation of /why/ I did this.
*/
/////////////////////////////////////////////////////////////////////
#pragma mark ***** More Asserts
// We use the system assert macro (from <kern/assert.h>) for standard asserts.
// In some cases we also want to assert that an incoming 'flags' parameter
// has only the bits that we know about set. In this case we use the
// AssertKnownFlags macro. As getting an unknown flag is more of a warning
// than an error, we just print a message and continue execution. And, to
// avoid a flood of junk in the system log, we only print a given message once.
#if MACH_ASSERT
static void AssertKnownFlagsCore(
uint64_t flags,
uint64_t knownFlags,
boolean_t * havePrintedPtr,
const char * fileStr,
int lineNumber,
const char * flagsStr,
const char * knownFlagsStr
)
// Core implementation of AssertKnownFlags.
{
// Check to see if we have any unknown flags.
if ( (flags & ~knownFlags) != 0 ) {
// If so, have we already printed a warning.
if ( (havePrintedPtr == NULL) || ! *havePrintedPtr ) {
// If not, print it.
printf("%s:%d: AssertKnownFlags(%s, %s) saw unknown flags 0x%llx.\n",
fileStr,
lineNumber,
flagsStr,
knownFlagsStr,
flags & ~knownFlags
);
}
// And record that we did.
if (havePrintedPtr != NULL) {
*havePrintedPtr = TRUE;
}
}
}
// In AssertKnownFlags macro, flags is the incoming flags and
// knownFlags is the set of all flags that we knew about when we
// wrote the code.
#define AssertKnownFlags(flags, knownFlags) \
do { \
static boolean_t sHavePrinted; \
AssertKnownFlagsCore((flags), (knownFlags), &sHavePrinted, __FILE__, __LINE__, # flags, # knownFlags); \
} while (0)
#else
#define AssertKnownFlags(flags, knownFlags) do { } while (0)
#endif
/////////////////////////////////////////////////////////////////////
#pragma mark ***** Error Conversion
static errno_t ErrnoFromKernReturn(kern_return_t kernErr)
// Maps a kern_return_t-style error into an errno_t-style error.
{
errno_t err;
if (kernErr == KERN_SUCCESS) {
err = 0;
} else {
err = EINVAL;
}
return err;
}
static kern_return_t KernReturnFromErrno(errno_t err)
// Maps an errno_t-style error into a kern_return_t-style error.
{
kern_return_t kernErr;
if (err == 0) {
kernErr = KERN_SUCCESS;
} else {
kernErr = KERN_FAILURE;
}
return err;
}
/////////////////////////////////////////////////////////////////////
#pragma mark ***** Memory and Locks
// gOSMallocTag is used for all of our allocations.
static OSMallocTag gOSMallocTag = NULL;
// gLockGroup is used for all of our locks.
static lck_grp_t * gLockGroup = NULL;
static void TermMemoryAndLocks(void)
// Disposes of gOSMallocTag and gLockGroup.
{
if (gLockGroup != NULL) {
lck_grp_free(gLockGroup);
gLockGroup = NULL;
}
if (gOSMallocTag != NULL) {
OSMalloc_Tagfree(gOSMallocTag);
gOSMallocTag = NULL;
}
}
static kern_return_t InitMemoryAndLocks(void)
// Initialises of gOSMallocTag and gLockGroup.
{
kern_return_t err;
err = KERN_SUCCESS;
gOSMallocTag = OSMalloc_Tagalloc("com.apple.dts.kext.MFSLives", OSMT_DEFAULT);
if (gOSMallocTag == NULL) {
err = KERN_FAILURE;
}
if (err == KERN_SUCCESS) {
gLockGroup = lck_grp_alloc_init("com.apple.dts.kext.MFSLives", LCK_GRP_ATTR_NULL);
if (gLockGroup == NULL) {
err = KERN_FAILURE;
}
}
// Clean up.
if (err != KERN_SUCCESS) {
TermMemoryAndLocks();
}
assert( (err == KERN_SUCCESS) == (gOSMallocTag != NULL) );
assert( (err == KERN_SUCCESS) == (gLockGroup != NULL) );
return err;
}
/////////////////////////////////////////////////////////////////////
#pragma mark ***** Core Data Structures
// gVNodeOperations is set up when we register the VFS plug-in with vfs_fsadd.
// It holds a pointer to the array of vnode operation functions for this
// VFS plug-in. We have to declare it early in this file because it's referenced
// by the code that creates vnodes.
static errno_t (**gVNodeOperations)(void *);
#pragma mark - FSMount
// FSMount holds the file system specific data that we need per mount point.
// We attach this to the kernel mount_t by calling vfs_setfsprivate in VFSOPMount.
// There is no reference count on this structure; it lives and dies along with the
// corresponding mount_t.
enum {
kFSMountMagic = 'MFMn',
kFSMountBadMagic = 'M!Mn'
};
struct FSMount {
uint32_t fMagic; // [1] must be kFSMountMagic
boolean_t fForceMount; // [1] copied from MFSLivesMountArgs; see "MFSLivesMountArgs.h" for details
boolean_t fForceFailure; // [1] copied from MFSLivesMountArgs; see "MFSLivesMountArgs.h" for details
mount_t fMountPoint; // [1] back pointer to the mount_t
dev_t fBlockRDevNum; // [1] raw dev_t of the device we're mounted on
vnode_t fBlockDevVNode; // [1] a vnode for the above; we have a use count reference on this
size_t fBlockDevBlockSize; // [1] block size, in bytes, for the above
uint64_t fBlockDevBlockCount; // [1] block count for the above
// The next group of values are all obtained from the MFS core when we
// call MFSMDBCheck. They contain all of the information that we need to
// interpret the MFS volume (in concert the with the routines exported by
// the MFS core).
size_t fMDBAndVABMSizeInBytes; // [1] size of combined MDB and VABM, rounded up to the next block size
uint16_t fDirectoryStartBlock; // [1] first block of the directory
uint16_t fDirectoryBlockCount; // [1] number of blocks in the directory
uint16_t fAllocationBlocksStartBlock;// [1] block number that holds the first allocation block
uint32_t fAllocationBlockSizeInBytes;// [1] allocate block size in bytes
void * fMDBVABM; // [1] a pointer to a buffer that holds the MDB/VABM;
// its size is fMDBAndVABMSizeInBytes
};
typedef struct FSMount FSMount;
// FSMount Notes
// -------------
// [1] This field is immutable. That is, it's set up as part of the initialisation
// process, and is not modified after that. Thus, it doesn't need to be
// protected from concurrent access. Yay for read-only file systems!
static FSMount * FSMountFromMount(mount_t mp)
// Gets the FSMount from a mount_t, with appropriate runtime checks in the
// debug version.
{
FSMount * result;
assert(mp != NULL);
result = vfs_fsprivate(mp);
assert(result != NULL);
assert(result->fMagic == kFSMountMagic);
assert(result->fMountPoint == mp);
return result;
}
#if MACH_ASSERT
static boolean_t ValidFSMount(FSMount *fsmp)
{
return (fsmp != NULL) && (fsmp->fMagic == kFSMountMagic);
}
#endif
#pragma mark - FSNode
// FSNode holds the file system specific data that we need per vnode. We attach this
// to the kernel vnode_t when we create a vnode (see the calls to vnode_create below).
// There is no reference count on this structure; its lifetime is controlled by the
// HNode that it's associated with. That's a complex topic that's discussed in detail
// in the comments in "HashNode.h".
enum {
kFSNodeMagic = 'MFFn',
kFSNodeBadMagic = 'M!Fn',
kHNodeMagic = 'MFHn'
};
struct FSNode {
uint32_t fMagic; // [1] must be kFSNodeMagic
boolean_t fInitialised; // [1] true if the FSNode has been initialised
uint16_t fDirBlock; // [1] block number of the file's directory entry; 0 for the root directory FSNode
size_t fDirOffset; // [1] offset of the file's directory entry; 0 for the root directory vnode
MFSForkInfo fForkInfo[2]; // [1] data (index 0) and rsrc (index 1) fork info; see the discussion
// of MFSForkInfo in "MFSCore.h"; all zeros for the root directory FSNode
uint32_t fLastDirOffset; // [2] cache of last valid uio_offset (for directories)
};
typedef struct FSNode FSNode;
// FSNode Notes
// -------------
// [1] This field is immutable. That is, it's set up when the vnode is created,
// and is not modified after that. Thus, it doesn't need to be protected
// from concurrent access. Yay for read-only file systems!
//
// [2] This is a uint32_t because that we can be sure that all reads and writes
// are atomic. We need this because, if two concurrent threads are reading
// through the root directory, they might end up trying to access this field
// simultaneously. As long as those accesses are atomic, we're OK even
// without a lock; the value will always be consistent (even though the threads
// will 'blow' each other's cache). If the accesse are not atomic (for example,
// if this field was an off_t (which is 64 bits, which is non-atomic when accessed
// by 32-bit code), you might get half of value A and half of value B, which would
// be bad (What do you mean, "bad?" / Try to imagine...).
//
// This is a long winded way of saying that we can avoid creating a mutex per
// FSNode by keeping this field small (-:
static FSNode * FSNodeFromVNode(vnode_t vn)
// A version of FSNodeGenericFromVNode that casts the result to the
// correct type (and does more runtime checks).
{
FSNode * result;
result = (FSNode *) FSNodeGenericFromVNode(vn);
assert( (result != NULL) && (result->fMagic == kFSNodeMagic) );
assert(result->fInitialised);
return result;
}
static FSNode * FSNodeFromHNode(HNodeRef hn)
// A version of FSNodeGenericFromHNode that casts the result to the
// correct type (and does more runtime checks).
{
FSNode * result;
result = (FSNode *) FSNodeGenericFromHNode(hn);
assert( (result != NULL) && (result->fMagic == kFSNodeMagic) );
assert(result->fInitialised);
return result;
}
static FSNode * FSNodeFromHNodeUnchecked(HNodeRef hn)
// A version of FSNodeGenericFromHNode that casts the result to the
// correct type but does not check that the FSNode is valid.
// This is used after calling HNodeLookupCreatingIfNecessary, because
// the FSNode could be newly created, and thus not have the correct
// magic.
{
FSNode * result;
result = (FSNode *) FSNodeGenericFromHNode(hn);
assert(result != NULL);
return result;
}
#if MACH_ASSERT
static boolean_t ValidFSNode(FSNode *fsn)
{
assert( (fsn != NULL) && (fsn->fMagic == kFSNodeMagic) );
assert(fsn->fInitialised);
return TRUE;
}
static boolean_t ValidVNode(vnode_t vn)
// Returns true if the vnode is valid on our file system.
{
FSMount * fsmp;
FSNode * fsn;
assert(vn != NULL);
fsmp = FSMountFromMount( vnode_mount(vn) ); // FSMountFromMount has its own assertions
fsn = FSNodeFromVNode(vn); // FSNodeFromVNode has its own assertions
if (vnode_isdir(vn)) {
assert(fsn->fDirBlock == 0);
assert(fsn->fDirOffset == 0);
} else if (vnode_isreg(vn)) {
assert((fsn->fDirBlock >= fsmp->fDirectoryStartBlock) && (fsn->fDirBlock < (fsmp->fDirectoryStartBlock + fsmp->fDirectoryBlockCount)));
assert(fsn->fDirOffset < fsmp->fBlockDevBlockSize);
} else {
assert(FALSE);
}
return (fsmp != NULL);
}
#endif
static void FSNodeScrub(FSNode * fsn)
// This routine is called to clean out an FSNode prior to its memory
// being deallocated. The implementation does not have to worry
// about race conditions; it is the only thread that could be accessing
// the FSNode at this time.
//
// For MFSLives, there is no scrubbable data in the FSNode, so we don't do
// much.
{
fsn->fMagic = kFSNodeBadMagic;
}
/////////////////////////////////////////////////////////////////////
#pragma mark ***** Core Algorithms
// It may seem like there's a lot of redundancy in the following routines
// (FSNodeGetOrCreateRootVNode, FSNodeGetOrCreateFileVNodeByName,
// FSNodeGetOrCreateFileVNodeByID, and their associated subroutines), but
// it wasn't obvious how to refactor them to reduce the redundancy without
// complicating the code excessively. As one goal of this sample is to keep
// things simple, I decided to prefer a lot of simple code over a small
// amount of complex code.
static errno_t FSNodeGetOrCreateRootVNode(FSMount *fsmp, vnode_t *vnPtr)
// Gets the root vnode for the file system, or creates one if none
// exists. This is the core of VFSOPRoot.
//
// fsmp must point to a valid FSMount.
//
// vnPtr must not be NULL. On error, *vnPtr will be NULL. On success,
// *vnPtr will be a vnode with an I/O reference that the caller is
// responsible for releasing.
//
// The overall structure of this routine is dictated by the architecture
// of the hash layer; see the comments in "HashNode.h" for details.
{
int err;
vnode_t vn;
HNodeRef hn;
FSNode * fsn;
assert(ValidFSMount(fsmp));
assert( vnPtr != NULL);
assert(*vnPtr == NULL);
hn = NULL;
vn = NULL;
err = HNodeLookupCreatingIfNecessary(fsmp->fBlockRDevNum, kMFSRootInodeNumber, 0, &hn, &vn);
if ( (err == 0) && (vn == NULL) ) {
struct vnode_fsparam params;
fsn = FSNodeFromHNodeUnchecked(hn);
// If this is a new FSNode, initialise it.
if ( ! fsn->fInitialised ) {
fsn->fMagic = kFSNodeMagic;
fsn->fInitialised = TRUE;
// For the root directory, all other fields can stay zero.
}
// Try to create the vnode.
params.vnfs_mp = fsmp->fMountPoint;
params.vnfs_vtype = VDIR;
params.vnfs_str = NULL;
params.vnfs_dvp = NULL;
params.vnfs_fsnode = hn;
params.vnfs_vops = gVNodeOperations;
params.vnfs_markroot = TRUE;
params.vnfs_marksystem = FALSE;
params.vnfs_rdev = 0; // we don't currently support VBLK or VCHR
params.vnfs_filesize = 0; // not relevant for a directory
// Name caching is completely disabled until I can work through all of the issues.
// Specifically, HFS Plus won't cache a precomposed name, and I think I should
// do the same.
params.vnfs_cnp = NULL;
params.vnfs_flags = VNFS_NOCACHE | VNFS_CANTCACHE;
err = vnode_create(VNCREATE_FLAVOR, sizeof(params), &params, &vn);
assert( (err == 0) == (vn != NULL) );
// Complete our contract with the hash layer.
if (err == 0) {
HNodeAttachVNodeSucceeded(hn, 0, vn);
} else {
if ( HNodeAttachVNodeFailed(hn, 0) ) {
FSNodeScrub(fsn);
HNodeScrubDone(hn);
}
}
}
if (err == 0) {
*vnPtr = vn;
}
assert( (err == 0) == (*vnPtr != NULL) );
return err;
}
static errno_t CheckForForkSpecifier(struct componentname *cn, size_t *forkIndexPtr)
// This routine checks to see if the path component /after/ the current path
// component in cn is a fork specifier. If so, it stores the appropriate
// fork index (0 for data, 1 for rsrc) in *forkIndexPtr.
//
// This routine is used by FSNodeGetOrCreateFileVNodeByName to see if the user
// is trying to open a specific fork.
//
// There are a bunch of possible results:
//
// o If the current path component in cn is the last component, the routine
// does nothing (leaving *forkIndexPtr as 0) and returns 0.
// o If the current path component in cn is not the last component and the
// next path component is a fork specifier, it consumes that component.
// Furthermore:
//
// o If cn indicates that the lookup was for LOOKUP or CREATE, the
// function returns 0.
// o If cn indicates that the lookup was for DELETE or RENAME, the
// function returns 0.
{
int err;
const char * suffix;
static const char kDataForkSpecifier[] = "/..namedfork/data";
static const char kRsrcForkSpecifier[] = "/..namedfork/rsrc";
assert(cn != NULL);
assert( forkIndexPtr != NULL);
assert(*forkIndexPtr == 0);
// If there's another component after this one (which would be kinda weird given that
// we're a flat file system), look to see if it's a valid fork specifier.
err = 0;
if ( !(cn->cn_flags & ISLASTCN) ) {
suffix = cn->cn_nameptr + cn->cn_namelen;
assert(*suffix == '/');
// This is potentially bogus because I can't guarantee that memory pointed to
// by suffix is valid. But this is more-or-less how HFS does it.
if (strncmp(suffix, kDataForkSpecifier, strlen(kDataForkSpecifier)) == 0) {
assert(*forkIndexPtr == 0);
cn->cn_consume = strlen(kDataForkSpecifier);
} else if (strncmp(suffix, kRsrcForkSpecifier, strlen(kRsrcForkSpecifier)) == 0) {
*forkIndexPtr = 1;
cn->cn_consume = strlen(kRsrcForkSpecifier);
}
}
// If we're looking up a resource fork to delete or rename it, that's just wrong
// and we should nip it in the bud. I don't think this is strictly necessary
// (after all we're a read-only file system, but even if we weren't we'd want to make
// this check in our VNOPRemove and VNOPRename entry points), but HFS does it this
// way and I'm reticent to ignore that advice. All-in-all, I can't see this check
// actively causing problems.
if ( (err == 0) && (*forkIndexPtr != 0) && ((cn->cn_nameiop == DELETE) || (cn->cn_nameiop == RENAME)) ) {
err = EPERM;
}
return err;
}
static errno_t SearchDirectoryByName(
FSMount * fsmp,
struct componentname * cn,
uint16_t * dirBlockPtr,
size_t * dirOffsetPtr,
MFSForkInfo forkInfo[],
struct vnode_attr * attr
)
// Searches the MFS directory on a volume (represented by fsmp) for a directory entry
// based on its name (referenced by cn), and returns various attributes of that
// directory entry (*dirBlockPtr, *dirOffsetPtr, forkInfo[0] (data fork info),
// forkInfo[1] (rsrc fork info) and, optionally, attr).
{
int err;
void * tempBuffer;
uint16_t dirBlock;
size_t dirOffset;
assert(ValidFSMount(fsmp));
assert(cn != NULL);
assert(dirBlockPtr != NULL);
assert(dirOffsetPtr != NULL);
assert(forkInfo != NULL);
// attr can be NULL
// Create the temporary buffer used by MFSDirectoryBlockFindEntryByName.
err = 0;
tempBuffer = OSMalloc(kMFSDirectoryBlockFindEntryByNameTempBufferSize, gOSMallocTag);
if (tempBuffer == NULL) {
err = ENOMEM;
}
// Iterate through the directory blocks, reading them into memory, and then calling
// the MFS core to look for the directory item.
if (err == 0) {
// MFSDirectoryBlockFindEntryByname requires that we clear the first byte of
// tempBuffer to tell it that it hasn't seen this buffer before.
*((char *) tempBuffer) = 0;
dirBlock = fsmp->fDirectoryStartBlock;
do {
buf_t buf;
const void * bufData;
buf = NULL;
err = buf_meta_bread(fsmp->fBlockDevVNode, dirBlock, fsmp->fBlockDevBlockSize, NULL, &buf);
if (err == 0) {
bufData = (const void *) buf_dataptr(buf);
assert(bufData != NULL);
err = MFSDirectoryBlockFindEntryByName(
bufData,
fsmp->fBlockDevBlockSize,
cn->cn_nameptr,
cn->cn_namelen,
tempBuffer,
&dirOffset,
attr
);
// If we found the item, return its fork info as well.
if (err == 0) {
err = MFSDirectoryEntryGetForkInfo(bufData, dirOffset, 0, &forkInfo[0]);
}
if (err == 0) {
err = MFSDirectoryEntryGetForkInfo(bufData, dirOffset, 1, &forkInfo[1]);
}
// If we didn't find the item, try the next directory block.
if (err == ENOENT) {
dirBlock += 1;
if (dirBlock < (fsmp->fDirectoryStartBlock + fsmp->fDirectoryBlockCount)) {
err = EAGAIN;
}
}
}
if (buf != NULL) {
buf_brelse(buf);
}
} while (err == EAGAIN);
}
// Copy the results out to the caller.
if (err == 0) {
*dirBlockPtr = dirBlock;
*dirOffsetPtr = dirOffset;
}
// Clean up.
if (tempBuffer != NULL) {
OSFree(tempBuffer, MAXPATHLEN, gOSMallocTag);
}
// Post-conditions
assert( (err != 0) || ((*dirBlockPtr >= fsmp->fDirectoryStartBlock) && (*dirBlockPtr < (fsmp->fDirectoryStartBlock + fsmp->fDirectoryBlockCount))) );
assert( (err != 0) || (*dirOffsetPtr < fsmp->fBlockDevBlockSize) );
return err;
}
static errno_t SearchDirectoryByID(
FSMount * fsmp,
ino_t ino,
uint16_t * dirBlockPtr,
size_t * dirOffsetPtr,
MFSForkInfo forkInfo[],
struct vnode_attr * attr
)
// Searches the MFS directory on a volume (represented by fsmp) for a directory
// entry based on its file number (ino), and returns various attributes of that
// directory entry (*dirBlockPtr, *dirOffsetPtr, forkInfo[0] (data fork info),
// forkInfo[1] (rsrc fork info) and, optionally, attr).
{
int err;
uint16_t dirBlock;
size_t dirOffset;
assert(ValidFSMount(fsmp));
// ino can be anything
assert(dirBlockPtr != NULL);
assert(dirOffsetPtr != NULL);
assert(forkInfo != NULL);
// attr can be NULL
// Iterate through the directory blocks, reading them into memory, and then calling
// the MFS core to iterate through each item in the block, looking for the one
// with the correct file number.
dirBlock = fsmp->fDirectoryStartBlock;
do {
buf_t buf;
const void * bufData;
boolean_t found;
buf = NULL;
err = buf_meta_bread(fsmp->fBlockDevVNode, dirBlock, fsmp->fBlockDevBlockSize, NULL, &buf);
if (err == 0) {
bufData = (const void *) buf_dataptr(buf);
assert(bufData != NULL);
found = FALSE;
dirOffset = kMFSDirectoryBlockIterateFromStart;
do {
struct vnode_attr tmpAttr;
VATTR_INIT(&tmpAttr);
VATTR_WANTED(&tmpAttr, va_fileid);
err = MFSDirectoryBlockIterate(
bufData,
fsmp->fBlockDevBlockSize,
&dirOffset,
&tmpAttr
);
if (err == 0) {
found = (tmpAttr.va_fileid == ino);
}
} while ( (err == 0) && ! found);
// If we found the item, return its attributes and fork info as well.
if ( (err == 0) && (attr != NULL) ) {
err = MFSDirectoryEntryGetAttr(bufData, dirOffset, attr);
}
if (err == 0) {
err = MFSDirectoryEntryGetForkInfo(bufData, dirOffset, 0, &forkInfo[0]);
}
if (err == 0) {
err = MFSDirectoryEntryGetForkInfo(bufData, dirOffset, 1, &forkInfo[1]);
}
// If we didn't find the item, try the next directory block.