1/*
2 * Copyright (c) 2000-2010 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
29#ifndef __HFS__
30#define __HFS__
31
32/* If set to 1, enables the code to allocate blocks from the start
33 * of the disk instead of the nextAllocation for sparse devices like
34 * sparse disk images or sparsebundle images.  The free extent cache
35 * for such volumes is also maintained based on the start block instead
36 * of number of contiguous allocation blocks.  These devices prefer
37 * allocation of blocks near the start of the disk to avoid the
38 * increasing the image size, but it can also result in file fragmentation.
39 */
40#define HFS_SPARSE_DEV 1
41
42#if DEBUG
43#define HFS_CHECK_LOCK_ORDER 1
44#endif
45
46#include <sys/appleapiopts.h>
47
48#ifdef KERNEL
49#ifdef __APPLE_API_PRIVATE
50#include <sys/param.h>
51#include <sys/queue.h>
52#include <sys/mount.h>
53#include <sys/vnode.h>
54#include <sys/quota.h>
55#include <sys/dirent.h>
56#include <sys/event.h>
57#include <sys/disk.h>
58#include <kern/thread_call.h>
59
60#include <kern/locks.h>
61
62#include <vfs/vfs_journal.h>
63
64#include <hfs/hfs_format.h>
65#include <hfs/hfs_catalog.h>
66#include <hfs/hfs_cnode.h>
67#include <hfs/hfs_macos_defs.h>
68#include <hfs/hfs_encodings.h>
69#include <hfs/hfs_hotfiles.h>
70
71#if CONFIG_HFS_ALLOC_RBTREE
72#include <hfs/hfscommon/headers/HybridAllocator.h>
73#endif
74
75#if CONFIG_PROTECT
76/* Forward declare the cprotect struct */
77struct cprotect;
78#endif
79
80/*
81 *	Just reported via MIG interface.
82 */
83#define VERSION_STRING	"hfs-2 (4-12-99)"
84
85#define HFS_LINK_MAX	32767
86
87#define HFS_MAX_DEFERED_ALLOC	(1024*1024)
88
89// 400 megs is a "big" file (i.e. one that when deleted
90// would touch enough data that we should break it into
91// multiple separate transactions)
92#define HFS_BIGFILE_SIZE (400LL * 1024LL * 1024LL)
93
94
95enum { kMDBSize = 512 };				/* Size of I/O transfer to read entire MDB */
96
97enum { kMasterDirectoryBlock = 2 };			/* MDB offset on disk in 512-byte blocks */
98enum { kMDBOffset = kMasterDirectoryBlock * 512 };	/* MDB offset on disk in bytes */
99
100#define kRootDirID kHFSRootFolderID
101
102
103/* number of locked buffer caches to hold for b-tree meta data */
104#define kMaxLockedMetaBuffers		32
105
106extern struct timezone gTimeZone;
107
108
109/* How many free extents to cache per volume */
110#define kMaxFreeExtents		10
111
112/*
113 * HFS_MINFREE gives the minimum acceptable percentage
114 * of file system blocks which may be free (but this
115 * minimum will never exceed HFS_MAXRESERVE bytes). If
116 * the free block count drops below this level only the
117 * superuser may continue to allocate blocks.
118 */
119#define HFS_MINFREE		1
120#define HFS_MAXRESERVE		((u_int64_t)(250*1024*1024))
121
122/*
123 * The system distinguishes between the desirable low-disk
124 * notifiaction levels for root volumes and non-root volumes.
125 * The various thresholds are computed as a fraction of the
126 * volume size, all capped at a certain fixed level
127 */
128
129#define HFS_ROOTVERYLOWDISKTRIGGERFRACTION 5
130#define HFS_ROOTVERYLOWDISKTRIGGERLEVEL ((u_int64_t)(512*1024*1024))
131#define HFS_ROOTLOWDISKTRIGGERFRACTION 10
132#define HFS_ROOTLOWDISKTRIGGERLEVEL ((u_int64_t)(1024*1024*1024))
133#define HFS_ROOTLOWDISKSHUTOFFFRACTION 11
134#define HFS_ROOTLOWDISKSHUTOFFLEVEL ((u_int64_t)(1024*1024*1024 + 250*1024*1024))
135
136#define HFS_VERYLOWDISKTRIGGERFRACTION 1
137#define HFS_VERYLOWDISKTRIGGERLEVEL ((u_int64_t)(100*1024*1024))
138#define HFS_LOWDISKTRIGGERFRACTION 2
139#define HFS_LOWDISKTRIGGERLEVEL ((u_int64_t)(150*1024*1024))
140#define HFS_LOWDISKSHUTOFFFRACTION 3
141#define HFS_LOWDISKSHUTOFFLEVEL ((u_int64_t)(200*1024*1024))
142
143/* Internal Data structures*/
144
145/* This structure describes the HFS specific mount structure data. */
146typedef struct hfsmount {
147	u_int32_t     hfs_flags;              /* see below */
148
149	/* Physical Description */
150	u_int32_t     hfs_logical_block_size;	/* Logical block size of the disk as reported by ioctl(DKIOCGETBLOCKSIZE), always a multiple of 512 */
151	daddr64_t     hfs_logical_block_count;  /* Number of logical blocks on the disk */
152	u_int64_t     hfs_logical_bytes;	/* Number of bytes on the disk device this HFS is mounted on (blockcount * blocksize) */
153	daddr64_t     hfs_alt_id_sector;      	/* location of alternate VH/MDB */
154	u_int32_t     hfs_physical_block_size;	/* Physical block size of the disk as reported by ioctl(DKIOCGETPHYSICALBLOCKSIZE) */
155	u_int32_t     hfs_log_per_phys;		/* Number of logical blocks per physical block size */
156
157	/* Access to VFS and devices */
158	struct mount		*hfs_mp;				/* filesystem vfs structure */
159	struct vnode		*hfs_devvp;				/* block device mounted vnode */
160	struct vnode *		hfs_extents_vp;
161	struct vnode *		hfs_catalog_vp;
162	struct vnode *		hfs_allocation_vp;
163	struct vnode *		hfs_attribute_vp;
164	struct vnode *		hfs_startup_vp;
165	struct vnode *		hfs_attrdata_vp;   /* pseudo file */
166	struct cnode *		hfs_extents_cp;
167	struct cnode *		hfs_catalog_cp;
168	struct cnode *		hfs_allocation_cp;
169	struct cnode *		hfs_attribute_cp;
170	struct cnode *		hfs_startup_cp;
171	dev_t			hfs_raw_dev;			/* device mounted */
172	u_int32_t		hfs_logBlockSize;		/* Size of buffer cache buffer for I/O */
173
174	/* Default values for HFS standard and non-init access */
175	uid_t         hfs_uid;            /* uid to set as owner of the files */
176	gid_t         hfs_gid;            /* gid to set as owner of the files */
177	mode_t        hfs_dir_mask;       /* mask to and with directory protection bits */
178	mode_t        hfs_file_mask;      /* mask to and with file protection bits */
179	u_int32_t        hfs_encoding;       /* Default encoding for non hfs+ volumes */
180
181	/* Persistent fields (on disk, dynamic) */
182	time_t        hfs_mtime;          /* file system last modification time */
183	u_int32_t     hfs_filecount;      /* number of files in file system */
184	u_int32_t     hfs_dircount;       /* number of directories in file system */
185	u_int32_t     freeBlocks;	  /* free allocation blocks */
186	u_int32_t     nextAllocation;	  /* start of next allocation search */
187	u_int32_t     sparseAllocation;   /* start of allocations for sparse devices */
188	u_int32_t     vcbNxtCNID;         /* next unused catalog node ID - protected by catalog lock */
189	u_int32_t     vcbWrCnt;           /* file system write count */
190	u_int64_t     encodingsBitmap;    /* in-use encodings */
191	u_int16_t     vcbNmFls;           /* HFS Only - root dir file count */
192	u_int16_t     vcbNmRtDirs;        /* HFS Only - root dir directory count */
193
194	/* Persistent fields (on disk, static) */
195	u_int16_t 			vcbSigWord;
196	int16_t				vcbFlags; /* Runtime flag to indicate if volume is dirty/clean */
197	u_int32_t 			vcbAtrb;
198	u_int32_t 			vcbJinfoBlock;
199	u_int32_t 			localCreateDate;/* volume create time from volume header (For HFS+, value is in local time) */
200	time_t				hfs_itime;	/* file system creation time (creation date of the root folder) */
201	time_t				hfs_btime;	/* file system last backup time */
202	u_int32_t 			blockSize;	/* size of allocation blocks */
203	u_int32_t 			totalBlocks;	/* total allocation blocks */
204	u_int32_t			allocLimit;	/* Do not allocate this block or beyond */
205	/*
206	 * NOTE: When resizing a volume to make it smaller, allocLimit is set to the allocation
207	 * block number which will contain the new alternate volume header.  At all other times,
208	 * allocLimit is set to totalBlocks.  The allocation code uses allocLimit instead of
209	 * totalBlocks to limit which blocks may be allocated, so that during a resize, we don't
210	 * put new content into the blocks we're trying to truncate away.
211	 */
212	int32_t 			vcbClpSiz;
213	u_int32_t     vcbFndrInfo[8];
214	int16_t 			vcbVBMSt;		/* HFS only */
215	int16_t 			vcbAlBlSt;		/* HFS only */
216
217	/* vcb stuff */
218	u_int8_t		 	vcbVN[256];		/* volume name in UTF-8 */
219	u_int32_t	 		volumeNameEncodingHint;
220	u_int32_t 			hfsPlusIOPosOffset;	/* Disk block where HFS+ starts */
221	u_int32_t 			vcbVBMIOSize;		/* volume bitmap I/O size */
222
223	/* cache of largest known free extents */
224	u_int32_t			vcbFreeExtCnt;
225	HFSPlusExtentDescriptor vcbFreeExt[kMaxFreeExtents];
226	lck_spin_t			vcbFreeExtLock;
227
228#if CONFIG_HFS_ALLOC_RBTREE
229	/*
230	 * Access to these fields should only be done
231	 * after acquiring the bitmap lock.  Note that the
232	 * "offset_block_end" field indicates the portion of
233	 * the bitmap that is currently managed by the red-black tree.
234	 */
235
236	/* Normal Allocation Tree */
237	extent_tree_offset_t offset_tree;
238	u_int32_t 			offset_free_extents;  /* number of free extents managed by tree */
239	u_int32_t			offset_block_end;
240#endif
241
242	/*
243	 * For setting persistent in-mount fields that relate
244	 * to the use of the extent trees.  See HFS Red-Black
245	 * Tree Allocator Flags below.
246	 */
247	u_int32_t extent_tree_flags;
248
249
250	u_int32_t		reserveBlocks;		/* free block reserve */
251	u_int32_t		loanedBlocks;		/* blocks on loan for delayed allocations */
252
253
254	/*
255	 * HFS+ Private system directories (two). Any access
256	 * (besides looking at the cd_cnid) requires holding
257	 * the Catalog File lock.
258	 */
259	struct cat_desc     hfs_private_desc[2];
260	struct cat_attr     hfs_private_attr[2];
261
262	u_int32_t		hfs_metadata_createdate;
263	hfs_to_unicode_func_t	hfs_get_unicode;
264	unicode_to_hfs_func_t	hfs_get_hfsname;
265
266	/* Quota variables: */
267	struct quotafile	hfs_qfiles[MAXQUOTAS];    /* quota files */
268
269	/* Journaling variables: */
270	void                *jnl;           // the journal for this volume (if one exists)
271	struct vnode        *jvp;           // device where the journal lives (may be equal to devvp)
272	u_int32_t            jnl_start;     // start block of the journal file (so we don't delete it)
273	u_int32_t            jnl_size;
274	u_int32_t            hfs_jnlfileid;
275	u_int32_t            hfs_jnlinfoblkid;
276	lck_rw_t	     	hfs_global_lock;
277	u_int32_t            hfs_global_lock_nesting;
278	void*				hfs_global_lockowner;
279
280	/* Notification variables: */
281	u_int32_t		hfs_notification_conditions;
282	u_int32_t		hfs_freespace_notify_dangerlimit;
283	u_int32_t		hfs_freespace_notify_warninglimit;
284	u_int32_t		hfs_freespace_notify_desiredlevel;
285
286	/* time mounted and last mounted mod time "snapshot" */
287	time_t		hfs_mount_time;
288	time_t 		hfs_last_mounted_mtime;
289
290	/* Metadata allocation zone variables: */
291	u_int32_t	hfs_metazone_start;
292	u_int32_t	hfs_metazone_end;
293	u_int32_t	hfs_hotfile_start;
294	u_int32_t	hfs_hotfile_end;
295        u_int32_t       hfs_min_alloc_start;
296	u_int32_t       hfs_freed_block_count;
297	int		hfs_hotfile_freeblks;
298	int		hfs_hotfile_maxblks;
299	int		hfs_overflow_maxblks;
300	int		hfs_catalog_maxblks;
301
302	/* Hot File Clustering variables: */
303	lck_mtx_t       hfc_mutex;      /* serialize hot file stages */
304	enum hfc_stage  hfc_stage;      /* what are we up to... */
305	time_t		hfc_timebase;   /* recording period start time */
306	time_t		hfc_timeout;    /* recording period stop time */
307	void *		hfc_recdata;    /* recording data (opaque) */
308	int		hfc_maxfiles;   /* maximum files to track */
309	struct vnode *  hfc_filevp;
310
311#if HFS_SPARSE_DEV
312	/* Sparse device variables: */
313	struct vnode * hfs_backingfs_rootvp;
314	u_int32_t      hfs_last_backingstatfs;
315	int            hfs_sparsebandblks;
316	u_int64_t      hfs_backingfs_maxblocks;
317#endif
318	size_t         hfs_max_inline_attrsize;
319
320	lck_mtx_t      hfs_mutex;      /* protects access to hfsmount data */
321	void          *hfs_freezing_proc;  /* who froze the fs */
322	void          *hfs_downgrading_proc; /* process who's downgrading to rdonly */
323	lck_rw_t       hfs_insync;     /* protects sync/freeze interaction */
324
325	/* Resize variables: */
326	u_int32_t		hfs_resize_blocksmoved;
327	u_int32_t		hfs_resize_totalblocks;
328	u_int32_t		hfs_resize_progress;
329#if CONFIG_PROTECT
330	struct cprotect *hfs_resize_cpentry;
331	u_int16_t		hfs_running_cp_major_vers;
332#endif
333
334
335	/* Per mount cnode hash variables: */
336	lck_mtx_t      hfs_chash_mutex;	/* protects access to cnode hash table */
337	u_long         hfs_cnodehash;	/* size of cnode hash table - 1 */
338	LIST_HEAD(cnodehashhead, cnode) *hfs_cnodehashtbl;	/* base of cnode hash */
339
340
341	/*
342	 * About the sync counters:
343	 * hfs_sync_scheduled  keeps track whether a timer was scheduled but we
344	 *                     haven't started processing the callback (i.e. we
345	 *                     haven't begun the flush).  This will be non-zero
346	 *                     even if the callback has been invoked, before we
347	 *                    start the flush.
348	 * hfs_sync_incomplete keeps track of the number of callbacks that have
349	 *                     not completed yet (including callbacks not yet
350	 *                     invoked).  We cannot safely unmount until this
351	 *                     drops to zero.
352	 *
353	 * In both cases, we use counters, not flags, so that we can avoid
354	 * taking locks.
355	 */
356	int32_t		hfs_sync_scheduled;
357	int32_t		hfs_sync_incomplete;
358	u_int64_t       hfs_last_sync_request_time;
359	u_int64_t       hfs_last_sync_time;
360	u_int32_t       hfs_active_threads;
361	u_int64_t       hfs_max_pending_io;
362
363	thread_call_t   hfs_syncer;	      // removeable devices get sync'ed by this guy
364
365} hfsmount_t;
366
367#define HFS_META_DELAY     (100)
368#define HFS_MILLISEC_SCALE (1000*1000)
369
370typedef hfsmount_t  ExtendedVCB;
371
372/* Aliases for legacy (Mac OS 9) field names */
373#define vcbLsMod           hfs_mtime
374#define vcbVolBkUp         hfs_btime
375#define extentsRefNum      hfs_extents_vp
376#define catalogRefNum      hfs_catalog_vp
377#define allocationsRefNum  hfs_allocation_vp
378#define vcbFilCnt          hfs_filecount
379#define vcbDirCnt          hfs_dircount
380
381/* Inline functions to set/reset vcbFlags.  Upper 8 bits indicate if the volume
382 * header/VCB is clean/dirty --- if set, volume header is dirty, and
383 * if clear, volume header is clean.  This value is checked to determine
384 * if the in-memory copy of volume header should be flushed to the disk
385 * or not.
386 */
387/* Set runtime flag to indicate that volume is dirty */
388static __inline__ void MarkVCBDirty(ExtendedVCB *vcb)
389{
390	vcb->vcbFlags |= 0xFF00;
391}
392
393/* Clear runtime flag to indicate that volume is dirty */
394static __inline__ void MarkVCBClean(ExtendedVCB *vcb)
395{
396	vcb->vcbFlags &= 0x00FF;
397}
398
399/* Check runtime flag to determine if the volume is dirty or not */
400static __inline__ Boolean IsVCBDirty(ExtendedVCB *vcb)
401{
402	return (vcb->vcbFlags & 0xFF00 ? true  : false);
403}
404
405/*
406 * There are two private directories in HFS+.
407 *
408 * One contains inodes for files that are hardlinked or open/unlinked.
409 * The other contains inodes for directories that are hardlinked.
410 */
411enum privdirtype {FILE_HARDLINKS, DIR_HARDLINKS};
412
413/* HFS Red-Black Tree Allocator Flags */
414#define HFS_ALLOC_RB_ENABLED		0x000001  	/* trees in use */
415#define HFS_ALLOC_RB_ERRORED		0x000002 	/* tree hit error; disabled for the mount */
416#define HFS_ALLOC_RB_MZACTIVE		0x000004 	/* metazone tree has finished building */
417#define HFS_ALLOC_RB_ACTIVE			0x000008	/* normalzone tree finished building */
418
419/* HFS Red-Black Unmount Synch. Flags */
420#define HFS_ALLOC_TREEBUILD_INFLIGHT	0x000010
421#define HFS_ALLOC_TEARDOWN_INFLIGHT		0x000020
422
423/* HFS mount point flags */
424#define HFS_READ_ONLY             0x00001
425#define HFS_UNKNOWN_PERMS         0x00002
426#define HFS_WRITEABLE_MEDIA       0x00004
427#define HFS_CLEANED_ORPHANS       0x00008
428#define HFS_X                     0x00010
429#define HFS_CASE_SENSITIVE        0x00020
430#define HFS_STANDARD              0x00040
431#define HFS_METADATA_ZONE         0x00080
432#define HFS_FRAGMENTED_FREESPACE  0x00100
433#define HFS_NEED_JNL_RESET        0x00200
434#define HFS_HAS_SPARSE_DEVICE     0x00400
435#define HFS_RESIZE_IN_PROGRESS    0x00800
436#define HFS_QUOTAS                0x01000
437#define HFS_CREATING_BTREE        0x02000
438/* When set, do not update nextAllocation in the mount structure */
439#define HFS_SKIP_UPDATE_NEXT_ALLOCATION 0x04000
440/* When set, the file system supports extent-based extended attributes */
441#define HFS_XATTR_EXTENTS         0x08000
442#define	HFS_FOLDERCOUNT           0x10000
443/* When set, the file system exists on a virtual device, like disk image */
444#define HFS_VIRTUAL_DEVICE        0x20000
445/* When set, we're in hfs_changefs, so hfs_sync should do nothing. */
446#define HFS_IN_CHANGEFS           0x40000
447/* When set, we are in process of downgrading or have downgraded to read-only,
448 * so hfs_start_transaction should return EROFS.
449 */
450#define HFS_RDONLY_DOWNGRADE      0x80000
451#define HFS_DID_CONTIG_SCAN      0x100000
452#define HFS_UNMAP                0x200000
453#define HFS_SSD					 0x400000
454
455
456
457/* Macro to update next allocation block in the HFS mount structure.  If
458 * the HFS_SKIP_UPDATE_NEXT_ALLOCATION is set, do not update
459 * nextAllocation block.
460 */
461#define HFS_UPDATE_NEXT_ALLOCATION(hfsmp, new_nextAllocation)			\
462	{								\
463		if ((hfsmp->hfs_flags & HFS_SKIP_UPDATE_NEXT_ALLOCATION) == 0)\
464			hfsmp->nextAllocation = new_nextAllocation;	\
465	}								\
466
467#define HFS_MOUNT_LOCK(hfsmp, metadata)                      \
468	{                                                    \
469		if ((metadata) && 1)                         \
470			lck_mtx_lock(&(hfsmp)->hfs_mutex);   \
471	}                                                    \
472
473#define HFS_MOUNT_UNLOCK(hfsmp, metadata)                    \
474	{                                                    \
475		if ((metadata) && 1)                         \
476			lck_mtx_unlock(&(hfsmp)->hfs_mutex); \
477	}                                                    \
478
479/* Macro for incrementing and decrementing the folder count in a cnode
480 * attribute only if the HFS_FOLDERCOUNT bit is set in the mount flags
481 * and kHFSHasFolderCount bit is set in the cnode flags.  Currently these
482 * bits are only set for case sensitive HFS+ volumes.
483 */
484#define INC_FOLDERCOUNT(hfsmp, cattr) 				\
485	if ((hfsmp->hfs_flags & HFS_FOLDERCOUNT) &&		\
486	    (cattr.ca_recflags & kHFSHasFolderCountMask)) { 	\
487		cattr.ca_dircount++;				\
488	}							\
489
490#define DEC_FOLDERCOUNT(hfsmp, cattr) 				\
491	if ((hfsmp->hfs_flags & HFS_FOLDERCOUNT) &&		\
492	    (cattr.ca_recflags & kHFSHasFolderCountMask) && 	\
493	    (cattr.ca_dircount > 0)) { 				\
494		cattr.ca_dircount--;				\
495	}							\
496
497typedef struct filefork FCB;
498
499/*
500 * Macros for creating item names for our special/private directories.
501 */
502#define MAKE_INODE_NAME(name, size, linkno) \
503	    (void) snprintf((name), size, "%s%d", HFS_INODE_PREFIX, (linkno))
504#define HFS_INODE_PREFIX_LEN	5
505
506#define MAKE_DIRINODE_NAME(name, size, linkno) \
507	    (void) snprintf((name), size, "%s%d", HFS_DIRINODE_PREFIX, (linkno))
508#define HFS_DIRINODE_PREFIX_LEN   4
509
510#define MAKE_DELETED_NAME(NAME, size, FID) \
511	    (void) snprintf((NAME), size, "%s%d", HFS_DELETE_PREFIX, (FID))
512#define HFS_DELETE_PREFIX_LEN	4
513
514
515#define HFS_AVERAGE_NAME_SIZE	22
516#define AVERAGE_HFSDIRENTRY_SIZE  (8+HFS_AVERAGE_NAME_SIZE+4)
517
518#define STD_DIRENT_LEN(namlen) \
519	((sizeof(struct dirent) - (NAME_MAX+1)) + (((namlen)+1 + 3) &~ 3))
520
521#define EXT_DIRENT_LEN(namlen) \
522	((sizeof(struct direntry) + (namlen) - (MAXPATHLEN-1) + 3) & ~3)
523
524
525enum { kHFSPlusMaxFileNameBytes = kHFSPlusMaxFileNameChars * 3 };
526
527
528/* macro to determine if hfs or hfsplus */
529#define ISHFSPLUS(VCB) ((VCB)->vcbSigWord == kHFSPlusSigWord)
530#define ISHFS(VCB) ((VCB)->vcbSigWord == kHFSSigWord)
531
532
533/*
534 * Various ways to acquire a VFS mount point pointer:
535 */
536#define VTOVFS(VP)  vnode_mount((VP))
537#define HFSTOVFS(HFSMP) ((HFSMP)->hfs_mp)
538#define VCBTOVFS(VCB)   HFSTOVFS(VCB)
539
540/*
541 * Various ways to acquire an HFS mount point pointer:
542 */
543#define VTOHFS(VP)  ((struct hfsmount *)vfs_fsprivate(vnode_mount((VP))))
544#define	VFSTOHFS(MP)  ((struct hfsmount *)vfs_fsprivate((MP)))
545#define VCBTOHFS(VCB) (VCB)
546#define FCBTOHFS(FCB)  ((struct hfsmount *)vfs_fsprivate(vnode_mount((FCB)->ff_cp->c_vp)))
547
548/*
549 * Various ways to acquire a VCB (legacy) pointer:
550 */
551#define VTOVCB(VP)       VTOHFS(VP)
552#define VFSTOVCB(MP)     VFSTOHFS(MP)
553#define HFSTOVCB(HFSMP)  (HFSMP)
554#define FCBTOVCB(FCB)    FCBTOHFS(FCB)
555
556
557#define E_NONE	0
558#define kHFSBlockSize 512
559
560/*
561 * Macros for getting the MDB/VH sector and offset
562 */
563#define HFS_PRI_SECTOR(blksize)          (1024 / (blksize))
564#define HFS_PRI_OFFSET(blksize)          ((blksize) > 1024 ? 1024 : 0)
565
566#define HFS_ALT_SECTOR(blksize, blkcnt)  (((blkcnt) - 1) - (512 / (blksize)))
567#define HFS_ALT_OFFSET(blksize)          ((blksize) > 1024 ? (blksize) - 1024 : 0)
568
569/* Convert the logical sector number to be aligned on physical block size boundary.
570 * We are assuming the partition is a multiple of physical block size.
571 */
572#define HFS_PHYSBLK_ROUNDDOWN(sector_num, log_per_phys)	((sector_num / log_per_phys) * log_per_phys)
573
574/*
575 * HFS specific fcntl()'s
576 */
577#define HFS_GET_BOOT_INFO   (FCNTL_FS_SPECIFIC_BASE + 0x00004)
578#define HFS_SET_BOOT_INFO   (FCNTL_FS_SPECIFIC_BASE + 0x00005)
579/* See HFSIOC_EXT_BULKACCESS and friends for HFS specific fsctls*/
580
581
582
583/*
584 *	This is the straight GMT conversion constant:
585 *	00:00:00 January 1, 1970 - 00:00:00 January 1, 1904
586 *	(3600 * 24 * ((365 * (1970 - 1904)) + (((1970 - 1904) / 4) + 1)))
587 */
588#define MAC_GMT_FACTOR		2082844800UL
589
590
591/*****************************************************************************
592	FUNCTION PROTOTYPES
593******************************************************************************/
594
595/*****************************************************************************
596	hfs_vnop_xxx functions from different files
597******************************************************************************/
598int hfs_vnop_readdirattr(struct vnop_readdirattr_args *);  /* in hfs_attrlist.c */
599
600int hfs_vnop_inactive(struct vnop_inactive_args *);        /* in hfs_cnode.c */
601int hfs_vnop_reclaim(struct vnop_reclaim_args *);          /* in hfs_cnode.c */
602
603int hfs_set_backingstore (struct vnode *vp, int val);				/* in hfs_cnode.c */
604int hfs_is_backingstore (struct vnode *vp, int *val);		/* in hfs_cnode.c */
605
606int hfs_vnop_link(struct vnop_link_args *);                /* in hfs_link.c */
607
608int hfs_vnop_lookup(struct vnop_lookup_args *);            /* in hfs_lookup.c */
609
610int hfs_vnop_search(struct vnop_searchfs_args *);          /* in hfs_search.c */
611
612int hfs_vnop_read(struct vnop_read_args *);           /* in hfs_readwrite.c */
613int hfs_vnop_write(struct vnop_write_args *);         /* in hfs_readwrite.c */
614int hfs_vnop_ioctl(struct vnop_ioctl_args *);         /* in hfs_readwrite.c */
615int hfs_vnop_select(struct vnop_select_args *);       /* in hfs_readwrite.c */
616int hfs_vnop_strategy(struct vnop_strategy_args *);   /* in hfs_readwrite.c */
617int hfs_vnop_allocate(struct vnop_allocate_args *);   /* in hfs_readwrite.c */
618int hfs_vnop_pagein(struct vnop_pagein_args *);       /* in hfs_readwrite.c */
619int hfs_vnop_pageout(struct vnop_pageout_args *);     /* in hfs_readwrite.c */
620int hfs_vnop_bwrite(struct vnop_bwrite_args *);       /* in hfs_readwrite.c */
621int hfs_vnop_blktooff(struct vnop_blktooff_args *);   /* in hfs_readwrite.c */
622int hfs_vnop_offtoblk(struct vnop_offtoblk_args *);   /* in hfs_readwrite.c */
623int hfs_vnop_blockmap(struct vnop_blockmap_args *);   /* in hfs_readwrite.c */
624
625int hfs_vnop_getxattr(struct vnop_getxattr_args *);        /* in hfs_xattr.c */
626int hfs_vnop_setxattr(struct vnop_setxattr_args *);        /* in hfs_xattr.c */
627int hfs_vnop_removexattr(struct vnop_removexattr_args *);  /* in hfs_xattr.c */
628int hfs_vnop_listxattr(struct vnop_listxattr_args *);      /* in hfs_xattr.c */
629#if NAMEDSTREAMS
630extern int hfs_vnop_getnamedstream(struct vnop_getnamedstream_args*);
631extern int hfs_vnop_makenamedstream(struct vnop_makenamedstream_args*);
632extern int hfs_vnop_removenamedstream(struct vnop_removenamedstream_args*);
633#endif
634
635
636/*****************************************************************************
637	Functions from MacOSStubs.c
638******************************************************************************/
639time_t to_bsd_time(u_int32_t hfs_time);
640
641u_int32_t to_hfs_time(time_t bsd_time);
642
643
644/*****************************************************************************
645	Functions from hfs_encodinghint.c
646******************************************************************************/
647u_int32_t hfs_pickencoding(const u_int16_t *src, int len);
648
649u_int32_t hfs_getencodingbias(void);
650
651void hfs_setencodingbias(u_int32_t bias);
652
653
654/*****************************************************************************
655	Functions from hfs_encodings.c
656******************************************************************************/
657void hfs_converterinit(void);
658
659int hfs_getconverter(u_int32_t encoding, hfs_to_unicode_func_t *get_unicode,
660		     unicode_to_hfs_func_t *get_hfsname);
661
662int hfs_relconverter(u_int32_t encoding);
663
664int hfs_to_utf8(ExtendedVCB *vcb, const Str31 hfs_str, ByteCount maxDstLen,
665		ByteCount *actualDstLen, unsigned char* dstStr);
666
667int utf8_to_hfs(ExtendedVCB *vcb, ByteCount srcLen, const unsigned char* srcStr,
668		Str31 dstStr);
669
670int mac_roman_to_utf8(const Str31 hfs_str, ByteCount maxDstLen, ByteCount *actualDstLen,
671		unsigned char* dstStr);
672
673int utf8_to_mac_roman(ByteCount srcLen, const unsigned char* srcStr, Str31 dstStr);
674
675int mac_roman_to_unicode(const Str31 hfs_str, UniChar *uni_str, u_int32_t maxCharLen, u_int32_t *usedCharLen);
676
677int unicode_to_hfs(ExtendedVCB *vcb, ByteCount srcLen, u_int16_t* srcStr, Str31 dstStr, int retry);
678
679
680/*****************************************************************************
681	Functions from hfs_notifications.c
682******************************************************************************/
683void hfs_generate_volume_notifications(struct hfsmount *hfsmp);
684
685
686/*****************************************************************************
687	Functions from hfs_readwrite.c
688******************************************************************************/
689extern int  hfs_relocate(struct  vnode *, u_int32_t, kauth_cred_t, struct  proc *);
690
691extern int hfs_truncate(struct vnode *, off_t, int, int, int, vfs_context_t);
692
693extern int hfs_release_storage (struct hfsmount *hfsmp, struct filefork *datafork,
694								struct filefork *rsrcfork,  u_int32_t fileid);
695
696extern int hfs_prepare_release_storage (struct hfsmount *hfsmp, struct vnode *vp);
697
698extern int hfs_bmap(struct vnode *, daddr_t, struct vnode **, daddr64_t *, unsigned int *);
699
700extern int hfs_fsync(struct vnode *, int, int, struct proc *);
701
702extern int hfs_access(struct vnode *, mode_t, kauth_cred_t, struct proc *);
703
704extern int hfs_removeallattr(struct hfsmount *hfsmp, u_int32_t fileid);
705
706extern int hfs_set_volxattr(struct hfsmount *hfsmp, unsigned int xattrtype, int state);
707
708extern int hfs_isallocated(struct hfsmount *hfsmp, u_int32_t startingBlock, u_int32_t numBlocks);
709
710extern int hfs_count_allocated(struct hfsmount *hfsmp, u_int32_t startBlock,
711		u_int32_t numBlocks, u_int32_t *alloc_count);
712
713extern int hfs_isrbtree_active (struct hfsmount *hfsmp);
714
715
716/*****************************************************************************
717	Functions from hfs_vfsops.c
718******************************************************************************/
719int hfs_mountroot(mount_t mp, vnode_t rvp, vfs_context_t context);
720
721/* used as a callback by the journaling code */
722extern void hfs_sync_metadata(void *arg);
723
724extern int hfs_vget(struct hfsmount *, cnid_t, struct vnode **, int, int);
725
726extern void hfs_setencodingbits(struct hfsmount *hfsmp, u_int32_t encoding);
727
728enum volop {VOL_UPDATE, VOL_MKDIR, VOL_RMDIR, VOL_MKFILE, VOL_RMFILE};
729extern int hfs_volupdate(struct hfsmount *hfsmp, enum volop op, int inroot);
730
731int hfs_flushvolumeheader(struct hfsmount *hfsmp, int waitfor, int altflush);
732#define HFS_ALTFLUSH	1
733
734extern int  hfs_extendfs(struct hfsmount *, u_int64_t, vfs_context_t);
735extern int  hfs_truncatefs(struct hfsmount *, u_int64_t, vfs_context_t);
736extern int  hfs_resize_progress(struct hfsmount *, u_int32_t *);
737
738/* If a runtime corruption is detected, mark the volume inconsistent
739 * bit in the volume attributes.
740 */
741void hfs_mark_volume_inconsistent(struct hfsmount *hfsmp);
742
743/*****************************************************************************
744	Functions from hfs_vfsutils.c
745******************************************************************************/
746u_int32_t BestBlockSizeFit(u_int32_t allocationBlockSize,
747                               u_int32_t blockSizeLimit,
748                               u_int32_t baseMultiple);
749
750OSErr	hfs_MountHFSVolume(struct hfsmount *hfsmp, HFSMasterDirectoryBlock *mdb,
751		struct proc *p);
752OSErr	hfs_MountHFSPlusVolume(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp,
753		off_t embeddedOffset, u_int64_t disksize, struct proc *p, void *args, kauth_cred_t cred);
754
755extern int hfsUnmount(struct hfsmount *hfsmp, struct proc *p);
756
757extern int overflow_extents(struct filefork *fp);
758
759extern int hfs_owner_rights(struct hfsmount *hfsmp, uid_t cnode_uid, kauth_cred_t cred,
760		struct proc *p, int invokesuperuserstatus);
761
762extern int check_for_tracked_file(struct vnode *vp, time_t ctime, uint64_t op_type, void *arg);
763extern int check_for_dataless_file(struct vnode *vp, uint64_t op_type);
764
765/*
766 * Journal lock function prototypes
767 */
768int hfs_lock_global (struct hfsmount *hfsmp, enum hfslocktype locktype);
769void hfs_unlock_global (struct hfsmount *hfsmp);
770
771
772/* HFS System file locking */
773#define SFL_CATALOG     0x0001
774#define SFL_EXTENTS     0x0002
775#define SFL_BITMAP      0x0004
776#define SFL_ATTRIBUTE   0x0008
777#define SFL_STARTUP	0x0010
778#define SFL_VALIDMASK   (SFL_CATALOG | SFL_EXTENTS | SFL_BITMAP | SFL_ATTRIBUTE | SFL_STARTUP)
779
780extern int  hfs_systemfile_lock(struct hfsmount *, int, enum hfslocktype);
781extern void hfs_systemfile_unlock(struct hfsmount *, int);
782
783extern u_int32_t  GetFileInfo(ExtendedVCB *vcb, u_int32_t dirid, const char *name,
784						   struct cat_attr *fattr, struct cat_fork *forkinfo);
785
786extern void hfs_remove_orphans(struct hfsmount *);
787
788u_int32_t GetLogicalBlockSize(struct vnode *vp);
789
790extern u_int32_t hfs_freeblks(struct hfsmount * hfsmp, int wantreserve);
791
792short MacToVFSError(OSErr err);
793
794void hfs_metadatazone_init(struct hfsmount *hfsmp, int disable);
795
796/* HFS directory hint functions. */
797extern directoryhint_t * hfs_getdirhint(struct cnode *, int, int);
798extern void  hfs_reldirhint(struct cnode *, directoryhint_t *);
799extern void  hfs_reldirhints(struct cnode *, int);
800extern void  hfs_insertdirhint(struct cnode *, directoryhint_t *);
801
802extern int hfs_namecmp(const u_int8_t *str1, size_t len1, const u_int8_t *str2, size_t len2);
803
804extern int     hfs_early_journal_init(struct hfsmount *hfsmp, HFSPlusVolumeHeader *vhp,
805			   void *_args, off_t embeddedOffset, daddr64_t mdb_offset,
806			   HFSMasterDirectoryBlock *mdbp, kauth_cred_t cred);
807
808extern int  hfs_virtualmetafile(struct cnode *);
809
810extern int hfs_start_transaction(struct hfsmount *hfsmp);
811extern int hfs_end_transaction(struct hfsmount *hfsmp);
812extern int hfs_journal_flush(struct hfsmount *hfsmp, boolean_t wait_for_IO);
813extern void hfs_sync_ejectable(struct hfsmount *hfsmp);
814
815extern void hfs_trim_callback(void *arg, uint32_t extent_count, const dk_extent_t *extents);
816
817/* Erase unused Catalog nodes due to <rdar://problem/6947811>. */
818extern int hfs_erase_unused_nodes(struct hfsmount *hfsmp);
819
820
821/*****************************************************************************
822	Functions from hfs_vnops.c
823******************************************************************************/
824int hfs_write_access(struct vnode *vp, kauth_cred_t cred, struct proc *p, Boolean considerFlags);
825
826int hfs_chmod(struct vnode *vp, int mode, kauth_cred_t cred, struct proc *p);
827
828int hfs_chown(struct vnode *vp, uid_t uid, gid_t gid, kauth_cred_t cred, struct proc *p);
829
830#define  kMaxSecsForFsync	5
831#define  HFS_SYNCTRANS		1
832extern int hfs_btsync(struct vnode *vp, int sync_transaction);
833
834extern void replace_desc(struct cnode *cp, struct cat_desc *cdp);
835
836extern int hfs_vgetrsrc(struct hfsmount *hfsmp, struct vnode *vp,
837			struct vnode **rvpp, int can_drop_lock, int error_on_unlink);
838
839extern int hfs_update(struct vnode *, int);
840
841
842/*****************************************************************************
843	Functions from hfs_xattr.c
844******************************************************************************/
845
846/* Maximum extended attribute size supported for all extended attributes except
847 * resource fork and finder info.
848 */
849#define HFS_XATTR_MAXSIZE	(128 * 1024)
850
851/* Number of bits used to represent maximum extended attribute size */
852#define HFS_XATTR_SIZE_BITS	18
853
854int  hfs_attrkeycompare(HFSPlusAttrKey *searchKey, HFSPlusAttrKey *trialKey);
855int  hfs_buildattrkey(u_int32_t fileID, const char *attrname, HFSPlusAttrKey *key);
856void hfs_xattr_init(struct hfsmount * hfsmp);
857int file_attribute_exist(struct hfsmount *hfsmp, uint32_t fileID);
858int init_attrdata_vnode(struct hfsmount *hfsmp);
859int hfs_getxattr_internal(struct cnode *, struct vnop_getxattr_args *,
860							struct hfsmount *, u_int32_t);
861int hfs_setxattr_internal(struct cnode *, caddr_t, size_t,
862						  struct vnop_setxattr_args *, struct hfsmount *, u_int32_t);
863
864
865
866/*****************************************************************************
867	Functions from hfs_link.c
868******************************************************************************/
869
870extern int  hfs_unlink(struct hfsmount *hfsmp, struct vnode *dvp, struct vnode *vp,
871                       struct componentname *cnp, int skip_reserve);
872extern int  hfs_lookup_siblinglinks(struct hfsmount *hfsmp, cnid_t linkfileid,
873                           cnid_t *prevlinkid,  cnid_t *nextlinkid);
874extern void  hfs_privatedir_init(struct hfsmount *, enum privdirtype);
875
876extern void  hfs_savelinkorigin(cnode_t *cp, cnid_t parentcnid);
877extern void  hfs_relorigins(struct cnode *cp);
878extern void  hfs_relorigin(struct cnode *cp, cnid_t parentcnid);
879extern int   hfs_haslinkorigin(cnode_t *cp);
880extern cnid_t  hfs_currentparent(cnode_t *cp);
881extern cnid_t  hfs_currentcnid(cnode_t *cp);
882
883
884#endif /* __APPLE_API_PRIVATE */
885#endif /* KERNEL */
886#endif /* __HFS__ */
887