Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

14.2 Virtual File System Buffer Initialization

14.2.1 Introduction to the Virtual File System

The Virtual File System (VFS) is a software layer within the kernel designed to provide a uniform file interface to user space. In Linux, everything is handled as a file. Linux files include disk files, pipes, sockets, and I/O devices. To uniquely identify a file, Linux utilizes an index node (inode) to represent it. An inode stores file metadata, which primarily encompasses the file size, device ID, user ID, group ID, file read/write modes, user access permissions, physical storage location, the reference count of users currently accessing the file, and file protection flags. The filename and the raw contents of the file itself are not stored within the inode. The definition of the inode structure is located in the file git/include/linux/fs.h and contains a large array of fields to facilitate diverse file operations and ensure file system access security.

User-space file operations involve a significant amount of directory path lookup procedures. To maximize lookup efficiency, Linux carves out a fallback caching zone in memory named the Dentry Cache (dcache). Each tracking entry within this cache block consists of a structure of type struct dentry, which is utilized to preserve frequently accessed path components. The dentry structure is declared within the file git/include/linux/dcache.h. When a user invokes a file operation, Linux first queries the dcache buffer to find a matching dentry for the targeted path or filename. A dentry encloses a direct pointer to its corresponding inode, thereby mapping out the concrete file represented by that entry. If a matching dentry cannot be located, Linux traverses upward through the directory hierarchy step-by-step from the parent node to resolve the file's inode. Upon successfully locating it, Linux instantiates a new dentry entry inside the dcache, which drastically accelerates future path resolution routines.

14.2.2 Hash Tables

Because the absolute number of files contained within a Linux file system can be exceptionally massive, it is impossible to cache the dentry descriptors for all files simultaneously inside the active buffer zone. To circumvent this scale barrier, Linux manages the dcache buffer by structuring it as a hash table. Querying a filename or path component within the cache can then be executed by passing the tokens through a specialized hash function.

A hash table is an extensively applied data structure characterized by its ability to store a large, unpredictable volume of indexed data within a relatively small set of fixed storage slots, while maintaining a baseline query time that remains fundamentally constant. The fundamental building block of a hash table is a bucket, with each bucket preserving explicit lookup keys alongside their corresponding data payload records. One primary challenge present in hash table architectures is the phenomenon of hash collisions—where distinct keys map onto the exact same index location within the table. Diversified strategies exist to resolve hash collisions, one of which is the chained list methodology. When chaining is employed to resolve collisions, each bucket encloses an additional structural pointer referencing a subsequent bucket. When a collision manifests, the colliding key and its associated payload are appended into a newly linked bucket slot down the chain.

When querying a hash table, the engine first runs a hash function to map the user-supplied lookup key into a target hash table index. If the key enclosed inside the bucket referenced by that index matches the target lookup key, the query result is immediately returned. If the keys diverge, the lookup tracking routine traces down the linked chain to evaluate the subsequent bucket slots, repeating this pass until the target key is matched or the tail boundary of the chain is reached. If the matching key cannot be located anywhere along the index's chained list, the query operation evaluates as a failure.

When executing an insertion operation, the key and the hash function are leveraged to compute the appropriate hash table index. If the bucket referenced by this index or any subsequent bucket down its linked chain is currently empty, the key and its corresponding data payload are written directly into that vacant slot. If no empty bucket is found along the existing chain, the subsystem allocates a brand-new bucket descriptor block, records the key and data payload within it, and appends the base address of this new bucket onto the pointer field of the preceding bucket in the chain. The layout of a hash table utilizing chained buckets is illustrated in Figure 14-4.

Figure 14-4 Structural Layout of a Hash Table

As demonstrated by the diagram above, a hash table is functionally composed of an array of independent linked lists, where each specific list encapsulates all entries that map to an identical hash table index value.

14.2.3 Initializing the Virtual File System Caches

The start_kernel() function performs the initialization of the memory buffers utilized by the virtual file system by invoking vfs_caches_init_early(). The routine vfs_caches_init_early() is defined within the source file git/fs/dcache.c, and its definition is implemented as follows:

void __init vfs_caches_init_early(void)
{
	int i;
	for (i = 0; i < ARRAY_SIZE(in_lookup_hashtable); i++)
		INIT_HLIST_BL_HEAD(&in_lookup_hashtable[i]);
	dcache_init_early();
	inode_init_early();
}

This function first utilizes the macro definition INIT_HLIST_BL_HEAD to initialize the bucket pointers of the hash table in_lookup_hashtable (i.e., the linked list heads) to null. The type of this linked list head is a pointer to a struct hlist_bl_head structure, which is declared as:

struct hlist_bl_head {
	struct hlist_bl_node *first;
};

It contains only a single tracking pointer field named first, whose data type resolves to a pointer referencing a structure of type:

struct hlist_bl_node {
	struct hlist_bl_node *next, **pprev;
};

The first field of the hash table bucket points to the initial element of the dentry list, which is of type struct hlist_bl_node. Linux leverages the d_hash member to chain together all colliding bucket elements that resolve to an identical index location, thereby composing the explicit linked list for that hash index. When the hash table is fully established, if a bucket corresponding to a particular index contains valid entries, the first pointer of the corresponding hash header points directly to the leading dentry of that index's list—specifically capturing the base memory address of the first dentry's d_hash field.

The next and pprev pointers within the d_hash field of the list components reference the base memory addresses of the d_hash fields belonging to the subsequent and preceding dentry entries, respectively. The pprev pointer of the very first element points back to the parent list head pointer itself, which maps to in_lookup_hashtable. The detailed configuration of the hash table framework adopted by the VFS is illustrated in Figure 14-5.

Figure 14-5 Hash Table Architecture Adopted by VFS

Following the initialization of these hash table headers, vfs_caches_init_early() invokes the routine dcache_init_early() to initialize the dcache buffer zone. The dcache_init_early() function is declared within git/fs/dcache.c and is implemented as:

static void __init dcache_init_early(void)
{
	if (hashdist)
		return;
	dentry_hashtable = alloc_large_system_hash("Dentry cache",sizeof(struct hlist_bl_head), 
       dhash_entries,13,HASH_EARLY | HASH_ZERO,&d_hash_shift,NULL,0,0);
	d_hash_shift = 32 - d_hash_shift;
}

This routine first tests the runtime value of the global variable hashdist to determine whether the hash table elements must be distributed across the distinct nodes of a NUMA architecture. If the configuration dictates that the hash table should be distributed across varying nodes, the early initialization pass is deferred, and dcache_init_early() exits immediately. Conversely, if the hash table components are centralized together, the routine invokes alloc_large_system_hash() to allocate a memory tracking buffer named "Dentry cache". The prototype signature of alloc_large_system_hash() is specified as follows:

void *__init alloc_large_system_hash(const char *tablename,
                                     unsigned long bucketsize,
                                     unsigned long numentries,
                                     int scale,
                                     int flags,
                                     unsigned int *_hash_shift,
                                     unsigned int *_hash_mask,
                                     unsigned long low_limit,
                                     unsigned long high_limit);

Within this tracking interface, tablename references the target string identity assigned to the cache buffer. bucketsize dictates the explicit capacity of an individual bucket, measured in raw bytes. numentries configures the total number of entries contained within the dcache hash table, which is supplied by the global variable dhash_entries. The default value of dhash_entries evaluates to 0, though it can be overridden to alternative constraints via the kernel command line parameters utilizing the option "dhash_entries=" during device tree processing. Currently, few hardware platforms explicitly define dhash_entries via command line arguments, and the vast majority rely on the default evaluation.

The function alloc_large_system_hash() can be triggered during early bootstrap initialization or invoked at later execution stages. It can wipe the allocated memory allocations to zero or fill the allocation blocks with -1. The memory allocation tracking algorithms differ depending on whether the call happens during early boot or late stages. When the flags parameter enables the bitmask flag HASH_EARLY, the system employs the early boot-stage block memory allocator framework; otherwise, it defaults to standard regular runtime allocation utilities. If invoked at later stages, the function allocates a cache area within the kernel's virtual memory space dedicated to caching dentry structures, whose base address is logged at dentry_cache. Diverging from the primary hash table tracking array, this memory zone preserves the literal dentry cache structures themselves, and is typically aligned to optimize Level 1 (L1 cache) high-speed cache lines. The buckets of the hash table store only the pointer members related to the underlying linked list architecture, whose sole purpose is to establish the memory storage locations of the cached dentry elements. When the system executes a cache query, it queries the dentry cache allocation first, which occupies a smaller memory footprint and delivers faster execution response times.

When the flags parameter enables the bitmask flag HASH_ZERO, the routine calls block memory allocation functions that zero out the memory payload; otherwise, it invokes memblock_alloc_raw() to allocate raw blocks and fills the payload with -1.

The scale argument determines the size scaling factor relative to memory pages. _hash_shift captures the bit width utilized to right-shift hash values when computing index mappings via the hash function. low_limit and high_limit specify the maximum and minimum capacity boundaries enforced on the hash table allocation space, while _hash_mask returns the bitmask utilized to isolate hash index values.

Upon initializing the dcache buffer infrastructure, the vfs_caches_init_early() function invokes inode_init_early() to allocate a separate tracking cache for the virtual file system designated as "Inode-cache". inode_init_early() is defined within the source file git/fs/inode.c, and its definition is implemented as follows:

void __init inode_init_early(void)
{
	if (hashdist)
		return;
	inode_hashtable = alloc_large_system_hash("Inode-cache", sizeof(struct hlist_head),
     ihash_entries,14,HASH_EARLY|HASH_ZERO, &i_hash_shift, &i_hash_mask,0,0);
}

The programmatic structure of this routine is functionally identical to the statements executed during dcache configuration. The Inode Cache acts as the target hash table used when querying file index nodes (inode structures). Similarly, the individual buckets of this hash table store only the pointer tracking elements related to the underlying linked list architecture, which are leveraged to determine the precise memory locations of the cached inode entries.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com