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