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