]> git.saurik.com Git - apple/xnu.git/blob - bsd/hfs/hfs_vfsutils.c
xnu-1228.5.20.tar.gz
[apple/xnu.git] / bsd / hfs / hfs_vfsutils.c
1 /*
2 * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* @(#)hfs_vfsutils.c 4.0
29 *
30 * (c) 1997-2002 Apple Computer, Inc. All Rights Reserved
31 *
32 * hfs_vfsutils.c -- Routines that go between the HFS layer and the VFS.
33 *
34 */
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/stat.h>
40 #include <sys/mount.h>
41 #include <sys/buf.h>
42 #include <sys/buf_internal.h>
43 #include <sys/ubc.h>
44 #include <sys/unistd.h>
45 #include <sys/utfconv.h>
46 #include <sys/kauth.h>
47 #include <sys/fcntl.h>
48 #include <sys/vnode_internal.h>
49
50 #include <libkern/OSAtomic.h>
51
52 #include "hfs.h"
53 #include "hfs_catalog.h"
54 #include "hfs_dbg.h"
55 #include "hfs_mount.h"
56 #include "hfs_endian.h"
57 #include "hfs_cnode.h"
58 #include "hfs_fsctl.h"
59
60 #include "hfscommon/headers/FileMgrInternal.h"
61 #include "hfscommon/headers/BTreesInternal.h"
62 #include "hfscommon/headers/HFSUnicodeWrappers.h"
63
64 static void ReleaseMetaFileVNode(struct vnode *vp);
65 static int hfs_late_journal_init(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp, void *_args);
66
67 static void hfs_metadatazone_init(struct hfsmount *);
68 static u_int32_t hfs_hotfile_freeblocks(struct hfsmount *);
69
70
71 //*******************************************************************************
72 // Note: Finder information in the HFS/HFS+ metadata are considered opaque and
73 // hence are not in the right byte order on little endian machines. It is
74 // the responsibility of the finder and other clients to swap the data.
75 //*******************************************************************************
76
77 //*******************************************************************************
78 // Routine: hfs_MountHFSVolume
79 //
80 //
81 //*******************************************************************************
82 unsigned char hfs_catname[] = "Catalog B-tree";
83 unsigned char hfs_extname[] = "Extents B-tree";
84 unsigned char hfs_vbmname[] = "Volume Bitmap";
85 unsigned char hfs_attrname[] = "Attribute B-tree";
86 unsigned char hfs_startupname[] = "Startup File";
87
88
89 __private_extern__
90 OSErr hfs_MountHFSVolume(struct hfsmount *hfsmp, HFSMasterDirectoryBlock *mdb,
91 __unused struct proc *p)
92 {
93 ExtendedVCB *vcb = HFSTOVCB(hfsmp);
94 int error;
95 ByteCount utf8chars;
96 struct cat_desc cndesc;
97 struct cat_attr cnattr;
98 struct cat_fork fork;
99
100 /* Block size must be a multiple of 512 */
101 if (SWAP_BE32(mdb->drAlBlkSiz) == 0 ||
102 (SWAP_BE32(mdb->drAlBlkSiz) & 0x01FF) != 0)
103 return (EINVAL);
104
105 /* don't mount a writeable volume if its dirty, it must be cleaned by fsck_hfs */
106 if (((hfsmp->hfs_flags & HFS_READ_ONLY) == 0) &&
107 ((SWAP_BE16(mdb->drAtrb) & kHFSVolumeUnmountedMask) == 0)) {
108 return (EINVAL);
109 }
110 hfsmp->hfs_flags |= HFS_STANDARD;
111 /*
112 * The MDB seems OK: transfer info from it into VCB
113 * Note - the VCB starts out clear (all zeros)
114 *
115 */
116 vcb->vcbSigWord = SWAP_BE16 (mdb->drSigWord);
117 vcb->vcbCrDate = to_bsd_time(LocalToUTC(SWAP_BE32(mdb->drCrDate)));
118 vcb->localCreateDate = SWAP_BE32 (mdb->drCrDate);
119 vcb->vcbLsMod = to_bsd_time(LocalToUTC(SWAP_BE32(mdb->drLsMod)));
120 vcb->vcbAtrb = SWAP_BE16 (mdb->drAtrb);
121 vcb->vcbNmFls = SWAP_BE16 (mdb->drNmFls);
122 vcb->vcbVBMSt = SWAP_BE16 (mdb->drVBMSt);
123 vcb->nextAllocation = SWAP_BE16 (mdb->drAllocPtr);
124 vcb->totalBlocks = SWAP_BE16 (mdb->drNmAlBlks);
125 vcb->allocLimit = vcb->totalBlocks;
126 vcb->blockSize = SWAP_BE32 (mdb->drAlBlkSiz);
127 vcb->vcbClpSiz = SWAP_BE32 (mdb->drClpSiz);
128 vcb->vcbAlBlSt = SWAP_BE16 (mdb->drAlBlSt);
129 vcb->vcbNxtCNID = SWAP_BE32 (mdb->drNxtCNID);
130 vcb->freeBlocks = SWAP_BE16 (mdb->drFreeBks);
131 vcb->vcbVolBkUp = to_bsd_time(LocalToUTC(SWAP_BE32(mdb->drVolBkUp)));
132 vcb->vcbWrCnt = SWAP_BE32 (mdb->drWrCnt);
133 vcb->vcbNmRtDirs = SWAP_BE16 (mdb->drNmRtDirs);
134 vcb->vcbFilCnt = SWAP_BE32 (mdb->drFilCnt);
135 vcb->vcbDirCnt = SWAP_BE32 (mdb->drDirCnt);
136 bcopy(mdb->drFndrInfo, vcb->vcbFndrInfo, sizeof(vcb->vcbFndrInfo));
137 if ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0)
138 vcb->vcbWrCnt++; /* Compensate for write of MDB on last flush */
139
140 /* convert hfs encoded name into UTF-8 string */
141 error = hfs_to_utf8(vcb, mdb->drVN, NAME_MAX, &utf8chars, vcb->vcbVN);
142 /*
143 * When an HFS name cannot be encoded with the current
144 * volume encoding we use MacRoman as a fallback.
145 */
146 if (error || (utf8chars == 0))
147 (void) mac_roman_to_utf8(mdb->drVN, NAME_MAX, &utf8chars, vcb->vcbVN);
148
149 hfsmp->hfs_logBlockSize = BestBlockSizeFit(vcb->blockSize, MAXBSIZE, hfsmp->hfs_phys_block_size);
150 vcb->vcbVBMIOSize = kHFSBlockSize;
151
152 hfsmp->hfs_alt_id_sector = HFS_ALT_SECTOR(hfsmp->hfs_phys_block_size,
153 hfsmp->hfs_phys_block_count);
154
155 bzero(&cndesc, sizeof(cndesc));
156 cndesc.cd_parentcnid = kHFSRootParentID;
157 cndesc.cd_flags |= CD_ISMETA;
158 bzero(&cnattr, sizeof(cnattr));
159 cnattr.ca_linkcount = 1;
160 cnattr.ca_mode = S_IFREG;
161 bzero(&fork, sizeof(fork));
162
163 /*
164 * Set up Extents B-tree vnode
165 */
166 cndesc.cd_nameptr = hfs_extname;
167 cndesc.cd_namelen = strlen((char *)hfs_extname);
168 cndesc.cd_cnid = cnattr.ca_fileid = kHFSExtentsFileID;
169 fork.cf_size = SWAP_BE32(mdb->drXTFlSize);
170 fork.cf_blocks = fork.cf_size / vcb->blockSize;
171 fork.cf_clump = SWAP_BE32(mdb->drXTClpSiz);
172 fork.cf_vblocks = 0;
173 fork.cf_extents[0].startBlock = SWAP_BE16(mdb->drXTExtRec[0].startBlock);
174 fork.cf_extents[0].blockCount = SWAP_BE16(mdb->drXTExtRec[0].blockCount);
175 fork.cf_extents[1].startBlock = SWAP_BE16(mdb->drXTExtRec[1].startBlock);
176 fork.cf_extents[1].blockCount = SWAP_BE16(mdb->drXTExtRec[1].blockCount);
177 fork.cf_extents[2].startBlock = SWAP_BE16(mdb->drXTExtRec[2].startBlock);
178 fork.cf_extents[2].blockCount = SWAP_BE16(mdb->drXTExtRec[2].blockCount);
179 cnattr.ca_blocks = fork.cf_blocks;
180
181 error = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &fork,
182 &hfsmp->hfs_extents_vp);
183 if (error) goto MtVolErr;
184 error = MacToVFSError(BTOpenPath(VTOF(hfsmp->hfs_extents_vp),
185 (KeyCompareProcPtr)CompareExtentKeys));
186 if (error) {
187 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
188 goto MtVolErr;
189 }
190 hfsmp->hfs_extents_cp = VTOC(hfsmp->hfs_extents_vp);
191
192 /*
193 * Set up Catalog B-tree vnode...
194 */
195 cndesc.cd_nameptr = hfs_catname;
196 cndesc.cd_namelen = strlen((char *)hfs_catname);
197 cndesc.cd_cnid = cnattr.ca_fileid = kHFSCatalogFileID;
198 fork.cf_size = SWAP_BE32(mdb->drCTFlSize);
199 fork.cf_blocks = fork.cf_size / vcb->blockSize;
200 fork.cf_clump = SWAP_BE32(mdb->drCTClpSiz);
201 fork.cf_vblocks = 0;
202 fork.cf_extents[0].startBlock = SWAP_BE16(mdb->drCTExtRec[0].startBlock);
203 fork.cf_extents[0].blockCount = SWAP_BE16(mdb->drCTExtRec[0].blockCount);
204 fork.cf_extents[1].startBlock = SWAP_BE16(mdb->drCTExtRec[1].startBlock);
205 fork.cf_extents[1].blockCount = SWAP_BE16(mdb->drCTExtRec[1].blockCount);
206 fork.cf_extents[2].startBlock = SWAP_BE16(mdb->drCTExtRec[2].startBlock);
207 fork.cf_extents[2].blockCount = SWAP_BE16(mdb->drCTExtRec[2].blockCount);
208 cnattr.ca_blocks = fork.cf_blocks;
209
210 error = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &fork,
211 &hfsmp->hfs_catalog_vp);
212 if (error) {
213 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
214 goto MtVolErr;
215 }
216 error = MacToVFSError(BTOpenPath(VTOF(hfsmp->hfs_catalog_vp),
217 (KeyCompareProcPtr)CompareCatalogKeys));
218 if (error) {
219 hfs_unlock(VTOC(hfsmp->hfs_catalog_vp));
220 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
221 goto MtVolErr;
222 }
223 hfsmp->hfs_catalog_cp = VTOC(hfsmp->hfs_catalog_vp);
224
225 /*
226 * Set up dummy Allocation file vnode (used only for locking bitmap)
227 */
228 cndesc.cd_nameptr = hfs_vbmname;
229 cndesc.cd_namelen = strlen((char *)hfs_vbmname);
230 cndesc.cd_cnid = cnattr.ca_fileid = kHFSAllocationFileID;
231 bzero(&fork, sizeof(fork));
232 cnattr.ca_blocks = 0;
233
234 error = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &fork,
235 &hfsmp->hfs_allocation_vp);
236 if (error) {
237 hfs_unlock(VTOC(hfsmp->hfs_catalog_vp));
238 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
239 goto MtVolErr;
240 }
241 hfsmp->hfs_allocation_cp = VTOC(hfsmp->hfs_allocation_vp);
242
243 /* mark the volume dirty (clear clean unmount bit) */
244 vcb->vcbAtrb &= ~kHFSVolumeUnmountedMask;
245
246 /*
247 * all done with system files so we can unlock now...
248 */
249 hfs_unlock(VTOC(hfsmp->hfs_allocation_vp));
250 hfs_unlock(VTOC(hfsmp->hfs_catalog_vp));
251 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
252
253 if (error == noErr)
254 {
255 error = cat_idlookup(hfsmp, kHFSRootFolderID, 0, NULL, NULL, NULL);
256 }
257
258 if ( error == noErr )
259 {
260 if ( !(vcb->vcbAtrb & kHFSVolumeHardwareLockMask) ) // if the disk is not write protected
261 {
262 MarkVCBDirty( vcb ); // mark VCB dirty so it will be written
263 }
264 }
265 goto CmdDone;
266
267 //-- Release any resources allocated so far before exiting with an error:
268 MtVolErr:
269 ReleaseMetaFileVNode(hfsmp->hfs_catalog_vp);
270 ReleaseMetaFileVNode(hfsmp->hfs_extents_vp);
271
272 CmdDone:
273 return (error);
274 }
275
276 //*******************************************************************************
277 // Routine: hfs_MountHFSPlusVolume
278 //
279 //
280 //*******************************************************************************
281
282 __private_extern__
283 OSErr hfs_MountHFSPlusVolume(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp,
284 off_t embeddedOffset, u_int64_t disksize, __unused struct proc *p, void *args, kauth_cred_t cred)
285 {
286 register ExtendedVCB *vcb;
287 struct cat_desc cndesc;
288 struct cat_attr cnattr;
289 struct cat_fork cfork;
290 u_int32_t blockSize;
291 daddr64_t spare_sectors;
292 struct BTreeInfoRec btinfo;
293 u_int16_t signature;
294 u_int16_t hfs_version;
295 int i;
296 OSErr retval;
297
298 signature = SWAP_BE16(vhp->signature);
299 hfs_version = SWAP_BE16(vhp->version);
300
301 if (signature == kHFSPlusSigWord) {
302 if (hfs_version != kHFSPlusVersion) {
303 printf("hfs_mount: invalid HFS+ version: %d\n", hfs_version);
304 return (EINVAL);
305 }
306 } else if (signature == kHFSXSigWord) {
307 if (hfs_version != kHFSXVersion) {
308 printf("hfs_mount: invalid HFSX version: %d\n", hfs_version);
309 return (EINVAL);
310 }
311 /* The in-memory signature is always 'H+'. */
312 signature = kHFSPlusSigWord;
313 hfsmp->hfs_flags |= HFS_X;
314 } else {
315 /* Removed printf for invalid HFS+ signature because it gives
316 * false error for UFS root volume
317 */
318 return (EINVAL);
319 }
320
321 /* Block size must be at least 512 and a power of 2 */
322 blockSize = SWAP_BE32(vhp->blockSize);
323 if (blockSize < 512 || !powerof2(blockSize))
324 return (EINVAL);
325
326 /* don't mount a writable volume if its dirty, it must be cleaned by fsck_hfs */
327 if ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0 && hfsmp->jnl == NULL &&
328 (SWAP_BE32(vhp->attributes) & kHFSVolumeUnmountedMask) == 0)
329 return (EINVAL);
330
331 /* Make sure we can live with the physical block size. */
332 if ((disksize & (hfsmp->hfs_phys_block_size - 1)) ||
333 (embeddedOffset & (hfsmp->hfs_phys_block_size - 1)) ||
334 (blockSize < hfsmp->hfs_phys_block_size)) {
335 return (ENXIO);
336 }
337 /*
338 * The VolumeHeader seems OK: transfer info from it into VCB
339 * Note - the VCB starts out clear (all zeros)
340 */
341 vcb = HFSTOVCB(hfsmp);
342
343 vcb->vcbSigWord = signature;
344 vcb->vcbJinfoBlock = SWAP_BE32(vhp->journalInfoBlock);
345 vcb->vcbLsMod = to_bsd_time(SWAP_BE32(vhp->modifyDate));
346 vcb->vcbAtrb = SWAP_BE32(vhp->attributes);
347 vcb->vcbClpSiz = SWAP_BE32(vhp->rsrcClumpSize);
348 vcb->vcbNxtCNID = SWAP_BE32(vhp->nextCatalogID);
349 vcb->vcbVolBkUp = to_bsd_time(SWAP_BE32(vhp->backupDate));
350 vcb->vcbWrCnt = SWAP_BE32(vhp->writeCount);
351 vcb->vcbFilCnt = SWAP_BE32(vhp->fileCount);
352 vcb->vcbDirCnt = SWAP_BE32(vhp->folderCount);
353
354 /* copy 32 bytes of Finder info */
355 bcopy(vhp->finderInfo, vcb->vcbFndrInfo, sizeof(vhp->finderInfo));
356
357 vcb->vcbAlBlSt = 0; /* hfs+ allocation blocks start at first block of volume */
358 if ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0)
359 vcb->vcbWrCnt++; /* compensate for write of Volume Header on last flush */
360
361 /* Now fill in the Extended VCB info */
362 vcb->nextAllocation = SWAP_BE32(vhp->nextAllocation);
363 vcb->totalBlocks = SWAP_BE32(vhp->totalBlocks);
364 vcb->allocLimit = vcb->totalBlocks;
365 vcb->freeBlocks = SWAP_BE32(vhp->freeBlocks);
366 vcb->blockSize = blockSize;
367 vcb->encodingsBitmap = SWAP_BE64(vhp->encodingsBitmap);
368 vcb->localCreateDate = SWAP_BE32(vhp->createDate);
369
370 vcb->hfsPlusIOPosOffset = embeddedOffset;
371
372 /* Default to no free block reserve */
373 vcb->reserveBlocks = 0;
374
375 /*
376 * Update the logical block size in the mount struct
377 * (currently set up from the wrapper MDB) using the
378 * new blocksize value:
379 */
380 hfsmp->hfs_logBlockSize = BestBlockSizeFit(vcb->blockSize, MAXBSIZE, hfsmp->hfs_phys_block_size);
381 vcb->vcbVBMIOSize = min(vcb->blockSize, MAXPHYSIO);
382
383 /*
384 * Validate and initialize the location of the alternate volume header.
385 */
386 spare_sectors = hfsmp->hfs_phys_block_count -
387 (((daddr64_t)vcb->totalBlocks * blockSize) /
388 hfsmp->hfs_phys_block_size);
389
390 if (spare_sectors > (blockSize / hfsmp->hfs_phys_block_size)) {
391 hfsmp->hfs_alt_id_sector = 0; /* partition has grown! */
392 } else {
393 hfsmp->hfs_alt_id_sector = (hfsmp->hfsPlusIOPosOffset / hfsmp->hfs_phys_block_size) +
394 HFS_ALT_SECTOR(hfsmp->hfs_phys_block_size,
395 hfsmp->hfs_phys_block_count);
396 }
397
398 bzero(&cndesc, sizeof(cndesc));
399 cndesc.cd_parentcnid = kHFSRootParentID;
400 cndesc.cd_flags |= CD_ISMETA;
401 bzero(&cnattr, sizeof(cnattr));
402 cnattr.ca_linkcount = 1;
403 cnattr.ca_mode = S_IFREG;
404
405 /*
406 * Set up Extents B-tree vnode
407 */
408 cndesc.cd_nameptr = hfs_extname;
409 cndesc.cd_namelen = strlen((char *)hfs_extname);
410 cndesc.cd_cnid = cnattr.ca_fileid = kHFSExtentsFileID;
411
412 cfork.cf_size = SWAP_BE64 (vhp->extentsFile.logicalSize);
413 cfork.cf_clump = SWAP_BE32 (vhp->extentsFile.clumpSize);
414 cfork.cf_blocks = SWAP_BE32 (vhp->extentsFile.totalBlocks);
415 cfork.cf_vblocks = 0;
416 cnattr.ca_blocks = cfork.cf_blocks;
417 for (i = 0; i < kHFSPlusExtentDensity; i++) {
418 cfork.cf_extents[i].startBlock =
419 SWAP_BE32 (vhp->extentsFile.extents[i].startBlock);
420 cfork.cf_extents[i].blockCount =
421 SWAP_BE32 (vhp->extentsFile.extents[i].blockCount);
422 }
423 retval = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cfork,
424 &hfsmp->hfs_extents_vp);
425 if (retval)
426 goto ErrorExit;
427 hfsmp->hfs_extents_cp = VTOC(hfsmp->hfs_extents_vp);
428 hfs_unlock(hfsmp->hfs_extents_cp);
429
430 retval = MacToVFSError(BTOpenPath(VTOF(hfsmp->hfs_extents_vp),
431 (KeyCompareProcPtr) CompareExtentKeysPlus));
432 if (retval)
433 goto ErrorExit;
434 /*
435 * Set up Catalog B-tree vnode
436 */
437 cndesc.cd_nameptr = hfs_catname;
438 cndesc.cd_namelen = strlen((char *)hfs_catname);
439 cndesc.cd_cnid = cnattr.ca_fileid = kHFSCatalogFileID;
440
441 cfork.cf_size = SWAP_BE64 (vhp->catalogFile.logicalSize);
442 cfork.cf_clump = SWAP_BE32 (vhp->catalogFile.clumpSize);
443 cfork.cf_blocks = SWAP_BE32 (vhp->catalogFile.totalBlocks);
444 cfork.cf_vblocks = 0;
445 cnattr.ca_blocks = cfork.cf_blocks;
446 for (i = 0; i < kHFSPlusExtentDensity; i++) {
447 cfork.cf_extents[i].startBlock =
448 SWAP_BE32 (vhp->catalogFile.extents[i].startBlock);
449 cfork.cf_extents[i].blockCount =
450 SWAP_BE32 (vhp->catalogFile.extents[i].blockCount);
451 }
452 retval = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cfork,
453 &hfsmp->hfs_catalog_vp);
454 if (retval) {
455 goto ErrorExit;
456 }
457 hfsmp->hfs_catalog_cp = VTOC(hfsmp->hfs_catalog_vp);
458 hfs_unlock(hfsmp->hfs_catalog_cp);
459
460 retval = MacToVFSError(BTOpenPath(VTOF(hfsmp->hfs_catalog_vp),
461 (KeyCompareProcPtr) CompareExtendedCatalogKeys));
462 if (retval) {
463 goto ErrorExit;
464 }
465 if ((hfsmp->hfs_flags & HFS_X) &&
466 BTGetInformation(VTOF(hfsmp->hfs_catalog_vp), 0, &btinfo) == 0) {
467 if (btinfo.keyCompareType == kHFSBinaryCompare) {
468 hfsmp->hfs_flags |= HFS_CASE_SENSITIVE;
469 /* Install a case-sensitive key compare */
470 (void) BTOpenPath(VTOF(hfsmp->hfs_catalog_vp),
471 (KeyCompareProcPtr)cat_binarykeycompare);
472 }
473 }
474
475 /*
476 * Set up Allocation file vnode
477 */
478 cndesc.cd_nameptr = hfs_vbmname;
479 cndesc.cd_namelen = strlen((char *)hfs_vbmname);
480 cndesc.cd_cnid = cnattr.ca_fileid = kHFSAllocationFileID;
481
482 cfork.cf_size = SWAP_BE64 (vhp->allocationFile.logicalSize);
483 cfork.cf_clump = SWAP_BE32 (vhp->allocationFile.clumpSize);
484 cfork.cf_blocks = SWAP_BE32 (vhp->allocationFile.totalBlocks);
485 cfork.cf_vblocks = 0;
486 cnattr.ca_blocks = cfork.cf_blocks;
487 for (i = 0; i < kHFSPlusExtentDensity; i++) {
488 cfork.cf_extents[i].startBlock =
489 SWAP_BE32 (vhp->allocationFile.extents[i].startBlock);
490 cfork.cf_extents[i].blockCount =
491 SWAP_BE32 (vhp->allocationFile.extents[i].blockCount);
492 }
493 retval = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cfork,
494 &hfsmp->hfs_allocation_vp);
495 if (retval) {
496 goto ErrorExit;
497 }
498 hfsmp->hfs_allocation_cp = VTOC(hfsmp->hfs_allocation_vp);
499 hfs_unlock(hfsmp->hfs_allocation_cp);
500
501 /*
502 * Set up Attribute B-tree vnode
503 */
504 if (vhp->attributesFile.totalBlocks != 0) {
505 cndesc.cd_nameptr = hfs_attrname;
506 cndesc.cd_namelen = strlen((char *)hfs_attrname);
507 cndesc.cd_cnid = cnattr.ca_fileid = kHFSAttributesFileID;
508
509 cfork.cf_size = SWAP_BE64 (vhp->attributesFile.logicalSize);
510 cfork.cf_clump = SWAP_BE32 (vhp->attributesFile.clumpSize);
511 cfork.cf_blocks = SWAP_BE32 (vhp->attributesFile.totalBlocks);
512 cfork.cf_vblocks = 0;
513 cnattr.ca_blocks = cfork.cf_blocks;
514 for (i = 0; i < kHFSPlusExtentDensity; i++) {
515 cfork.cf_extents[i].startBlock =
516 SWAP_BE32 (vhp->attributesFile.extents[i].startBlock);
517 cfork.cf_extents[i].blockCount =
518 SWAP_BE32 (vhp->attributesFile.extents[i].blockCount);
519 }
520 retval = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cfork,
521 &hfsmp->hfs_attribute_vp);
522 if (retval) {
523 goto ErrorExit;
524 }
525 hfsmp->hfs_attribute_cp = VTOC(hfsmp->hfs_attribute_vp);
526 hfs_unlock(hfsmp->hfs_attribute_cp);
527 retval = MacToVFSError(BTOpenPath(VTOF(hfsmp->hfs_attribute_vp),
528 (KeyCompareProcPtr) hfs_attrkeycompare));
529 if (retval) {
530 goto ErrorExit;
531 }
532 }
533
534 /*
535 * Set up Startup file vnode
536 */
537 if (vhp->startupFile.totalBlocks != 0) {
538 cndesc.cd_nameptr = hfs_startupname;
539 cndesc.cd_namelen = strlen((char *)hfs_startupname);
540 cndesc.cd_cnid = cnattr.ca_fileid = kHFSStartupFileID;
541
542 cfork.cf_size = SWAP_BE64 (vhp->startupFile.logicalSize);
543 cfork.cf_clump = SWAP_BE32 (vhp->startupFile.clumpSize);
544 cfork.cf_blocks = SWAP_BE32 (vhp->startupFile.totalBlocks);
545 cfork.cf_vblocks = 0;
546 cnattr.ca_blocks = cfork.cf_blocks;
547 for (i = 0; i < kHFSPlusExtentDensity; i++) {
548 cfork.cf_extents[i].startBlock =
549 SWAP_BE32 (vhp->startupFile.extents[i].startBlock);
550 cfork.cf_extents[i].blockCount =
551 SWAP_BE32 (vhp->startupFile.extents[i].blockCount);
552 }
553 retval = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cfork,
554 &hfsmp->hfs_startup_vp);
555 if (retval) {
556 goto ErrorExit;
557 }
558 hfsmp->hfs_startup_cp = VTOC(hfsmp->hfs_startup_vp);
559 hfs_unlock(hfsmp->hfs_startup_cp);
560 }
561
562 /* Pick up volume name and create date */
563 retval = cat_idlookup(hfsmp, kHFSRootFolderID, 0, &cndesc, &cnattr, NULL);
564 if (retval) {
565 goto ErrorExit;
566 }
567 vcb->vcbCrDate = cnattr.ca_itime;
568 vcb->volumeNameEncodingHint = cndesc.cd_encoding;
569 bcopy(cndesc.cd_nameptr, vcb->vcbVN, min(255, cndesc.cd_namelen));
570 cat_releasedesc(&cndesc);
571
572 /* mark the volume dirty (clear clean unmount bit) */
573 vcb->vcbAtrb &= ~kHFSVolumeUnmountedMask;
574 if (hfsmp->jnl && (hfsmp->hfs_flags & HFS_READ_ONLY) == 0) {
575 hfs_flushvolumeheader(hfsmp, TRUE, 0);
576 }
577
578 /* kHFSHasFolderCount is only supported/updated on HFSX volumes */
579 if ((hfsmp->hfs_flags & HFS_X) != 0) {
580 hfsmp->hfs_flags |= HFS_FOLDERCOUNT;
581 }
582
583 //
584 // Check if we need to do late journal initialization. This only
585 // happens if a previous version of MacOS X (or 9) touched the disk.
586 // In that case hfs_late_journal_init() will go re-locate the journal
587 // and journal_info_block files and validate that they're still kosher.
588 //
589 if ( (vcb->vcbAtrb & kHFSVolumeJournaledMask)
590 && (SWAP_BE32(vhp->lastMountedVersion) != kHFSJMountVersion)
591 && (hfsmp->jnl == NULL)) {
592
593 retval = hfs_late_journal_init(hfsmp, vhp, args);
594 if (retval != 0) {
595 hfsmp->jnl = NULL;
596
597 // if the journal failed to open, then set the lastMountedVersion
598 // to be "FSK!" which fsck_hfs will see and force the fsck instead
599 // of just bailing out because the volume is journaled.
600 if (!(hfsmp->hfs_flags & HFS_READ_ONLY)) {
601 HFSPlusVolumeHeader *jvhp;
602 daddr64_t mdb_offset;
603 struct buf *bp = NULL;
604
605 hfsmp->hfs_flags |= HFS_NEED_JNL_RESET;
606
607 mdb_offset = (daddr64_t)((embeddedOffset / blockSize) + HFS_PRI_SECTOR(blockSize));
608
609 retval = (int)buf_meta_bread(hfsmp->hfs_devvp, mdb_offset, blockSize, cred, &bp);
610 if (retval == 0) {
611 jvhp = (HFSPlusVolumeHeader *)(buf_dataptr(bp) + HFS_PRI_OFFSET(blockSize));
612
613 if (SWAP_BE16(jvhp->signature) == kHFSPlusSigWord || SWAP_BE16(jvhp->signature) == kHFSXSigWord) {
614 printf ("hfs(3): Journal replay fail. Writing lastMountVersion as FSK!\n");
615 jvhp->lastMountedVersion = SWAP_BE32(kFSKMountVersion);
616 buf_bwrite(bp);
617 } else {
618 buf_brelse(bp);
619 }
620 bp = NULL;
621 } else if (bp) {
622 buf_brelse(bp);
623 // clear this so the error exit path won't try to use it
624 bp = NULL;
625 }
626 }
627
628 retval = EINVAL;
629 goto ErrorExit;
630 } else if (hfsmp->jnl) {
631 vfs_setflags(hfsmp->hfs_mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
632 }
633 } else if (hfsmp->jnl || ((vcb->vcbAtrb & kHFSVolumeJournaledMask) && (hfsmp->hfs_flags & HFS_READ_ONLY))) {
634 struct cat_attr jinfo_attr, jnl_attr;
635
636 if (hfsmp->hfs_flags & HFS_READ_ONLY) {
637 vcb->vcbAtrb &= ~kHFSVolumeJournaledMask;
638 }
639
640 // if we're here we need to fill in the fileid's for the
641 // journal and journal_info_block.
642 hfsmp->hfs_jnlinfoblkid = GetFileInfo(vcb, kRootDirID, ".journal_info_block", &jinfo_attr, NULL);
643 hfsmp->hfs_jnlfileid = GetFileInfo(vcb, kRootDirID, ".journal", &jnl_attr, NULL);
644 if (hfsmp->hfs_jnlinfoblkid == 0 || hfsmp->hfs_jnlfileid == 0) {
645 printf("hfs: danger! couldn't find the file-id's for the journal or journal_info_block\n");
646 printf("hfs: jnlfileid %d, jnlinfoblkid %d\n", hfsmp->hfs_jnlfileid, hfsmp->hfs_jnlinfoblkid);
647 }
648
649 if (hfsmp->hfs_flags & HFS_READ_ONLY) {
650 vcb->vcbAtrb |= kHFSVolumeJournaledMask;
651 }
652
653 if (hfsmp->jnl == NULL) {
654 vfs_clearflags(hfsmp->hfs_mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
655 }
656 }
657
658 /*
659 * Establish a metadata allocation zone.
660 */
661 hfs_metadatazone_init(hfsmp);
662
663 /*
664 * Make any metadata zone adjustments.
665 */
666 if (hfsmp->hfs_flags & HFS_METADATA_ZONE) {
667 /* Keep the roving allocator out of the metadata zone. */
668 if (vcb->nextAllocation >= hfsmp->hfs_metazone_start &&
669 vcb->nextAllocation <= hfsmp->hfs_metazone_end) {
670 HFS_UPDATE_NEXT_ALLOCATION(hfsmp, hfsmp->hfs_metazone_end + 1);
671 }
672 }
673
674 /* Setup private/hidden directories for hardlinks. */
675 hfs_privatedir_init(hfsmp, FILE_HARDLINKS);
676 hfs_privatedir_init(hfsmp, DIR_HARDLINKS);
677
678 if ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0)
679 hfs_remove_orphans(hfsmp);
680
681 if ( !(vcb->vcbAtrb & kHFSVolumeHardwareLockMask) ) // if the disk is not write protected
682 {
683 MarkVCBDirty( vcb ); // mark VCB dirty so it will be written
684 }
685
686 /*
687 * Allow hot file clustering if conditions allow.
688 */
689 if ((hfsmp->hfs_flags & HFS_METADATA_ZONE) &&
690 ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0)) {
691 (void) hfs_recording_init(hfsmp);
692 }
693
694 /* Force ACLs on HFS+ file systems. */
695 vfs_setextendedsecurity(HFSTOVFS(hfsmp));
696
697 /* Check if volume supports writing of extent-based extended attributes */
698 hfs_check_volxattr(hfsmp, HFS_SET_XATTREXTENTS_STATE);
699
700 return (0);
701
702 ErrorExit:
703 /*
704 * A fatal error occurred and the volume cannot be mounted
705 * release any resources that we aquired...
706 */
707 if (hfsmp->hfs_attribute_vp)
708 ReleaseMetaFileVNode(hfsmp->hfs_attribute_vp);
709 ReleaseMetaFileVNode(hfsmp->hfs_allocation_vp);
710 ReleaseMetaFileVNode(hfsmp->hfs_catalog_vp);
711 ReleaseMetaFileVNode(hfsmp->hfs_extents_vp);
712
713 return (retval);
714 }
715
716
717 /*
718 * ReleaseMetaFileVNode
719 *
720 * vp L - -
721 */
722 static void ReleaseMetaFileVNode(struct vnode *vp)
723 {
724 struct filefork *fp;
725
726 if (vp && (fp = VTOF(vp))) {
727 if (fp->fcbBTCBPtr != NULL) {
728 (void)hfs_lock(VTOC(vp), HFS_EXCLUSIVE_LOCK);
729 (void) BTClosePath(fp);
730 hfs_unlock(VTOC(vp));
731 }
732
733 /* release the node even if BTClosePath fails */
734 vnode_recycle(vp);
735 vnode_put(vp);
736 }
737 }
738
739
740 /*************************************************************
741 *
742 * Unmounts a hfs volume.
743 * At this point vflush() has been called (to dump all non-metadata files)
744 *
745 *************************************************************/
746
747 __private_extern__
748 int
749 hfsUnmount( register struct hfsmount *hfsmp, __unused struct proc *p)
750 {
751 /* Get rid of our attribute data vnode (if any). */
752 if (hfsmp->hfs_attrdata_vp) {
753 vnode_t advp = hfsmp->hfs_attrdata_vp;
754
755 if (vnode_get(advp) == 0) {
756 vnode_rele_ext(advp, O_EVTONLY, 0);
757 vnode_put(advp);
758 }
759 hfsmp->hfs_attrdata_vp = NULLVP;
760 }
761
762 if (hfsmp->hfs_startup_vp)
763 ReleaseMetaFileVNode(hfsmp->hfs_startup_vp);
764
765 if (hfsmp->hfs_allocation_vp)
766 ReleaseMetaFileVNode(hfsmp->hfs_allocation_vp);
767
768 if (hfsmp->hfs_attribute_vp)
769 ReleaseMetaFileVNode(hfsmp->hfs_attribute_vp);
770
771 ReleaseMetaFileVNode(hfsmp->hfs_catalog_vp);
772 ReleaseMetaFileVNode(hfsmp->hfs_extents_vp);
773
774 /*
775 * Setting these pointers to NULL so that any references
776 * past this point will fail, and tell us the point of failure.
777 * Also, facilitates a check in hfs_update for a null catalog
778 * vp
779 */
780 hfsmp->hfs_allocation_vp = NULL;
781 hfsmp->hfs_attribute_vp = NULL;
782 hfsmp->hfs_catalog_vp = NULL;
783 hfsmp->hfs_extents_vp = NULL;
784 hfsmp->hfs_startup_vp = NULL;
785
786 return (0);
787 }
788
789
790 /*
791 * Test if fork has overflow extents.
792 */
793 __private_extern__
794 int
795 overflow_extents(struct filefork *fp)
796 {
797 u_long blocks;
798
799 //
800 // If the vnode pointer is NULL then we're being called
801 // from hfs_remove_orphans() with a faked-up filefork
802 // and therefore it has to be an HFS+ volume. Otherwise
803 // we check through the volume header to see what type
804 // of volume we're on.
805 //
806 if (FTOV(fp) == NULL || VTOVCB(FTOV(fp))->vcbSigWord == kHFSPlusSigWord) {
807 if (fp->ff_extents[7].blockCount == 0)
808 return (0);
809
810 blocks = fp->ff_extents[0].blockCount +
811 fp->ff_extents[1].blockCount +
812 fp->ff_extents[2].blockCount +
813 fp->ff_extents[3].blockCount +
814 fp->ff_extents[4].blockCount +
815 fp->ff_extents[5].blockCount +
816 fp->ff_extents[6].blockCount +
817 fp->ff_extents[7].blockCount;
818 } else {
819 if (fp->ff_extents[2].blockCount == 0)
820 return false;
821
822 blocks = fp->ff_extents[0].blockCount +
823 fp->ff_extents[1].blockCount +
824 fp->ff_extents[2].blockCount;
825 }
826
827 return (fp->ff_blocks > blocks);
828 }
829
830
831 /*
832 * Lock HFS system file(s).
833 */
834 __private_extern__
835 int
836 hfs_systemfile_lock(struct hfsmount *hfsmp, int flags, enum hfslocktype locktype)
837 {
838 /*
839 * Locking order is Catalog file, Attributes file, Startup file, Bitmap file, Extents file
840 */
841 if (flags & SFL_CATALOG) {
842
843 #ifdef HFS_CHECK_LOCK_ORDER
844 if (hfsmp->hfs_attribute_cp && hfsmp->hfs_attribute_cp->c_lockowner == current_thread()) {
845 panic("hfs_systemfile_lock: bad lock order (Attributes before Catalog)");
846 }
847 if (hfsmp->hfs_startup_cp && hfsmp->hfs_startup_cp->c_lockowner == current_thread()) {
848 panic("hfs_systemfile_lock: bad lock order (Startup before Catalog)");
849 }
850 if (hfsmp-> hfs_extents_cp && hfsmp->hfs_extents_cp->c_lockowner == current_thread()) {
851 panic("hfs_systemfile_lock: bad lock order (Extents before Catalog)");
852 }
853 #endif /* HFS_CHECK_LOCK_ORDER */
854
855 (void) hfs_lock(hfsmp->hfs_catalog_cp, locktype);
856 /*
857 * When the catalog file has overflow extents then
858 * also acquire the extents b-tree lock if its not
859 * already requested.
860 */
861 if ((flags & SFL_EXTENTS) == 0 &&
862 overflow_extents(VTOF(hfsmp->hfs_catalog_vp))) {
863 flags |= SFL_EXTENTS;
864 }
865 }
866 if (flags & SFL_ATTRIBUTE) {
867
868 #ifdef HFS_CHECK_LOCK_ORDER
869 if (hfsmp->hfs_startup_cp && hfsmp->hfs_startup_cp->c_lockowner == current_thread()) {
870 panic("hfs_systemfile_lock: bad lock order (Startup before Attributes)");
871 }
872 if (hfsmp->hfs_extents_cp && hfsmp->hfs_extents_cp->c_lockowner == current_thread()) {
873 panic("hfs_systemfile_lock: bad lock order (Extents before Attributes)");
874 }
875 #endif /* HFS_CHECK_LOCK_ORDER */
876
877 if (hfsmp->hfs_attribute_cp) {
878 (void) hfs_lock(hfsmp->hfs_attribute_cp, locktype);
879 /*
880 * When the attribute file has overflow extents then
881 * also acquire the extents b-tree lock if its not
882 * already requested.
883 */
884 if ((flags & SFL_EXTENTS) == 0 &&
885 overflow_extents(VTOF(hfsmp->hfs_attribute_vp))) {
886 flags |= SFL_EXTENTS;
887 }
888 } else {
889 flags &= ~SFL_ATTRIBUTE;
890 }
891 }
892 if (flags & SFL_STARTUP) {
893 #ifdef HFS_CHECK_LOCK_ORDER
894 if (hfsmp-> hfs_extents_cp && hfsmp->hfs_extents_cp->c_lockowner == current_thread()) {
895 panic("hfs_systemfile_lock: bad lock order (Extents before Startup)");
896 }
897 #endif /* HFS_CHECK_LOCK_ORDER */
898
899 (void) hfs_lock(hfsmp->hfs_startup_cp, locktype);
900 /*
901 * When the startup file has overflow extents then
902 * also acquire the extents b-tree lock if its not
903 * already requested.
904 */
905 if ((flags & SFL_EXTENTS) == 0 &&
906 overflow_extents(VTOF(hfsmp->hfs_startup_vp))) {
907 flags |= SFL_EXTENTS;
908 }
909 }
910 /*
911 * To prevent locks being taken in the wrong order, the extent lock
912 * gets a bitmap lock as well.
913 */
914 if (flags & (SFL_BITMAP | SFL_EXTENTS)) {
915 /*
916 * Since the only bitmap operations are clearing and
917 * setting bits we always need exclusive access. And
918 * when we have a journal, we can "hide" behind that
919 * lock since we can only change the bitmap from
920 * within a transaction.
921 */
922 if (hfsmp->jnl || (hfsmp->hfs_allocation_cp == NULL)) {
923 flags &= ~SFL_BITMAP;
924 } else {
925 (void) hfs_lock(hfsmp->hfs_allocation_cp, HFS_EXCLUSIVE_LOCK);
926 /* The bitmap lock is also grabbed when only extent lock
927 * was requested. Set the bitmap lock bit in the lock
928 * flags which callers will use during unlock.
929 */
930 flags |= SFL_BITMAP;
931 }
932 }
933 if (flags & SFL_EXTENTS) {
934 /*
935 * Since the extents btree lock is recursive we always
936 * need exclusive access.
937 */
938 (void) hfs_lock(hfsmp->hfs_extents_cp, HFS_EXCLUSIVE_LOCK);
939 }
940 return (flags);
941 }
942
943 /*
944 * unlock HFS system file(s).
945 */
946 __private_extern__
947 void
948 hfs_systemfile_unlock(struct hfsmount *hfsmp, int flags)
949 {
950 struct timeval tv;
951 u_int32_t lastfsync;
952 int numOfLockedBuffs;
953
954 if (hfsmp->jnl == NULL) {
955 microuptime(&tv);
956 lastfsync = tv.tv_sec;
957 }
958 if (flags & SFL_STARTUP && hfsmp->hfs_startup_cp) {
959 hfs_unlock(hfsmp->hfs_startup_cp);
960 }
961 if (flags & SFL_ATTRIBUTE && hfsmp->hfs_attribute_cp) {
962 if (hfsmp->jnl == NULL) {
963 BTGetLastSync((FCB*)VTOF(hfsmp->hfs_attribute_vp), &lastfsync);
964 numOfLockedBuffs = count_lock_queue();
965 if ((numOfLockedBuffs > kMaxLockedMetaBuffers) ||
966 ((numOfLockedBuffs > 1) && ((tv.tv_sec - lastfsync) >
967 kMaxSecsForFsync))) {
968 hfs_btsync(hfsmp->hfs_attribute_vp, HFS_SYNCTRANS);
969 }
970 }
971 hfs_unlock(hfsmp->hfs_attribute_cp);
972 }
973 if (flags & SFL_CATALOG) {
974 if (hfsmp->jnl == NULL) {
975 BTGetLastSync((FCB*)VTOF(hfsmp->hfs_catalog_vp), &lastfsync);
976 numOfLockedBuffs = count_lock_queue();
977 if ((numOfLockedBuffs > kMaxLockedMetaBuffers) ||
978 ((numOfLockedBuffs > 1) && ((tv.tv_sec - lastfsync) >
979 kMaxSecsForFsync))) {
980 hfs_btsync(hfsmp->hfs_catalog_vp, HFS_SYNCTRANS);
981 }
982 }
983 hfs_unlock(hfsmp->hfs_catalog_cp);
984 }
985 if (flags & SFL_BITMAP) {
986 hfs_unlock(hfsmp->hfs_allocation_cp);
987 }
988 if (flags & SFL_EXTENTS) {
989 if (hfsmp->jnl == NULL) {
990 BTGetLastSync((FCB*)VTOF(hfsmp->hfs_extents_vp), &lastfsync);
991 numOfLockedBuffs = count_lock_queue();
992 if ((numOfLockedBuffs > kMaxLockedMetaBuffers) ||
993 ((numOfLockedBuffs > 1) && ((tv.tv_sec - lastfsync) >
994 kMaxSecsForFsync))) {
995 hfs_btsync(hfsmp->hfs_extents_vp, HFS_SYNCTRANS);
996 }
997 }
998 hfs_unlock(hfsmp->hfs_extents_cp);
999 }
1000 }
1001
1002
1003 /*
1004 * RequireFileLock
1005 *
1006 * Check to see if a vnode is locked in the current context
1007 * This is to be used for debugging purposes only!!
1008 */
1009 #if HFS_DIAGNOSTIC
1010 void RequireFileLock(FileReference vp, int shareable)
1011 {
1012 int locked;
1013
1014 /* The extents btree and allocation bitmap are always exclusive. */
1015 if (VTOC(vp)->c_fileid == kHFSExtentsFileID ||
1016 VTOC(vp)->c_fileid == kHFSAllocationFileID) {
1017 shareable = 0;
1018 }
1019
1020 locked = VTOC(vp)->c_lockowner == (void *)current_thread();
1021
1022 if (!locked && !shareable) {
1023 switch (VTOC(vp)->c_fileid) {
1024 case kHFSExtentsFileID:
1025 panic("extents btree not locked! v: 0x%08X\n #\n", (u_int)vp);
1026 break;
1027 case kHFSCatalogFileID:
1028 panic("catalog btree not locked! v: 0x%08X\n #\n", (u_int)vp);
1029 break;
1030 case kHFSAllocationFileID:
1031 /* The allocation file can hide behind the jornal lock. */
1032 if (VTOHFS(vp)->jnl == NULL)
1033 panic("allocation file not locked! v: 0x%08X\n #\n", (u_int)vp);
1034 break;
1035 case kHFSStartupFileID:
1036 panic("startup file not locked! v: 0x%08X\n #\n", (u_int)vp);
1037 case kHFSAttributesFileID:
1038 panic("attributes btree not locked! v: 0x%08X\n #\n", (u_int)vp);
1039 break;
1040 }
1041 }
1042 }
1043 #endif
1044
1045
1046 /*
1047 * There are three ways to qualify for ownership rights on an object:
1048 *
1049 * 1. (a) Your UID matches the cnode's UID.
1050 * (b) The object in question is owned by "unknown"
1051 * 2. (a) Permissions on the filesystem are being ignored and
1052 * your UID matches the replacement UID.
1053 * (b) Permissions on the filesystem are being ignored and
1054 * the replacement UID is "unknown".
1055 * 3. You are root.
1056 *
1057 */
1058 int
1059 hfs_owner_rights(struct hfsmount *hfsmp, uid_t cnode_uid, kauth_cred_t cred,
1060 __unused struct proc *p, int invokesuperuserstatus)
1061 {
1062 if ((kauth_cred_getuid(cred) == cnode_uid) || /* [1a] */
1063 (cnode_uid == UNKNOWNUID) || /* [1b] */
1064 ((((unsigned int)vfs_flags(HFSTOVFS(hfsmp))) & MNT_UNKNOWNPERMISSIONS) && /* [2] */
1065 ((kauth_cred_getuid(cred) == hfsmp->hfs_uid) || /* [2a] */
1066 (hfsmp->hfs_uid == UNKNOWNUID))) || /* [2b] */
1067 (invokesuperuserstatus && (suser(cred, 0) == 0))) { /* [3] */
1068 return (0);
1069 } else {
1070 return (EPERM);
1071 }
1072 }
1073
1074
1075 unsigned long BestBlockSizeFit(unsigned long allocationBlockSize,
1076 unsigned long blockSizeLimit,
1077 unsigned long baseMultiple) {
1078 /*
1079 Compute the optimal (largest) block size (no larger than allocationBlockSize) that is less than the
1080 specified limit but still an even multiple of the baseMultiple.
1081 */
1082 int baseBlockCount, blockCount;
1083 unsigned long trialBlockSize;
1084
1085 if (allocationBlockSize % baseMultiple != 0) {
1086 /*
1087 Whoops: the allocation blocks aren't even multiples of the specified base:
1088 no amount of dividing them into even parts will be a multiple, either then!
1089 */
1090 return 512; /* Hope for the best */
1091 };
1092
1093 /* Try the obvious winner first, to prevent 12K allocation blocks, for instance,
1094 from being handled as two 6K logical blocks instead of 3 4K logical blocks.
1095 Even though the former (the result of the loop below) is the larger allocation
1096 block size, the latter is more efficient: */
1097 if (allocationBlockSize % PAGE_SIZE == 0) return PAGE_SIZE;
1098
1099 /* No clear winner exists: pick the largest even fraction <= MAXBSIZE: */
1100 baseBlockCount = allocationBlockSize / baseMultiple; /* Now guaranteed to be an even multiple */
1101
1102 for (blockCount = baseBlockCount; blockCount > 0; --blockCount) {
1103 trialBlockSize = blockCount * baseMultiple;
1104 if (allocationBlockSize % trialBlockSize == 0) { /* An even multiple? */
1105 if ((trialBlockSize <= blockSizeLimit) &&
1106 (trialBlockSize % baseMultiple == 0)) {
1107 return trialBlockSize;
1108 };
1109 };
1110 };
1111
1112 /* Note: we should never get here, since blockCount = 1 should always work,
1113 but this is nice and safe and makes the compiler happy, too ... */
1114 return 512;
1115 }
1116
1117
1118 __private_extern__
1119 u_long
1120 GetFileInfo(ExtendedVCB *vcb, __unused u_int32_t dirid, const char *name,
1121 struct cat_attr *fattr, struct cat_fork *forkinfo)
1122 {
1123 struct hfsmount * hfsmp;
1124 struct cat_desc jdesc;
1125 int lockflags;
1126 int error;
1127
1128 if (vcb->vcbSigWord != kHFSPlusSigWord)
1129 return (0);
1130
1131 hfsmp = VCBTOHFS(vcb);
1132
1133 memset(&jdesc, 0, sizeof(struct cat_desc));
1134 jdesc.cd_parentcnid = kRootDirID;
1135 jdesc.cd_nameptr = (const u_int8_t *)name;
1136 jdesc.cd_namelen = strlen(name);
1137
1138 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG, HFS_SHARED_LOCK);
1139 error = cat_lookup(hfsmp, &jdesc, 0, NULL, fattr, forkinfo, NULL);
1140 hfs_systemfile_unlock(hfsmp, lockflags);
1141
1142 if (error == 0) {
1143 return (fattr->ca_fileid);
1144 } else if (hfsmp->hfs_flags & HFS_READ_ONLY) {
1145 return (0);
1146 }
1147
1148 return (0); /* XXX what callers expect on an error */
1149 }
1150
1151
1152 /*
1153 * On HFS Plus Volumes, there can be orphaned files or directories
1154 * These are files or directories that were unlinked while busy.
1155 * If the volume was not cleanly unmounted then some of these may
1156 * have persisted and need to be removed.
1157 */
1158 __private_extern__
1159 void
1160 hfs_remove_orphans(struct hfsmount * hfsmp)
1161 {
1162 struct BTreeIterator * iterator = NULL;
1163 struct FSBufferDescriptor btdata;
1164 struct HFSPlusCatalogFile filerec;
1165 struct HFSPlusCatalogKey * keyp;
1166 struct proc *p = current_proc();
1167 FCB *fcb;
1168 ExtendedVCB *vcb;
1169 char filename[32];
1170 char tempname[32];
1171 size_t namelen;
1172 cat_cookie_t cookie;
1173 int catlock = 0;
1174 int catreserve = 0;
1175 int started_tr = 0;
1176 int lockflags;
1177 int result;
1178 int orphanedlinks = 0;
1179
1180 bzero(&cookie, sizeof(cookie));
1181
1182 if (hfsmp->hfs_flags & HFS_CLEANED_ORPHANS)
1183 return;
1184
1185 vcb = HFSTOVCB(hfsmp);
1186 fcb = VTOF(hfsmp->hfs_catalog_vp);
1187
1188 btdata.bufferAddress = &filerec;
1189 btdata.itemSize = sizeof(filerec);
1190 btdata.itemCount = 1;
1191
1192 MALLOC(iterator, struct BTreeIterator *, sizeof(*iterator), M_TEMP, M_WAITOK);
1193 bzero(iterator, sizeof(*iterator));
1194
1195 /* Build a key to "temp" */
1196 keyp = (HFSPlusCatalogKey*)&iterator->key;
1197 keyp->parentID = hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid;
1198 keyp->nodeName.length = 4; /* "temp" */
1199 keyp->keyLength = kHFSPlusCatalogKeyMinimumLength + keyp->nodeName.length * 2;
1200 keyp->nodeName.unicode[0] = 't';
1201 keyp->nodeName.unicode[1] = 'e';
1202 keyp->nodeName.unicode[2] = 'm';
1203 keyp->nodeName.unicode[3] = 'p';
1204
1205 /*
1206 * Position the iterator just before the first real temp file/dir.
1207 */
1208 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG, HFS_EXCLUSIVE_LOCK);
1209 (void) BTSearchRecord(fcb, iterator, NULL, NULL, iterator);
1210 hfs_systemfile_unlock(hfsmp, lockflags);
1211
1212 /* Visit all the temp files/dirs in the HFS+ private directory. */
1213 for (;;) {
1214 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG, HFS_EXCLUSIVE_LOCK);
1215 result = BTIterateRecord(fcb, kBTreeNextRecord, iterator, &btdata, NULL);
1216 hfs_systemfile_unlock(hfsmp, lockflags);
1217 if (result)
1218 break;
1219 if (keyp->parentID != hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid)
1220 break;
1221
1222 (void) utf8_encodestr(keyp->nodeName.unicode, keyp->nodeName.length * 2,
1223 (u_int8_t *)filename, &namelen, sizeof(filename), 0, 0);
1224
1225 (void) snprintf(tempname, sizeof(tempname), "%s%d",
1226 HFS_DELETE_PREFIX, filerec.fileID);
1227
1228 /*
1229 * Delete all files (and directories) named "tempxxx",
1230 * where xxx is the file's cnid in decimal.
1231 *
1232 */
1233 if (bcmp(tempname, filename, namelen) == 0) {
1234 struct filefork dfork;
1235 struct filefork rfork;
1236 struct cnode cnode;
1237
1238 bzero(&dfork, sizeof(dfork));
1239 bzero(&rfork, sizeof(rfork));
1240 bzero(&cnode, sizeof(cnode));
1241
1242 /* Delete any attributes, ignore errors */
1243 (void) hfs_removeallattr(hfsmp, filerec.fileID);
1244
1245 if (hfs_start_transaction(hfsmp) != 0) {
1246 printf("hfs_remove_orphans: failed to start transaction\n");
1247 goto exit;
1248 }
1249 started_tr = 1;
1250
1251 /*
1252 * Reserve some space in the Catalog file.
1253 */
1254 if (cat_preflight(hfsmp, CAT_DELETE, &cookie, p) != 0) {
1255 printf("hfs_remove_orphans: cat_preflight failed\n");
1256 goto exit;
1257 }
1258 catreserve = 1;
1259
1260 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
1261 catlock = 1;
1262
1263 /* Build a fake cnode */
1264 cat_convertattr(hfsmp, (CatalogRecord *)&filerec, &cnode.c_attr,
1265 &dfork.ff_data, &rfork.ff_data);
1266 cnode.c_desc.cd_parentcnid = hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid;
1267 cnode.c_desc.cd_nameptr = (const u_int8_t *)filename;
1268 cnode.c_desc.cd_namelen = namelen;
1269 cnode.c_desc.cd_cnid = cnode.c_attr.ca_fileid;
1270 cnode.c_blocks = dfork.ff_blocks + rfork.ff_blocks;
1271
1272 /* Position iterator at previous entry */
1273 if (BTIterateRecord(fcb, kBTreePrevRecord, iterator,
1274 NULL, NULL) != 0) {
1275 break;
1276 }
1277
1278 /* Truncate the file to zero (both forks) */
1279 if (dfork.ff_blocks > 0) {
1280 u_int64_t fsize;
1281
1282 dfork.ff_cp = &cnode;
1283 cnode.c_datafork = &dfork;
1284 cnode.c_rsrcfork = NULL;
1285 fsize = (u_int64_t)dfork.ff_blocks * (u_int64_t)HFSTOVCB(hfsmp)->blockSize;
1286 while (fsize > 0) {
1287 if (fsize > HFS_BIGFILE_SIZE && overflow_extents(&dfork)) {
1288 fsize -= HFS_BIGFILE_SIZE;
1289 } else {
1290 fsize = 0;
1291 }
1292
1293 if (TruncateFileC(vcb, (FCB*)&dfork, fsize, false) != 0) {
1294 printf("error truncting data fork!\n");
1295 break;
1296 }
1297
1298 //
1299 // if we're iteratively truncating this file down,
1300 // then end the transaction and start a new one so
1301 // that no one transaction gets too big.
1302 //
1303 if (fsize > 0 && started_tr) {
1304 /* Drop system file locks before starting
1305 * another transaction to preserve lock order.
1306 */
1307 hfs_systemfile_unlock(hfsmp, lockflags);
1308 catlock = 0;
1309 hfs_end_transaction(hfsmp);
1310
1311 if (hfs_start_transaction(hfsmp) != 0) {
1312 started_tr = 0;
1313 break;
1314 }
1315 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
1316 catlock = 1;
1317 }
1318 }
1319 }
1320
1321 if (rfork.ff_blocks > 0) {
1322 rfork.ff_cp = &cnode;
1323 cnode.c_datafork = NULL;
1324 cnode.c_rsrcfork = &rfork;
1325 if (TruncateFileC(vcb, (FCB*)&rfork, 0, false) != 0) {
1326 printf("error truncting rsrc fork!\n");
1327 break;
1328 }
1329 }
1330
1331 /* Remove the file or folder record from the Catalog */
1332 if (cat_delete(hfsmp, &cnode.c_desc, &cnode.c_attr) != 0) {
1333 printf("hfs_remove_orphans: error deleting cat rec for id %d!\n", cnode.c_desc.cd_cnid);
1334 hfs_systemfile_unlock(hfsmp, lockflags);
1335 catlock = 0;
1336 hfs_volupdate(hfsmp, VOL_UPDATE, 0);
1337 break;
1338 }
1339 ++orphanedlinks;
1340
1341 /* Update parent and volume counts */
1342 hfsmp->hfs_private_attr[FILE_HARDLINKS].ca_entries--;
1343 if (cnode.c_attr.ca_mode & S_IFDIR) {
1344 DEC_FOLDERCOUNT(hfsmp, hfsmp->hfs_private_attr[FILE_HARDLINKS]);
1345 }
1346
1347 (void)cat_update(hfsmp, &hfsmp->hfs_private_desc[FILE_HARDLINKS],
1348 &hfsmp->hfs_private_attr[FILE_HARDLINKS], NULL, NULL);
1349
1350 /* Drop locks and end the transaction */
1351 hfs_systemfile_unlock(hfsmp, lockflags);
1352 cat_postflight(hfsmp, &cookie, p);
1353 catlock = catreserve = 0;
1354
1355 /*
1356 Now that Catalog is unlocked, update the volume info, making
1357 sure to differentiate between files and directories
1358 */
1359 if (cnode.c_attr.ca_mode & S_IFDIR) {
1360 hfs_volupdate(hfsmp, VOL_RMDIR, 0);
1361 }
1362 else{
1363 hfs_volupdate(hfsmp, VOL_RMFILE, 0);
1364 }
1365
1366 if (started_tr) {
1367 hfs_end_transaction(hfsmp);
1368 started_tr = 0;
1369 }
1370
1371 } /* end if */
1372 } /* end for */
1373 if (orphanedlinks > 0)
1374 printf("HFS: Removed %d orphaned unlinked files or directories \n", orphanedlinks);
1375 exit:
1376 if (catlock) {
1377 hfs_systemfile_unlock(hfsmp, lockflags);
1378 }
1379 if (catreserve) {
1380 cat_postflight(hfsmp, &cookie, p);
1381 }
1382 if (started_tr) {
1383 hfs_end_transaction(hfsmp);
1384 }
1385
1386 FREE(iterator, M_TEMP);
1387 hfsmp->hfs_flags |= HFS_CLEANED_ORPHANS;
1388 }
1389
1390
1391 /*
1392 * This will return the correct logical block size for a given vnode.
1393 * For most files, it is the allocation block size, for meta data like
1394 * BTrees, this is kept as part of the BTree private nodeSize
1395 */
1396 u_int32_t
1397 GetLogicalBlockSize(struct vnode *vp)
1398 {
1399 u_int32_t logBlockSize;
1400
1401 DBG_ASSERT(vp != NULL);
1402
1403 /* start with default */
1404 logBlockSize = VTOHFS(vp)->hfs_logBlockSize;
1405
1406 if (vnode_issystem(vp)) {
1407 if (VTOF(vp)->fcbBTCBPtr != NULL) {
1408 BTreeInfoRec bTreeInfo;
1409
1410 /*
1411 * We do not lock the BTrees, because if we are getting block..then the tree
1412 * should be locked in the first place.
1413 * We just want the nodeSize wich will NEVER change..so even if the world
1414 * is changing..the nodeSize should remain the same. Which argues why lock
1415 * it in the first place??
1416 */
1417
1418 (void) BTGetInformation (VTOF(vp), kBTreeInfoVersion, &bTreeInfo);
1419
1420 logBlockSize = bTreeInfo.nodeSize;
1421
1422 } else if (VTOC(vp)->c_fileid == kHFSAllocationFileID) {
1423 logBlockSize = VTOVCB(vp)->vcbVBMIOSize;
1424 }
1425 }
1426
1427 DBG_ASSERT(logBlockSize > 0);
1428
1429 return logBlockSize;
1430 }
1431
1432 __private_extern__
1433 u_int32_t
1434 hfs_freeblks(struct hfsmount * hfsmp, int wantreserve)
1435 {
1436 u_int32_t freeblks;
1437 u_int32_t rsrvblks;
1438 u_int32_t loanblks;
1439
1440 /*
1441 * We don't bother taking the mount lock
1442 * to look at these values since the values
1443 * themselves are each updated automically
1444 * on aligned addresses.
1445 */
1446 freeblks = hfsmp->freeBlocks;
1447 rsrvblks = hfsmp->reserveBlocks;
1448 loanblks = hfsmp->loanedBlocks;
1449 if (wantreserve) {
1450 if (freeblks > rsrvblks)
1451 freeblks -= rsrvblks;
1452 else
1453 freeblks = 0;
1454 }
1455 if (freeblks > loanblks)
1456 freeblks -= loanblks;
1457 else
1458 freeblks = 0;
1459
1460 #ifdef HFS_SPARSE_DEV
1461 /*
1462 * When the underlying device is sparse, check the
1463 * available space on the backing store volume.
1464 */
1465 if ((hfsmp->hfs_flags & HFS_HAS_SPARSE_DEVICE) && hfsmp->hfs_backingfs_rootvp) {
1466 struct vfsstatfs *vfsp; /* 272 bytes */
1467 u_int64_t vfreeblks;
1468 u_int32_t loanedblks;
1469 struct mount * backingfs_mp;
1470 struct timeval now;
1471
1472 backingfs_mp = vnode_mount(hfsmp->hfs_backingfs_rootvp);
1473
1474 microtime(&now);
1475 if ((now.tv_sec - hfsmp->hfs_last_backingstatfs) >= 1) {
1476 vfs_update_vfsstat(backingfs_mp, vfs_context_kernel(), VFS_KERNEL_EVENT);
1477 hfsmp->hfs_last_backingstatfs = now.tv_sec;
1478 }
1479
1480 if ((vfsp = vfs_statfs(backingfs_mp))) {
1481 HFS_MOUNT_LOCK(hfsmp, TRUE);
1482 vfreeblks = vfsp->f_bavail;
1483 /* Normalize block count if needed. */
1484 if (vfsp->f_bsize != hfsmp->blockSize) {
1485 vfreeblks = ((u_int64_t)vfreeblks * (u_int64_t)(vfsp->f_bsize)) / hfsmp->blockSize;
1486 }
1487 if (vfreeblks > (unsigned int)hfsmp->hfs_sparsebandblks)
1488 vfreeblks -= hfsmp->hfs_sparsebandblks;
1489 else
1490 vfreeblks = 0;
1491
1492 /* Take into account any delayed allocations. */
1493 loanedblks = 2 * hfsmp->loanedBlocks;
1494 if (vfreeblks > loanedblks)
1495 vfreeblks -= loanedblks;
1496 else
1497 vfreeblks = 0;
1498
1499 freeblks = MIN(vfreeblks, freeblks);
1500 HFS_MOUNT_UNLOCK(hfsmp, TRUE);
1501 }
1502 }
1503 #endif /* HFS_SPARSE_DEV */
1504
1505 return (freeblks);
1506 }
1507
1508 /*
1509 * Map HFS Common errors (negative) to BSD error codes (positive).
1510 * Positive errors (ie BSD errors) are passed through unchanged.
1511 */
1512 short MacToVFSError(OSErr err)
1513 {
1514 if (err >= 0)
1515 return err;
1516
1517 switch (err) {
1518 case dskFulErr: /* -34 */
1519 case btNoSpaceAvail: /* -32733 */
1520 return ENOSPC;
1521 case fxOvFlErr: /* -32750 */
1522 return EOVERFLOW;
1523
1524 case btBadNode: /* -32731 */
1525 return EIO;
1526
1527 case memFullErr: /* -108 */
1528 return ENOMEM; /* +12 */
1529
1530 case cmExists: /* -32718 */
1531 case btExists: /* -32734 */
1532 return EEXIST; /* +17 */
1533
1534 case cmNotFound: /* -32719 */
1535 case btNotFound: /* -32735 */
1536 return ENOENT; /* 28 */
1537
1538 case cmNotEmpty: /* -32717 */
1539 return ENOTEMPTY; /* 66 */
1540
1541 case cmFThdDirErr: /* -32714 */
1542 return EISDIR; /* 21 */
1543
1544 case fxRangeErr: /* -32751 */
1545 return ERANGE;
1546
1547 case bdNamErr: /* -37 */
1548 return ENAMETOOLONG; /* 63 */
1549
1550 case paramErr: /* -50 */
1551 case fileBoundsErr: /* -1309 */
1552 return EINVAL; /* +22 */
1553
1554 case fsBTBadNodeSize:
1555 return ENXIO;
1556
1557 default:
1558 return EIO; /* +5 */
1559 }
1560 }
1561
1562
1563 /*
1564 * Find the current thread's directory hint for a given index.
1565 *
1566 * Requires an exclusive lock on directory cnode.
1567 *
1568 * Use detach if the cnode lock must be dropped while the hint is still active.
1569 */
1570 __private_extern__
1571 directoryhint_t *
1572 hfs_getdirhint(struct cnode *dcp, int index, int detach)
1573 {
1574 struct timeval tv;
1575 directoryhint_t *hint;
1576 boolean_t need_remove, need_init;
1577 const u_int8_t * name;
1578
1579 microuptime(&tv);
1580
1581 /*
1582 * Look for an existing hint first. If not found, create a new one (when
1583 * the list is not full) or recycle the oldest hint. Since new hints are
1584 * always added to the head of the list, the last hint is always the
1585 * oldest.
1586 */
1587 TAILQ_FOREACH(hint, &dcp->c_hintlist, dh_link) {
1588 if (hint->dh_index == index)
1589 break;
1590 }
1591 if (hint != NULL) { /* found an existing hint */
1592 need_init = false;
1593 need_remove = true;
1594 } else { /* cannot find an existing hint */
1595 need_init = true;
1596 if (dcp->c_dirhintcnt < HFS_MAXDIRHINTS) { /* we don't need recycling */
1597 /* Create a default directory hint */
1598 MALLOC_ZONE(hint, directoryhint_t *, sizeof(directoryhint_t), M_HFSDIRHINT, M_WAITOK);
1599 ++dcp->c_dirhintcnt;
1600 need_remove = false;
1601 } else { /* recycle the last (i.e., the oldest) hint */
1602 hint = TAILQ_LAST(&dcp->c_hintlist, hfs_hinthead);
1603 if ((hint->dh_desc.cd_flags & CD_HASBUF) &&
1604 (name = hint->dh_desc.cd_nameptr)) {
1605 hint->dh_desc.cd_nameptr = NULL;
1606 hint->dh_desc.cd_namelen = 0;
1607 hint->dh_desc.cd_flags &= ~CD_HASBUF;
1608 vfs_removename((const char *)name);
1609 }
1610 need_remove = true;
1611 }
1612 }
1613
1614 if (need_remove)
1615 TAILQ_REMOVE(&dcp->c_hintlist, hint, dh_link);
1616
1617 if (detach)
1618 --dcp->c_dirhintcnt;
1619 else
1620 TAILQ_INSERT_HEAD(&dcp->c_hintlist, hint, dh_link);
1621
1622 if (need_init) {
1623 hint->dh_index = index;
1624 hint->dh_desc.cd_flags = 0;
1625 hint->dh_desc.cd_encoding = 0;
1626 hint->dh_desc.cd_namelen = 0;
1627 hint->dh_desc.cd_nameptr = NULL;
1628 hint->dh_desc.cd_parentcnid = dcp->c_fileid;
1629 hint->dh_desc.cd_hint = dcp->c_childhint;
1630 hint->dh_desc.cd_cnid = 0;
1631 }
1632 hint->dh_time = tv.tv_sec;
1633 return (hint);
1634 }
1635
1636 /*
1637 * Release a single directory hint.
1638 *
1639 * Requires an exclusive lock on directory cnode.
1640 */
1641 __private_extern__
1642 void
1643 hfs_reldirhint(struct cnode *dcp, directoryhint_t * relhint)
1644 {
1645 const u_int8_t * name;
1646 directoryhint_t *hint;
1647
1648 /* Check if item is on list (could be detached) */
1649 TAILQ_FOREACH(hint, &dcp->c_hintlist, dh_link) {
1650 if (hint == relhint) {
1651 TAILQ_REMOVE(&dcp->c_hintlist, relhint, dh_link);
1652 --dcp->c_dirhintcnt;
1653 break;
1654 }
1655 }
1656 name = relhint->dh_desc.cd_nameptr;
1657 if ((relhint->dh_desc.cd_flags & CD_HASBUF) && (name != NULL)) {
1658 relhint->dh_desc.cd_nameptr = NULL;
1659 relhint->dh_desc.cd_namelen = 0;
1660 relhint->dh_desc.cd_flags &= ~CD_HASBUF;
1661 vfs_removename((const char *)name);
1662 }
1663 FREE_ZONE(relhint, sizeof(directoryhint_t), M_HFSDIRHINT);
1664 }
1665
1666 /*
1667 * Release directory hints for given directory
1668 *
1669 * Requires an exclusive lock on directory cnode.
1670 */
1671 __private_extern__
1672 void
1673 hfs_reldirhints(struct cnode *dcp, int stale_hints_only)
1674 {
1675 struct timeval tv;
1676 directoryhint_t *hint, *prev;
1677 const u_int8_t * name;
1678
1679 if (stale_hints_only)
1680 microuptime(&tv);
1681
1682 /* searching from the oldest to the newest, so we can stop early when releasing stale hints only */
1683 for (hint = TAILQ_LAST(&dcp->c_hintlist, hfs_hinthead); hint != NULL; hint = prev) {
1684 if (stale_hints_only && (tv.tv_sec - hint->dh_time) < HFS_DIRHINT_TTL)
1685 break; /* stop here if this entry is too new */
1686 name = hint->dh_desc.cd_nameptr;
1687 if ((hint->dh_desc.cd_flags & CD_HASBUF) && (name != NULL)) {
1688 hint->dh_desc.cd_nameptr = NULL;
1689 hint->dh_desc.cd_namelen = 0;
1690 hint->dh_desc.cd_flags &= ~CD_HASBUF;
1691 vfs_removename((const char *)name);
1692 }
1693 prev = TAILQ_PREV(hint, hfs_hinthead, dh_link); /* must save this pointer before calling FREE_ZONE on this node */
1694 TAILQ_REMOVE(&dcp->c_hintlist, hint, dh_link);
1695 FREE_ZONE(hint, sizeof(directoryhint_t), M_HFSDIRHINT);
1696 --dcp->c_dirhintcnt;
1697 }
1698 }
1699
1700 /*
1701 * Insert a detached directory hint back into the list of dirhints.
1702 *
1703 * Requires an exclusive lock on directory cnode.
1704 */
1705 __private_extern__
1706 void
1707 hfs_insertdirhint(struct cnode *dcp, directoryhint_t * hint)
1708 {
1709 directoryhint_t *test;
1710
1711 TAILQ_FOREACH(test, &dcp->c_hintlist, dh_link) {
1712 if (test == hint)
1713 panic("hfs_insertdirhint: hint %p already on list!", hint);
1714 }
1715
1716 TAILQ_INSERT_HEAD(&dcp->c_hintlist, hint, dh_link);
1717 ++dcp->c_dirhintcnt;
1718 }
1719
1720 /*
1721 * Perform a case-insensitive compare of two UTF-8 filenames.
1722 *
1723 * Returns 0 if the strings match.
1724 */
1725 __private_extern__
1726 int
1727 hfs_namecmp(const u_int8_t *str1, size_t len1, const u_int8_t *str2, size_t len2)
1728 {
1729 u_int16_t *ustr1, *ustr2;
1730 size_t ulen1, ulen2;
1731 size_t maxbytes;
1732 int cmp = -1;
1733
1734 if (len1 != len2)
1735 return (cmp);
1736
1737 maxbytes = kHFSPlusMaxFileNameChars << 1;
1738 MALLOC(ustr1, u_int16_t *, maxbytes << 1, M_TEMP, M_WAITOK);
1739 ustr2 = ustr1 + (maxbytes >> 1);
1740
1741 if (utf8_decodestr(str1, len1, ustr1, &ulen1, maxbytes, ':', 0) != 0)
1742 goto out;
1743 if (utf8_decodestr(str2, len2, ustr2, &ulen2, maxbytes, ':', 0) != 0)
1744 goto out;
1745
1746 cmp = FastUnicodeCompare(ustr1, ulen1>>1, ustr2, ulen2>>1);
1747 out:
1748 FREE(ustr1, M_TEMP);
1749 return (cmp);
1750 }
1751
1752
1753 __private_extern__
1754 int
1755 hfs_early_journal_init(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp,
1756 void *_args, off_t embeddedOffset, daddr64_t mdb_offset,
1757 HFSMasterDirectoryBlock *mdbp, kauth_cred_t cred)
1758 {
1759 JournalInfoBlock *jibp;
1760 struct buf *jinfo_bp, *bp;
1761 int sectors_per_fsblock, arg_flags=0, arg_tbufsz=0;
1762 int retval, blksize = hfsmp->hfs_phys_block_size;
1763 struct vnode *devvp;
1764 struct hfs_mount_args *args = _args;
1765 u_int32_t jib_flags;
1766 u_int64_t jib_offset;
1767 u_int64_t jib_size;
1768
1769 devvp = hfsmp->hfs_devvp;
1770
1771 if (args != NULL && (args->flags & HFSFSMNT_EXTENDED_ARGS)) {
1772 arg_flags = args->journal_flags;
1773 arg_tbufsz = args->journal_tbuffer_size;
1774 }
1775
1776 sectors_per_fsblock = SWAP_BE32(vhp->blockSize) / blksize;
1777
1778 retval = (int)buf_meta_bread(devvp,
1779 (daddr64_t)((embeddedOffset/blksize) +
1780 (SWAP_BE32(vhp->journalInfoBlock)*sectors_per_fsblock)),
1781 SWAP_BE32(vhp->blockSize), cred, &jinfo_bp);
1782 if (retval)
1783 return retval;
1784
1785 jibp = (JournalInfoBlock *)buf_dataptr(jinfo_bp);
1786 jib_flags = SWAP_BE32(jibp->flags);
1787 jib_offset = SWAP_BE64(jibp->offset);
1788 jib_size = SWAP_BE64(jibp->size);
1789
1790 if (jib_flags & kJIJournalInFSMask) {
1791 hfsmp->jvp = hfsmp->hfs_devvp;
1792 } else {
1793 printf("hfs: journal not stored in fs! don't know what to do.\n");
1794 buf_brelse(jinfo_bp);
1795 return EINVAL;
1796 }
1797
1798 // save this off for the hack-y check in hfs_remove()
1799 hfsmp->jnl_start = jib_offset / SWAP_BE32(vhp->blockSize);
1800 hfsmp->jnl_size = jib_size;
1801
1802 if ((hfsmp->hfs_flags & HFS_READ_ONLY) && (vfs_flags(hfsmp->hfs_mp) & MNT_ROOTFS) == 0) {
1803 // if the file system is read-only, check if the journal is empty.
1804 // if it is, then we can allow the mount. otherwise we have to
1805 // return failure.
1806 retval = journal_is_clean(hfsmp->jvp,
1807 jib_offset + embeddedOffset,
1808 jib_size,
1809 devvp,
1810 hfsmp->hfs_phys_block_size);
1811
1812 hfsmp->jnl = NULL;
1813
1814 buf_brelse(jinfo_bp);
1815
1816 if (retval) {
1817 printf("hfs: early journal init: volume on %s is read-only and journal is dirty. Can not mount volume.\n",
1818 vnode_name(devvp));
1819 }
1820
1821 return retval;
1822 }
1823
1824 if (jib_flags & kJIJournalNeedInitMask) {
1825 printf("hfs: Initializing the journal (joffset 0x%llx sz 0x%llx)...\n",
1826 jib_offset + embeddedOffset, jib_size);
1827 hfsmp->jnl = journal_create(hfsmp->jvp,
1828 jib_offset + embeddedOffset,
1829 jib_size,
1830 devvp,
1831 blksize,
1832 arg_flags,
1833 arg_tbufsz,
1834 hfs_sync_metadata, hfsmp->hfs_mp);
1835
1836 // no need to start a transaction here... if this were to fail
1837 // we'd just re-init it on the next mount.
1838 jib_flags &= ~kJIJournalNeedInitMask;
1839 jibp->flags = SWAP_BE32(jib_flags);
1840 buf_bwrite(jinfo_bp);
1841 jinfo_bp = NULL;
1842 jibp = NULL;
1843 } else {
1844 //printf("hfs: Opening the journal (joffset 0x%llx sz 0x%llx vhp_blksize %d)...\n",
1845 // jib_offset + embeddedOffset,
1846 // jib_size, SWAP_BE32(vhp->blockSize));
1847
1848 hfsmp->jnl = journal_open(hfsmp->jvp,
1849 jib_offset + embeddedOffset,
1850 jib_size,
1851 devvp,
1852 blksize,
1853 arg_flags,
1854 arg_tbufsz,
1855 hfs_sync_metadata, hfsmp->hfs_mp);
1856
1857 buf_brelse(jinfo_bp);
1858 jinfo_bp = NULL;
1859 jibp = NULL;
1860
1861 if (hfsmp->jnl && mdbp) {
1862 // reload the mdb because it could have changed
1863 // if the journal had to be replayed.
1864 if (mdb_offset == 0) {
1865 mdb_offset = (daddr64_t)((embeddedOffset / blksize) + HFS_PRI_SECTOR(blksize));
1866 }
1867 retval = (int)buf_meta_bread(devvp, mdb_offset, blksize, cred, &bp);
1868 if (retval) {
1869 buf_brelse(bp);
1870 printf("hfs: failed to reload the mdb after opening the journal (retval %d)!\n",
1871 retval);
1872 return retval;
1873 }
1874 bcopy((char *)buf_dataptr(bp) + HFS_PRI_OFFSET(blksize), mdbp, 512);
1875 buf_brelse(bp);
1876 bp = NULL;
1877 }
1878 }
1879
1880
1881 //printf("journal @ 0x%x\n", hfsmp->jnl);
1882
1883 // if we expected the journal to be there and we couldn't
1884 // create it or open it then we have to bail out.
1885 if (hfsmp->jnl == NULL) {
1886 printf("hfs: early jnl init: failed to open/create the journal (retval %d).\n", retval);
1887 return EINVAL;
1888 }
1889
1890 return 0;
1891 }
1892
1893
1894 //
1895 // This function will go and re-locate the .journal_info_block and
1896 // the .journal files in case they moved (which can happen if you
1897 // run Norton SpeedDisk). If we fail to find either file we just
1898 // disable journaling for this volume and return. We turn off the
1899 // journaling bit in the vcb and assume it will get written to disk
1900 // later (if it doesn't on the next mount we'd do the same thing
1901 // again which is harmless). If we disable journaling we don't
1902 // return an error so that the volume is still mountable.
1903 //
1904 // If the info we find for the .journal_info_block and .journal files
1905 // isn't what we had stored, we re-set our cached info and proceed
1906 // with opening the journal normally.
1907 //
1908 static int
1909 hfs_late_journal_init(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp, void *_args)
1910 {
1911 JournalInfoBlock *jibp;
1912 struct buf *jinfo_bp;
1913 int sectors_per_fsblock, arg_flags=0, arg_tbufsz=0;
1914 int retval, write_jibp = 0, recreate_journal = 0;
1915 struct vnode *devvp;
1916 struct cat_attr jib_attr, jattr;
1917 struct cat_fork jib_fork, jfork;
1918 ExtendedVCB *vcb;
1919 u_long fid;
1920 struct hfs_mount_args *args = _args;
1921 u_int32_t jib_flags;
1922 u_int64_t jib_offset;
1923 u_int64_t jib_size;
1924
1925 devvp = hfsmp->hfs_devvp;
1926 vcb = HFSTOVCB(hfsmp);
1927
1928 if (args != NULL && (args->flags & HFSFSMNT_EXTENDED_ARGS)) {
1929 if (args->journal_disable) {
1930 return 0;
1931 }
1932
1933 arg_flags = args->journal_flags;
1934 arg_tbufsz = args->journal_tbuffer_size;
1935 }
1936
1937 fid = GetFileInfo(vcb, kRootDirID, ".journal_info_block", &jib_attr, &jib_fork);
1938 if (fid == 0 || jib_fork.cf_extents[0].startBlock == 0 || jib_fork.cf_size == 0) {
1939 printf("hfs: can't find the .journal_info_block! disabling journaling (start: %d).\n",
1940 jib_fork.cf_extents[0].startBlock);
1941 vcb->vcbAtrb &= ~kHFSVolumeJournaledMask;
1942 return 0;
1943 }
1944 hfsmp->hfs_jnlinfoblkid = fid;
1945
1946 // make sure the journal_info_block begins where we think it should.
1947 if (SWAP_BE32(vhp->journalInfoBlock) != jib_fork.cf_extents[0].startBlock) {
1948 printf("hfs: The journal_info_block moved (was: %d; is: %d). Fixing up\n",
1949 SWAP_BE32(vhp->journalInfoBlock), jib_fork.cf_extents[0].startBlock);
1950
1951 vcb->vcbJinfoBlock = jib_fork.cf_extents[0].startBlock;
1952 vhp->journalInfoBlock = SWAP_BE32(jib_fork.cf_extents[0].startBlock);
1953 recreate_journal = 1;
1954 }
1955
1956
1957 sectors_per_fsblock = SWAP_BE32(vhp->blockSize) / hfsmp->hfs_phys_block_size;
1958 retval = (int)buf_meta_bread(devvp,
1959 (daddr64_t)(vcb->hfsPlusIOPosOffset / hfsmp->hfs_phys_block_size +
1960 (SWAP_BE32(vhp->journalInfoBlock)*sectors_per_fsblock)),
1961 SWAP_BE32(vhp->blockSize), NOCRED, &jinfo_bp);
1962 if (retval) {
1963 printf("hfs: can't read journal info block. disabling journaling.\n");
1964 vcb->vcbAtrb &= ~kHFSVolumeJournaledMask;
1965 return 0;
1966 }
1967
1968 jibp = (JournalInfoBlock *)buf_dataptr(jinfo_bp);
1969 jib_flags = SWAP_BE32(jibp->flags);
1970 jib_offset = SWAP_BE64(jibp->offset);
1971 jib_size = SWAP_BE64(jibp->size);
1972
1973 fid = GetFileInfo(vcb, kRootDirID, ".journal", &jattr, &jfork);
1974 if (fid == 0 || jfork.cf_extents[0].startBlock == 0 || jfork.cf_size == 0) {
1975 printf("hfs: can't find the journal file! disabling journaling (start: %d)\n",
1976 jfork.cf_extents[0].startBlock);
1977 buf_brelse(jinfo_bp);
1978 vcb->vcbAtrb &= ~kHFSVolumeJournaledMask;
1979 return 0;
1980 }
1981 hfsmp->hfs_jnlfileid = fid;
1982
1983 // make sure the journal file begins where we think it should.
1984 if ((jib_offset / (u_int64_t)vcb->blockSize) != jfork.cf_extents[0].startBlock) {
1985 printf("hfs: The journal file moved (was: %lld; is: %d). Fixing up\n",
1986 (jib_offset / (u_int64_t)vcb->blockSize), jfork.cf_extents[0].startBlock);
1987
1988 jib_offset = (u_int64_t)jfork.cf_extents[0].startBlock * (u_int64_t)vcb->blockSize;
1989 write_jibp = 1;
1990 recreate_journal = 1;
1991 }
1992
1993 // check the size of the journal file.
1994 if (jib_size != (u_int64_t)jfork.cf_extents[0].blockCount*vcb->blockSize) {
1995 printf("hfs: The journal file changed size! (was %lld; is %lld). Fixing up.\n",
1996 jib_size, (u_int64_t)jfork.cf_extents[0].blockCount*vcb->blockSize);
1997
1998 jib_size = (u_int64_t)jfork.cf_extents[0].blockCount * vcb->blockSize;
1999 write_jibp = 1;
2000 recreate_journal = 1;
2001 }
2002
2003 if (jib_flags & kJIJournalInFSMask) {
2004 hfsmp->jvp = hfsmp->hfs_devvp;
2005 } else {
2006 printf("hfs: journal not stored in fs! don't know what to do.\n");
2007 buf_brelse(jinfo_bp);
2008 return EINVAL;
2009 }
2010
2011 // save this off for the hack-y check in hfs_remove()
2012 hfsmp->jnl_start = jib_offset / SWAP_BE32(vhp->blockSize);
2013 hfsmp->jnl_size = jib_size;
2014
2015 if ((hfsmp->hfs_flags & HFS_READ_ONLY) && (vfs_flags(hfsmp->hfs_mp) & MNT_ROOTFS) == 0) {
2016 // if the file system is read-only, check if the journal is empty.
2017 // if it is, then we can allow the mount. otherwise we have to
2018 // return failure.
2019 retval = journal_is_clean(hfsmp->jvp,
2020 jib_offset + (off_t)vcb->hfsPlusIOPosOffset,
2021 jib_size,
2022 devvp,
2023 hfsmp->hfs_phys_block_size);
2024
2025 hfsmp->jnl = NULL;
2026
2027 buf_brelse(jinfo_bp);
2028
2029 if (retval) {
2030 printf("hfs: late journal init: volume on %s is read-only and journal is dirty. Can not mount volume.\n",
2031 vnode_name(devvp));
2032 }
2033
2034 return retval;
2035 }
2036
2037 if ((jib_flags & kJIJournalNeedInitMask) || recreate_journal) {
2038 printf("hfs: Initializing the journal (joffset 0x%llx sz 0x%llx)...\n",
2039 jib_offset + (off_t)vcb->hfsPlusIOPosOffset, jib_size);
2040 hfsmp->jnl = journal_create(hfsmp->jvp,
2041 jib_offset + (off_t)vcb->hfsPlusIOPosOffset,
2042 jib_size,
2043 devvp,
2044 hfsmp->hfs_phys_block_size,
2045 arg_flags,
2046 arg_tbufsz,
2047 hfs_sync_metadata, hfsmp->hfs_mp);
2048
2049 // no need to start a transaction here... if this were to fail
2050 // we'd just re-init it on the next mount.
2051 jib_flags &= ~kJIJournalNeedInitMask;
2052 write_jibp = 1;
2053
2054 } else {
2055 //
2056 // if we weren't the last person to mount this volume
2057 // then we need to throw away the journal because it
2058 // is likely that someone else mucked with the disk.
2059 // if the journal is empty this is no big deal. if the
2060 // disk is dirty this prevents us from replaying the
2061 // journal over top of changes that someone else made.
2062 //
2063 arg_flags |= JOURNAL_RESET;
2064
2065 //printf("hfs: Opening the journal (joffset 0x%llx sz 0x%llx vhp_blksize %d)...\n",
2066 // jib_offset + (off_t)vcb->hfsPlusIOPosOffset,
2067 // jib_size, SWAP_BE32(vhp->blockSize));
2068
2069 hfsmp->jnl = journal_open(hfsmp->jvp,
2070 jib_offset + (off_t)vcb->hfsPlusIOPosOffset,
2071 jib_size,
2072 devvp,
2073 hfsmp->hfs_phys_block_size,
2074 arg_flags,
2075 arg_tbufsz,
2076 hfs_sync_metadata, hfsmp->hfs_mp);
2077 }
2078
2079
2080 if (write_jibp) {
2081 jibp->flags = SWAP_BE32(jib_flags);
2082 jibp->offset = SWAP_BE64(jib_offset);
2083 jibp->size = SWAP_BE64(jib_size);
2084
2085 buf_bwrite(jinfo_bp);
2086 } else {
2087 buf_brelse(jinfo_bp);
2088 }
2089 jinfo_bp = NULL;
2090 jibp = NULL;
2091
2092 //printf("journal @ 0x%x\n", hfsmp->jnl);
2093
2094 // if we expected the journal to be there and we couldn't
2095 // create it or open it then we have to bail out.
2096 if (hfsmp->jnl == NULL) {
2097 printf("hfs: late jnl init: failed to open/create the journal (retval %d).\n", retval);
2098 return EINVAL;
2099 }
2100
2101 return 0;
2102 }
2103
2104 /*
2105 * Calculate the allocation zone for metadata.
2106 *
2107 * This zone includes the following:
2108 * Allocation Bitmap file
2109 * Overflow Extents file
2110 * Journal file
2111 * Quota files
2112 * Clustered Hot files
2113 * Catalog file
2114 *
2115 * METADATA ALLOCATION ZONE
2116 * ____________________________________________________________________________
2117 * | | | | | | |
2118 * | BM | JF | OEF | CATALOG |---> | HOT FILES |
2119 * |____|____|_____|_______________|______________________________|___________|
2120 *
2121 * <------------------------------- N * 128 MB ------------------------------->
2122 *
2123 */
2124 #define GIGABYTE (u_int64_t)(1024*1024*1024)
2125
2126 #define OVERFLOW_DEFAULT_SIZE (4*1024*1024)
2127 #define OVERFLOW_MAXIMUM_SIZE (128*1024*1024)
2128 #define JOURNAL_DEFAULT_SIZE (8*1024*1024)
2129 #define JOURNAL_MAXIMUM_SIZE (512*1024*1024)
2130 #define HOTBAND_MINIMUM_SIZE (10*1024*1024)
2131 #define HOTBAND_MAXIMUM_SIZE (512*1024*1024)
2132
2133 static void
2134 hfs_metadatazone_init(struct hfsmount *hfsmp)
2135 {
2136 ExtendedVCB *vcb;
2137 u_int64_t fs_size;
2138 u_int64_t zonesize;
2139 u_int64_t temp;
2140 u_int64_t filesize;
2141 u_int32_t blk;
2142 int items;
2143
2144 vcb = HFSTOVCB(hfsmp);
2145 fs_size = (u_int64_t)vcb->blockSize * (u_int64_t)vcb->totalBlocks;
2146
2147 /*
2148 * For volumes less than 10 GB, don't bother.
2149 */
2150 if (fs_size < ((u_int64_t)10 * GIGABYTE))
2151 return;
2152 /*
2153 * Skip non-journaled volumes as well.
2154 */
2155 if (hfsmp->jnl == NULL)
2156 return;
2157
2158 /*
2159 * Start with allocation bitmap (a fixed size).
2160 */
2161 zonesize = roundup(vcb->totalBlocks / 8, vcb->vcbVBMIOSize);
2162
2163 /*
2164 * Overflow Extents file gets 4 MB per 100 GB.
2165 */
2166 items = fs_size / ((u_int64_t)100 * GIGABYTE);
2167 filesize = (u_int64_t)(items + 1) * OVERFLOW_DEFAULT_SIZE;
2168 if (filesize > OVERFLOW_MAXIMUM_SIZE)
2169 filesize = OVERFLOW_MAXIMUM_SIZE;
2170 zonesize += filesize;
2171 hfsmp->hfs_overflow_maxblks = filesize / vcb->blockSize;
2172
2173 /*
2174 * Plan for at least 8 MB of journal for each
2175 * 100 GB of disk space (up to a 512 MB).
2176 */
2177 items = fs_size / ((u_int64_t)100 * GIGABYTE);
2178 filesize = (u_int64_t)(items + 1) * JOURNAL_DEFAULT_SIZE;
2179 if (filesize > JOURNAL_MAXIMUM_SIZE)
2180 filesize = JOURNAL_MAXIMUM_SIZE;
2181 zonesize += filesize;
2182
2183 /*
2184 * Catalog file gets 10 MB per 1 GB.
2185 *
2186 * How about considering the current catalog size (used nodes * node size)
2187 * and the current file data size to help estimate the required
2188 * catalog size.
2189 */
2190 filesize = MIN((fs_size / 1024) * 10, GIGABYTE);
2191 hfsmp->hfs_catalog_maxblks = filesize / vcb->blockSize;
2192 zonesize += filesize;
2193
2194 /*
2195 * Add space for hot file region.
2196 *
2197 * ...for now, use 5 MB per 1 GB (0.5 %)
2198 */
2199 filesize = (fs_size / 1024) * 5;
2200 if (filesize > HOTBAND_MAXIMUM_SIZE)
2201 filesize = HOTBAND_MAXIMUM_SIZE;
2202 else if (filesize < HOTBAND_MINIMUM_SIZE)
2203 filesize = HOTBAND_MINIMUM_SIZE;
2204 /*
2205 * Calculate user quota file requirements.
2206 */
2207 items = QF_USERS_PER_GB * (fs_size / GIGABYTE);
2208 if (items < QF_MIN_USERS)
2209 items = QF_MIN_USERS;
2210 else if (items > QF_MAX_USERS)
2211 items = QF_MAX_USERS;
2212 if (!powerof2(items)) {
2213 int x = items;
2214 items = 4;
2215 while (x>>1 != 1) {
2216 x = x >> 1;
2217 items = items << 1;
2218 }
2219 }
2220 filesize += (items + 1) * sizeof(struct dqblk);
2221 /*
2222 * Calculate group quota file requirements.
2223 *
2224 */
2225 items = QF_GROUPS_PER_GB * (fs_size / GIGABYTE);
2226 if (items < QF_MIN_GROUPS)
2227 items = QF_MIN_GROUPS;
2228 else if (items > QF_MAX_GROUPS)
2229 items = QF_MAX_GROUPS;
2230 if (!powerof2(items)) {
2231 int x = items;
2232 items = 4;
2233 while (x>>1 != 1) {
2234 x = x >> 1;
2235 items = items << 1;
2236 }
2237 }
2238 filesize += (items + 1) * sizeof(struct dqblk);
2239 zonesize += filesize;
2240
2241 /*
2242 * Round up entire zone to a bitmap block's worth.
2243 * The extra space goes to the catalog file and hot file area.
2244 */
2245 temp = zonesize;
2246 zonesize = roundup(zonesize, (u_int64_t)vcb->vcbVBMIOSize * 8 * vcb->blockSize);
2247 temp = zonesize - temp; /* temp has extra space */
2248 filesize += temp / 3;
2249 hfsmp->hfs_catalog_maxblks += (temp - (temp / 3)) / vcb->blockSize;
2250
2251 hfsmp->hfs_hotfile_maxblks = filesize / vcb->blockSize;
2252
2253 /* Convert to allocation blocks. */
2254 blk = zonesize / vcb->blockSize;
2255
2256 /* The default metadata zone location is at the start of volume. */
2257 hfsmp->hfs_metazone_start = 1;
2258 hfsmp->hfs_metazone_end = blk - 1;
2259
2260 /* The default hotfile area is at the end of the zone. */
2261 hfsmp->hfs_hotfile_start = blk - (filesize / vcb->blockSize);
2262 hfsmp->hfs_hotfile_end = hfsmp->hfs_metazone_end;
2263 hfsmp->hfs_hotfile_freeblks = hfs_hotfile_freeblocks(hfsmp);
2264 #if 0
2265 printf("HFS: metadata zone is %d to %d\n", hfsmp->hfs_metazone_start, hfsmp->hfs_metazone_end);
2266 printf("HFS: hot file band is %d to %d\n", hfsmp->hfs_hotfile_start, hfsmp->hfs_hotfile_end);
2267 printf("HFS: hot file band free blocks = %d\n", hfsmp->hfs_hotfile_freeblks);
2268 #endif
2269 hfsmp->hfs_flags |= HFS_METADATA_ZONE;
2270 }
2271
2272
2273 static u_int32_t
2274 hfs_hotfile_freeblocks(struct hfsmount *hfsmp)
2275 {
2276 ExtendedVCB *vcb = HFSTOVCB(hfsmp);
2277 int lockflags;
2278 int freeblocks;
2279
2280 lockflags = hfs_systemfile_lock(hfsmp, SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
2281 freeblocks = MetaZoneFreeBlocks(vcb);
2282 hfs_systemfile_unlock(hfsmp, lockflags);
2283
2284 /* Minus Extents overflow file reserve. */
2285 freeblocks -=
2286 hfsmp->hfs_overflow_maxblks - VTOF(hfsmp->hfs_extents_vp)->ff_blocks;
2287 /* Minus catalog file reserve. */
2288 freeblocks -=
2289 hfsmp->hfs_catalog_maxblks - VTOF(hfsmp->hfs_catalog_vp)->ff_blocks;
2290 if (freeblocks < 0)
2291 freeblocks = 0;
2292
2293 return MIN(freeblocks, hfsmp->hfs_hotfile_maxblks);
2294 }
2295
2296 /*
2297 * Determine if a file is a "virtual" metadata file.
2298 * This includes journal and quota files.
2299 */
2300 __private_extern__
2301 int
2302 hfs_virtualmetafile(struct cnode *cp)
2303 {
2304 const char * filename;
2305
2306
2307 if (cp->c_parentcnid != kHFSRootFolderID)
2308 return (0);
2309
2310 filename = (const char *)cp->c_desc.cd_nameptr;
2311 if (filename == NULL)
2312 return (0);
2313
2314 if ((strncmp(filename, ".journal", sizeof(".journal")) == 0) ||
2315 (strncmp(filename, ".journal_info_block", sizeof(".journal_info_block")) == 0) ||
2316 (strncmp(filename, ".quota.user", sizeof(".quota.user")) == 0) ||
2317 (strncmp(filename, ".quota.group", sizeof(".quota.group")) == 0) ||
2318 (strncmp(filename, ".hotfiles.btree", sizeof(".hotfiles.btree")) == 0))
2319 return (1);
2320
2321 return (0);
2322 }
2323
2324
2325 __private_extern__
2326 int
2327 hfs_start_transaction(struct hfsmount *hfsmp)
2328 {
2329 int ret, unlock_on_err=0;
2330 void * thread = current_thread();
2331
2332 #ifdef HFS_CHECK_LOCK_ORDER
2333 /*
2334 * You cannot start a transaction while holding a system
2335 * file lock. (unless the transaction is nested.)
2336 */
2337 if (hfsmp->jnl && journal_owner(hfsmp->jnl) != thread) {
2338 if (hfsmp->hfs_catalog_cp && hfsmp->hfs_catalog_cp->c_lockowner == thread) {
2339 panic("hfs_start_transaction: bad lock order (cat before jnl)\n");
2340 }
2341 if (hfsmp->hfs_attribute_cp && hfsmp->hfs_attribute_cp->c_lockowner == thread) {
2342 panic("hfs_start_transaction: bad lock order (attr before jnl)\n");
2343 }
2344 if (hfsmp->hfs_extents_cp && hfsmp->hfs_extents_cp->c_lockowner == thread) {
2345 panic("hfs_start_transaction: bad lock order (ext before jnl)\n");
2346 }
2347 }
2348 #endif /* HFS_CHECK_LOCK_ORDER */
2349
2350 if (hfsmp->jnl == NULL || journal_owner(hfsmp->jnl) != thread) {
2351 lck_rw_lock_shared(&hfsmp->hfs_global_lock);
2352 unlock_on_err = 1;
2353 }
2354
2355 if (hfsmp->jnl) {
2356 ret = journal_start_transaction(hfsmp->jnl);
2357 if (ret == 0) {
2358 OSAddAtomic(1, (SInt32 *)&hfsmp->hfs_global_lock_nesting);
2359 }
2360 } else {
2361 ret = 0;
2362 }
2363
2364 if (ret != 0 && unlock_on_err) {
2365 lck_rw_unlock_shared(&hfsmp->hfs_global_lock);
2366 }
2367
2368 return ret;
2369 }
2370
2371 __private_extern__
2372 int
2373 hfs_end_transaction(struct hfsmount *hfsmp)
2374 {
2375 int need_unlock=0, ret;
2376
2377 if ( hfsmp->jnl == NULL
2378 || ( journal_owner(hfsmp->jnl) == current_thread()
2379 && (OSAddAtomic(-1, (SInt32 *)&hfsmp->hfs_global_lock_nesting) == 1)) ) {
2380
2381 need_unlock = 1;
2382 }
2383
2384 if (hfsmp->jnl) {
2385 ret = journal_end_transaction(hfsmp->jnl);
2386 } else {
2387 ret = 0;
2388 }
2389
2390 if (need_unlock) {
2391 lck_rw_unlock_shared(&hfsmp->hfs_global_lock);
2392 }
2393
2394 return ret;
2395 }