1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Default implementations and global values for the VFS. */
7 #include <vfs.h> // keep this first
20 struct sb_tailq super_blocks = TAILQ_HEAD_INITIALIZER(super_blocks);
21 spinlock_t super_blocks_lock = SPINLOCK_INITIALIZER;
22 struct fs_type_tailq file_systems = TAILQ_HEAD_INITIALIZER(file_systems);
23 struct namespace default_ns;
25 struct kmem_cache *dentry_kcache; // not to be confused with the dcache
26 struct kmem_cache *inode_kcache;
27 struct kmem_cache *file_kcache;
29 /* Mounts fs from dev_name at mnt_pt in namespace ns. There could be no mnt_pt,
30 * such as with the root of (the default) namespace. Not sure how it would work
31 * with multiple namespaces on the same FS yet. Note if you mount the same FS
32 * multiple times, you only have one FS still (and one SB). If we ever support
34 struct vfsmount *__mount_fs(struct fs_type *fs, char *dev_name,
35 struct dentry *mnt_pt, int flags,
38 struct super_block *sb;
39 struct vfsmount *vmnt = kmalloc(sizeof(struct vfsmount), 0);
41 /* this first ref is stored in the NS tailq below */
42 kref_init(&vmnt->mnt_kref, fake_release, 1);
43 /* Build the vfsmount, if there is no mnt_pt, mnt is the root vfsmount (for
44 * now). fields related to the actual FS, like the sb and the mnt_root are
45 * set in the fs-specific get_sb() call. */
47 vmnt->mnt_parent = NULL;
48 vmnt->mnt_mountpoint = NULL;
49 } else { /* common case, but won't be tested til we try to mount another FS */
50 mnt_pt->d_mount_point = TRUE;
51 mnt_pt->d_mounted_fs = vmnt;
52 kref_get(&vmnt->mnt_kref, 1); /* held by mnt_pt */
53 vmnt->mnt_parent = mnt_pt->d_sb->s_mount;
54 vmnt->mnt_mountpoint = mnt_pt;
56 TAILQ_INIT(&vmnt->mnt_child_mounts);
57 vmnt->mnt_flags = flags;
58 vmnt->mnt_devname = dev_name;
59 vmnt->mnt_namespace = ns;
60 kref_get(&ns->kref, 1); /* held by vmnt */
62 /* Read in / create the SB */
63 sb = fs->get_sb(fs, flags, dev_name, vmnt);
65 panic("You're FS sucks");
67 /* TODO: consider moving this into get_sb or something, in case the SB
68 * already exists (mounting again) (if we support that) */
69 spin_lock(&super_blocks_lock);
70 TAILQ_INSERT_TAIL(&super_blocks, sb, s_list); /* storing a ref here... */
71 spin_unlock(&super_blocks_lock);
73 /* Update holding NS */
75 TAILQ_INSERT_TAIL(&ns->vfsmounts, vmnt, mnt_list);
76 spin_unlock(&ns->lock);
77 /* note to self: so, right after this point, the NS points to the root FS
78 * mount (we return the mnt, which gets assigned), the root mnt has a dentry
79 * for /, backed by an inode, with a SB prepped and in memory. */
87 dentry_kcache = kmem_cache_create("dentry", sizeof(struct dentry),
88 __alignof__(struct dentry), 0, 0, 0);
89 inode_kcache = kmem_cache_create("inode", sizeof(struct inode),
90 __alignof__(struct inode), 0, 0, 0);
91 file_kcache = kmem_cache_create("file", sizeof(struct file),
92 __alignof__(struct file), 0, 0, 0);
93 /* default NS never dies, +1 to exist */
94 kref_init(&default_ns.kref, fake_release, 1);
95 spinlock_init(&default_ns.lock);
96 default_ns.root = NULL;
97 TAILQ_INIT(&default_ns.vfsmounts);
99 /* build list of all FS's in the system. put yours here. if this is ever
100 * done on the fly, we'll need to lock. */
101 TAILQ_INSERT_TAIL(&file_systems, &kfs_fs_type, list);
103 TAILQ_INSERT_TAIL(&file_systems, &ext2_fs_type, list);
105 TAILQ_FOREACH(fs, &file_systems, list)
106 printk("Supports the %s Filesystem\n", fs->name);
108 /* mounting KFS at the root (/), pending root= parameters */
109 // TODO: linux creates a temp root_fs, then mounts the real root onto that
110 default_ns.root = __mount_fs(&kfs_fs_type, "RAM", NULL, 0, &default_ns);
112 printk("vfs_init() completed\n");
115 /* Builds / populates the qstr of a dentry based on its d_iname. If there is an
116 * l_name, (long), it will use that instead of the inline name. This will
117 * probably change a bit. */
118 void qstr_builder(struct dentry *dentry, char *l_name)
120 dentry->d_name.name = l_name ? l_name : dentry->d_iname;
121 // TODO: pending what we actually do in d_hash
122 //dentry->d_name.hash = dentry->d_op->d_hash(dentry, &dentry->d_name);
123 dentry->d_name.hash = 0xcafebabe;
124 dentry->d_name.len = strnlen(dentry->d_name.name, MAX_FILENAME_SZ);
127 /* Useful little helper - return the string ptr for a given file */
128 char *file_name(struct file *file)
130 return file->f_dentry->d_name.name;
133 /* Some issues with this, coupled closely to fs_lookup.
135 * Note the use of __dentry_free, instead of kref_put. In those cases, we don't
136 * want to treat it like a kref and we have the only reference to it, so it is
137 * okay to do this. It makes dentry_release() easier too. */
138 static struct dentry *do_lookup(struct dentry *parent, char *name)
140 struct dentry *result, *query;
141 query = get_dentry(parent->d_sb, parent, name);
143 warn("OOM in do_lookup(), probably wasn't expected\n");
146 result = dcache_get(parent->d_sb, query);
148 __dentry_free(query);
151 /* No result, check for negative */
152 if (query->d_flags & DENTRY_NEGATIVE) {
153 __dentry_free(query);
156 /* not in the dcache at all, need to consult the FS */
157 result = parent->d_inode->i_op->lookup(parent->d_inode, query, 0);
159 /* Note the USED flag will get turned off when this gets added to the
160 * LRU in dentry_release(). There's a slight race here that we'll panic
161 * on, but I want to catch it (in dcache_put()) for now. */
162 query->d_flags |= DENTRY_NEGATIVE;
163 dcache_put(parent->d_sb, query);
164 kref_put(&query->d_kref);
167 dcache_put(parent->d_sb, result);
168 /* This is because KFS doesn't return the same dentry, but ext2 does. this
169 * is ugly and needs to be fixed. (TODO) */
171 __dentry_free(query);
173 /* TODO: if the following are done by us, how do we know the i_ino?
174 * also need to handle inodes that are already read in! For now, we're
175 * going to have the FS handle it in it's lookup() method:
177 * - read in the inode
178 * - put in the inode cache */
182 /* Update ND such that it represents having followed dentry. IAW the nd
183 * refcnting rules, we need to decref any references that were in there before
184 * they get clobbered. */
185 static int next_link(struct dentry *dentry, struct nameidata *nd)
187 assert(nd->dentry && nd->mnt);
188 /* update the dentry */
189 kref_get(&dentry->d_kref, 1);
190 kref_put(&nd->dentry->d_kref);
192 /* update the mount, if we need to */
193 if (dentry->d_sb->s_mount != nd->mnt) {
194 kref_get(&dentry->d_sb->s_mount->mnt_kref, 1);
195 kref_put(&nd->mnt->mnt_kref);
196 nd->mnt = dentry->d_sb->s_mount;
201 /* Walk up one directory, being careful of mountpoints, namespaces, and the top
203 static int climb_up(struct nameidata *nd)
205 printd("CLIMB_UP, from %s\n", nd->dentry->d_name.name);
206 /* Top of the world, just return. Should also check for being at the top of
207 * the current process's namespace (TODO) */
208 if (!nd->dentry->d_parent || (nd->dentry->d_parent == nd->dentry))
210 /* Check if we are at the top of a mount, if so, we need to follow
211 * backwards, and then climb_up from that one. We might need to climb
212 * multiple times if we mount multiple FSs at the same spot (highly
213 * unlikely). This is completely untested. Might recurse instead. */
214 while (nd->mnt->mnt_root == nd->dentry) {
215 if (!nd->mnt->mnt_parent) {
216 warn("Might have expected a parent vfsmount (dentry had a parent)");
219 next_link(nd->mnt->mnt_mountpoint, nd);
221 /* Backwards walk (no mounts or any other issues now). */
222 next_link(nd->dentry->d_parent, nd);
223 printd("CLIMB_UP, to %s\n", nd->dentry->d_name.name);
227 /* nd->dentry might be on a mount point, so we need to move on to the child
229 static int follow_mount(struct nameidata *nd)
231 if (!nd->dentry->d_mount_point)
233 next_link(nd->dentry->d_mounted_fs->mnt_root, nd);
237 static int link_path_walk(char *path, struct nameidata *nd);
239 /* When nd->dentry is for a symlink, this will recurse and follow that symlink,
240 * so that nd contains the results of following the symlink (dentry and mnt).
241 * Returns when it isn't a symlink, 1 on following a link, and < 0 on error. */
242 static int follow_symlink(struct nameidata *nd)
246 if (!S_ISLNK(nd->dentry->d_inode->i_mode))
248 if (nd->depth > MAX_SYMLINK_DEPTH)
250 printd("Following symlink for dentry %p %s\n", nd->dentry,
251 nd->dentry->d_name.name);
253 symname = nd->dentry->d_inode->i_op->readlink(nd->dentry);
254 /* We need to pin in nd->dentry (the dentry of the symlink), since we need
255 * it's symname's storage to stay in memory throughout the upcoming
256 * link_path_walk(). The last_sym gets decreffed when we path_release() or
257 * follow another symlink. */
259 kref_put(&nd->last_sym->d_kref);
260 kref_get(&nd->dentry->d_kref, 1);
261 nd->last_sym = nd->dentry;
262 /* If this an absolute path in the symlink, we need to free the old path and
263 * start over, otherwise, we continue from the PARENT of nd (the symlink) */
264 if (symname[0] == '/') {
267 nd->dentry = default_ns.root->mnt_root;
269 nd->dentry = current->fs_env.root;
270 nd->mnt = nd->dentry->d_sb->s_mount;
271 kref_get(&nd->mnt->mnt_kref, 1);
272 kref_get(&nd->dentry->d_kref, 1);
276 /* either way, keep on walking in the free world! */
277 retval = link_path_walk(symname, nd);
278 return (retval == 0 ? 1 : retval);
281 /* Little helper, to make it easier to break out of the nested loops. Will also
282 * '\0' out the first slash if it's slashes all the way down. Or turtles. */
283 static bool packed_trailing_slashes(char *first_slash)
285 for (char *i = first_slash; *i == '/'; i++) {
286 if (*(i + 1) == '\0') {
294 /* Simple helper to set nd to track it's last name to be Name. Also be careful
295 * with the storage of name. Don't use and nd's name past the lifetime of the
296 * string used in the path_lookup()/link_path_walk/whatever. Consider replacing
297 * parts of this with a qstr builder. Note this uses the dentry's d_op, which
298 * might not be the dentry we care about. */
299 static void stash_nd_name(struct nameidata *nd, char *name)
301 nd->last.name = name;
302 nd->last.len = strlen(name);
303 nd->last.hash = nd->dentry->d_op->d_hash(nd->dentry, &nd->last);
306 /* Resolves the links in a basic path walk. 0 for success, -EWHATEVER
307 * otherwise. The final lookup is returned via nd. */
308 static int link_path_walk(char *path, struct nameidata *nd)
310 struct dentry *link_dentry;
311 struct inode *link_inode, *nd_inode;
316 /* Prevent crazy recursion */
317 if (nd->depth > MAX_SYMLINK_DEPTH)
319 /* skip all leading /'s */
322 /* if there's nothing left (null terminated), we're done. This should only
323 * happen for "/", which if we wanted a PARENT, should fail (there is no
326 if (nd->flags & LOOKUP_PARENT) {
330 /* o/w, we're good */
333 /* iterate through each intermediate link of the path. in general, nd
334 * tracks where we are in the path, as far as dentries go. once we have the
335 * next dentry, we try to update nd based on that dentry. link is the part
336 * of the path string that we are looking up */
338 nd_inode = nd->dentry->d_inode;
339 if ((error = check_perms(nd_inode, nd->intent)))
341 /* find the next link, break out if it is the end */
342 next_slash = strchr(link, '/');
346 if (packed_trailing_slashes(next_slash)) {
347 nd->flags |= LOOKUP_DIRECTORY;
351 /* skip over any interim ./ */
352 if (!strncmp("./", link, 2))
354 /* Check for "../", walk up */
355 if (!strncmp("../", link, 3)) {
360 link_dentry = do_lookup(nd->dentry, link);
364 /* make link_dentry the current step/answer */
365 next_link(link_dentry, nd);
366 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt dentry */
367 /* we could be on a mountpoint or a symlink - need to follow them */
369 if ((error = follow_symlink(nd)) < 0)
371 /* Turn off a possible DIRECTORY lookup, which could have been set
372 * during the follow_symlink (a symlink could have had a directory at
373 * the end), though it was in the middle of the real path. */
374 nd->flags &= ~LOOKUP_DIRECTORY;
375 if (!S_ISDIR(nd->dentry->d_inode->i_mode))
378 /* move through the path string to the next entry */
379 link = next_slash + 1;
380 /* advance past any other interim slashes. we know we won't hit the end
381 * due to the for loop check above */
385 /* Now, we're on the last link of the path. We need to deal with with . and
386 * .. . This might be weird with PARENT lookups - not sure what semantics
387 * we want exactly. This will give the parent of whatever the PATH was
388 * supposed to look like. Note that ND currently points to the parent of
389 * the last item (link). */
390 if (!strcmp(".", link)) {
391 if (nd->flags & LOOKUP_PARENT) {
392 assert(nd->dentry->d_name.name);
393 stash_nd_name(nd, nd->dentry->d_name.name);
398 if (!strcmp("..", link)) {
400 if (nd->flags & LOOKUP_PARENT) {
401 assert(nd->dentry->d_name.name);
402 stash_nd_name(nd, nd->dentry->d_name.name);
407 /* need to attempt to look it up, in case it's a symlink */
408 link_dentry = do_lookup(nd->dentry, link);
410 /* if there's no dentry, we are okay if we are looking for the parent */
411 if (nd->flags & LOOKUP_PARENT) {
412 assert(strcmp(link, ""));
413 stash_nd_name(nd, link);
419 next_link(link_dentry, nd);
420 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt'd dentry */
421 /* at this point, nd is on the final link, but it might be a symlink */
422 if (nd->flags & LOOKUP_FOLLOW) {
423 error = follow_symlink(nd);
426 /* if we actually followed a symlink, then nd is set and we're done */
430 /* One way or another, nd is on the last element of the path, symlinks and
431 * all. Now we need to climb up to set nd back on the parent, if that's
433 if (nd->flags & LOOKUP_PARENT) {
434 assert(nd->dentry->d_name.name);
435 stash_nd_name(nd, link_dentry->d_name.name);
439 /* now, we have the dentry set, and don't want the parent, but might be on a
440 * mountpoint still. FYI: this hasn't been thought through completely. */
442 /* If we wanted a directory, but didn't get one, error out */
443 if ((nd->flags & LOOKUP_DIRECTORY) && !S_ISDIR(nd->dentry->d_inode->i_mode))
448 /* Given path, return the inode for the final dentry. The ND should be
449 * initialized for the first call - specifically, we need the intent.
450 * LOOKUP_PARENT and friends go in the flags var, which is not the intent.
452 * If path_lookup wants a PARENT, but hits the top of the FS (root or
453 * otherwise), we want it to error out. It's still unclear how we want to
454 * handle processes with roots that aren't root, but at the very least, we don't
455 * want to think we have the parent of /, but have / itself. Due to the way
456 * link_path_walk works, if that happened, we probably don't have a
457 * nd->last.name. This needs more thought (TODO).
459 * Need to be careful too. While the path has been copied-in to the kernel,
460 * it's still user input. */
461 int path_lookup(char *path, int flags, struct nameidata *nd)
464 printd("Path lookup for %s\n", path);
465 /* we allow absolute lookups with no process context */
466 if (path[0] == '/') { /* absolute lookup */
468 nd->dentry = default_ns.root->mnt_root;
470 nd->dentry = current->fs_env.root;
471 } else { /* relative lookup */
473 /* Don't need to lock on the fs_env since we're reading one item */
474 nd->dentry = current->fs_env.pwd;
476 nd->mnt = nd->dentry->d_sb->s_mount;
477 /* Whenever references get put in the nd, incref them. Whenever they are
478 * removed, decref them. */
479 kref_get(&nd->mnt->mnt_kref, 1);
480 kref_get(&nd->dentry->d_kref, 1);
482 nd->depth = 0; /* used in symlink following */
483 retval = link_path_walk(path, nd);
484 /* make sure our PARENT lookup worked */
485 if (!retval && (flags & LOOKUP_PARENT))
486 assert(nd->last.name);
490 /* Call this after any use of path_lookup when you are done with its results,
491 * regardless of whether it succeeded or not. It will free any references */
492 void path_release(struct nameidata *nd)
494 kref_put(&nd->dentry->d_kref);
495 kref_put(&nd->mnt->mnt_kref);
496 /* Free the last symlink dentry used, if there was one */
498 kref_put(&nd->last_sym->d_kref);
499 nd->last_sym = 0; /* catch reuse bugs */
503 /* External version of mount, only call this after having a / mount */
504 int mount_fs(struct fs_type *fs, char *dev_name, char *path, int flags)
506 struct nameidata nd_r = {0}, *nd = &nd_r;
508 retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
511 /* taking the namespace of the vfsmount of path */
512 if (!__mount_fs(fs, dev_name, nd->dentry, flags, nd->mnt->mnt_namespace))
519 /* Superblock functions */
521 /* Dentry "hash" function for the hash table to use. Since we already have the
522 * hash in the qstr, we don't need to rehash. Also, note we'll be using the
523 * dentry in question as both the key and the value. */
524 static size_t __dcache_hash(void *k)
526 return (size_t)((struct dentry*)k)->d_name.hash;
529 /* Dentry cache hashtable equality function. This means we need to pass in some
530 * minimal dentry when doing a lookup. */
531 static ssize_t __dcache_eq(void *k1, void *k2)
533 if (((struct dentry*)k1)->d_parent != ((struct dentry*)k2)->d_parent)
535 /* TODO: use the FS-specific string comparison */
536 return !strcmp(((struct dentry*)k1)->d_name.name,
537 ((struct dentry*)k2)->d_name.name);
540 /* Helper to alloc and initialize a generic superblock. This handles all the
541 * VFS related things, like lists. Each FS will need to handle its own things
542 * in it's *_get_sb(), usually involving reading off the disc. */
543 struct super_block *get_sb(void)
545 struct super_block *sb = kmalloc(sizeof(struct super_block), 0);
547 spinlock_init(&sb->s_lock);
548 kref_init(&sb->s_kref, fake_release, 1); /* for the ref passed out */
549 TAILQ_INIT(&sb->s_inodes);
550 TAILQ_INIT(&sb->s_dirty_i);
551 TAILQ_INIT(&sb->s_io_wb);
552 TAILQ_INIT(&sb->s_lru_d);
553 TAILQ_INIT(&sb->s_files);
554 sb->s_dcache = create_hashtable(100, __dcache_hash, __dcache_eq);
555 sb->s_icache = create_hashtable(100, __generic_hash, __generic_eq);
556 spinlock_init(&sb->s_lru_lock);
557 spinlock_init(&sb->s_dcache_lock);
558 spinlock_init(&sb->s_icache_lock);
559 sb->s_fs_info = 0; // can override somewhere else
563 /* Final stages of initializing a super block, including creating and linking
564 * the root dentry, root inode, vmnt, and sb. The d_op and root_ino are
565 * FS-specific, but otherwise it's FS-independent, tricky, and not worth having
566 * around multiple times.
568 * Not the world's best interface, so it's subject to change, esp since we're
569 * passing (now 3) FS-specific things. */
570 void init_sb(struct super_block *sb, struct vfsmount *vmnt,
571 struct dentry_operations *d_op, unsigned long root_ino,
574 /* Build and init the first dentry / inode. The dentry ref is stored later
575 * by vfsmount's mnt_root. The parent is dealt with later. */
576 struct dentry *d_root = get_dentry(sb, 0, "/"); /* probably right */
579 panic("OOM! init_sb() can't fail yet!");
580 /* a lot of here on down is normally done in lookup() or create, since
581 * get_dentry isn't a fully usable dentry. The two FS-specific settings are
582 * normally inherited from a parent within the same FS in get_dentry, but we
585 d_root->d_fs_info = d_fs_info;
586 struct inode *inode = get_inode(d_root);
588 panic("This FS sucks!");
589 inode->i_ino = root_ino;
590 /* TODO: add the inode to the appropriate list (off i_list) */
591 /* TODO: do we need to read in the inode? can we do this on demand? */
592 /* if this FS is already mounted, we'll need to do something different. */
593 sb->s_op->read_inode(inode);
594 icache_put(sb, inode);
595 /* Link the dentry and SB to the VFS mount */
596 vmnt->mnt_root = d_root; /* ref comes from get_dentry */
598 /* If there is no mount point, there is no parent. This is true only for
600 if (vmnt->mnt_mountpoint) {
601 kref_get(&vmnt->mnt_mountpoint->d_kref, 1); /* held by d_root */
602 d_root->d_parent = vmnt->mnt_mountpoint; /* dentry of the root */
604 d_root->d_parent = d_root; /* set root as its own parent */
606 /* insert the dentry into the dentry cache. when's the earliest we can?
607 * when's the earliest we should? what about concurrent accesses to the
608 * same dentry? should be locking the dentry... */
609 dcache_put(sb, d_root);
610 kref_put(&inode->i_kref); /* give up the ref from get_inode() */
613 /* Dentry Functions */
615 /* Helper to alloc and initialize a generic dentry. The following needs to be
616 * set still: d_op (if no parent), d_fs_info (opt), d_inode, connect the inode
617 * to the dentry (and up the d_kref again), maybe dcache_put(). The inode
618 * stitching is done in get_inode() or lookup (depending on the FS).
619 * The setting of the d_op might be problematic when dealing with mounts. Just
622 * If the name is longer than the inline name, it will kmalloc a buffer, so
623 * don't worry about the storage for *name after calling this. */
624 struct dentry *get_dentry(struct super_block *sb, struct dentry *parent,
628 size_t name_len = strnlen(name, MAX_FILENAME_SZ); /* not including \0! */
629 struct dentry *dentry = kmem_cache_alloc(dentry_kcache, 0);
636 //memset(dentry, 0, sizeof(struct dentry));
637 kref_init(&dentry->d_kref, dentry_release, 1); /* this ref is returned */
638 spinlock_init(&dentry->d_lock);
639 TAILQ_INIT(&dentry->d_subdirs);
641 kref_get(&sb->s_kref, 1);
642 dentry->d_sb = sb; /* storing a ref here... */
643 dentry->d_mount_point = FALSE;
644 dentry->d_mounted_fs = 0;
645 if (parent) { /* no parent for rootfs mount */
646 kref_get(&parent->d_kref, 1);
647 dentry->d_op = parent->d_op; /* d_op set in init_sb for parentless */
649 dentry->d_parent = parent;
650 dentry->d_flags = DENTRY_USED;
651 dentry->d_fs_info = 0;
652 if (name_len < DNAME_INLINE_LEN) {
653 strncpy(dentry->d_iname, name, name_len);
654 dentry->d_iname[name_len] = '\0';
655 qstr_builder(dentry, 0);
657 l_name = kmalloc(name_len + 1, 0);
659 strncpy(l_name, name, name_len);
660 l_name[name_len] = '\0';
661 qstr_builder(dentry, l_name);
663 /* Catch bugs by aggressively zeroing this (o/w we use old stuff) */
668 /* Called when the dentry is unreferenced (after kref == 0). This works closely
669 * with the resurrection in dcache_get().
671 * The dentry is still in the dcache, but needs to be un-USED and added to the
672 * LRU dentry list. Even dentries that were used in a failed lookup need to be
673 * cached - they ought to be the negative dentries. Note that all dentries have
674 * parents, even negative ones (it is needed to find it in the dcache). */
675 void dentry_release(struct kref *kref)
677 struct dentry *dentry = container_of(kref, struct dentry, d_kref);
679 printd("'Releasing' dentry %p: %s\n", dentry, dentry->d_name.name);
680 /* DYING dentries (recently unlinked / rmdir'd) just get freed */
681 if (dentry->d_flags & DENTRY_DYING) {
682 __dentry_free(dentry);
685 /* This lock ensures the USED state and the TAILQ membership is in sync.
686 * Also used to check the refcnt, though that might not be necessary. */
687 spin_lock(&dentry->d_lock);
688 /* While locked, we need to double check the kref, in case someone already
689 * reup'd it. Re-up? you're crazy! Reee-up, you're outta yo mind! */
690 if (!kref_refcnt(&dentry->d_kref)) {
691 /* Note this is where negative dentries get set UNUSED */
692 if (dentry->d_flags & DENTRY_USED) {
693 dentry->d_flags &= ~DENTRY_USED;
694 spin_lock(&dentry->d_sb->s_lru_lock);
695 TAILQ_INSERT_TAIL(&dentry->d_sb->s_lru_d, dentry, d_lru);
696 spin_unlock(&dentry->d_sb->s_lru_lock);
698 /* and make sure it wasn't USED, then UNUSED again */
699 /* TODO: think about issues with this */
700 warn("This should be rare. Tell brho this happened.");
703 spin_unlock(&dentry->d_lock);
706 /* Called when we really dealloc and get rid of a dentry (like when it is
707 * removed from the dcache, either for memory or correctness reasons)
709 * This has to handle two types of dentries: full ones (ones that had been used)
710 * and ones that had been just for lookups - hence the check for d_inode.
712 * Note that dentries pin and kref their inodes. When all the dentries are
713 * gone, we want the inode to be released via kref. The inode has internal /
714 * weak references to the dentry, which are not refcounted. */
715 void __dentry_free(struct dentry *dentry)
718 printk("Freeing dentry %p: %s\n", dentry, dentry->d_name.name);
719 assert(dentry->d_op); /* catch bugs. a while back, some lacked d_op */
720 dentry->d_op->d_release(dentry);
721 /* TODO: check/test the boundaries on this. */
722 if (dentry->d_name.len > DNAME_INLINE_LEN)
723 kfree((void*)dentry->d_name.name);
724 kref_put(&dentry->d_sb->s_kref);
725 if (dentry->d_parent)
726 kref_put(&dentry->d_parent->d_kref);
727 if (dentry->d_mounted_fs)
728 kref_put(&dentry->d_mounted_fs->mnt_kref);
729 if (dentry->d_inode) {
730 TAILQ_REMOVE(&dentry->d_inode->i_dentry, dentry, d_alias);
731 kref_put(&dentry->d_inode->i_kref); /* dentries kref inodes */
733 kmem_cache_free(dentry_kcache, dentry);
736 /* Looks up the dentry for the given path, returning a refcnt'd dentry (or 0).
737 * Permissions are applied for the current user, which is quite a broken system
738 * at the moment. Flags are lookup flags. */
739 struct dentry *lookup_dentry(char *path, int flags)
741 struct dentry *dentry;
742 struct nameidata nd_r = {0}, *nd = &nd_r;
745 error = path_lookup(path, flags, nd);
752 kref_get(&dentry->d_kref, 1);
757 /* Get a dentry from the dcache. At a minimum, we need the name hash and parent
758 * in what_i_want, though most uses will probably be from a get_dentry() call.
759 * We pass in the SB in the off chance that we don't want to use a get'd dentry.
761 * The unusual variable name (instead of just "key" or something) is named after
762 * ex-SPC Castro's porn folder. Caller deals with the memory for what_i_want.
764 * If the dentry is negative, we don't return the actual result - instead, we
765 * set the negative flag in 'what i want'. The reason is we don't want to
766 * kref_get() and then immediately put (causing dentry_release()). This also
767 * means that dentry_release() should never get someone who wasn't USED (barring
768 * the race, which it handles). And we don't need to ever have a dentry set as
769 * USED and NEGATIVE (which is always wrong, but would be needed for a cleaner
772 * This is where we do the "kref resurrection" - we are returning a kref'd
773 * object, even if it wasn't kref'd before. This means the dcache does NOT hold
774 * krefs (it is a weak/internal ref), but it is a source of kref generation. We
775 * sync up with the possible freeing of the dentry by locking the table. See
776 * Doc/kref for more info. */
777 struct dentry *dcache_get(struct super_block *sb, struct dentry *what_i_want)
779 struct dentry *found;
780 /* This lock protects the hash, as well as ensures the returned object
781 * doesn't get deleted/freed out from under us */
782 spin_lock(&sb->s_dcache_lock);
783 found = hashtable_search(sb->s_dcache, what_i_want);
785 if (found->d_flags & DENTRY_NEGATIVE) {
786 what_i_want->d_flags |= DENTRY_NEGATIVE;
787 spin_unlock(&sb->s_dcache_lock);
790 spin_lock(&found->d_lock);
791 __kref_get(&found->d_kref, 1); /* prob could be done outside the lock*/
792 /* If we're here (after kreffing) and it is not USED, we are the one who
793 * should resurrect */
794 if (!(found->d_flags & DENTRY_USED)) {
795 found->d_flags |= DENTRY_USED;
796 spin_lock(&sb->s_lru_lock);
797 TAILQ_REMOVE(&sb->s_lru_d, found, d_lru);
798 spin_unlock(&sb->s_lru_lock);
800 spin_unlock(&found->d_lock);
802 spin_unlock(&sb->s_dcache_lock);
806 /* Adds a dentry to the dcache. Note the *dentry is both the key and the value.
807 * If the value was already in there (which can happen iff it was negative), for
808 * now we'll remove it and put the new one in there. */
809 void dcache_put(struct super_block *sb, struct dentry *key_val)
813 spin_lock(&sb->s_dcache_lock);
814 old = hashtable_remove(sb->s_dcache, key_val);
816 assert(old->d_flags & DENTRY_NEGATIVE);
817 /* This is possible, but rare for now (about to be put on the LRU) */
818 assert(!(old->d_flags & DENTRY_USED));
819 assert(!kref_refcnt(&old->d_kref));
820 spin_lock(&sb->s_lru_lock);
821 TAILQ_REMOVE(&sb->s_lru_d, old, d_lru);
822 spin_unlock(&sb->s_lru_lock);
825 /* this returns 0 on failure (TODO: Fix this ghetto shit) */
826 retval = hashtable_insert(sb->s_dcache, key_val, key_val);
828 spin_unlock(&sb->s_dcache_lock);
831 /* Will remove and return the dentry. Caller deallocs the key, but the retval
832 * won't have a reference. * Returns 0 if it wasn't found. Callers can't
833 * assume much - they should not use the reference they *get back*, (if they
834 * already had one for key, they can use that). There may be other users out
836 struct dentry *dcache_remove(struct super_block *sb, struct dentry *key)
838 struct dentry *retval;
839 spin_lock(&sb->s_dcache_lock);
840 retval = hashtable_remove(sb->s_dcache, key);
841 spin_unlock(&sb->s_dcache_lock);
845 /* This will clean out the LRU list, which are the unused dentries of the dentry
846 * cache. This will optionally only free the negative ones. Note that we grab
847 * the hash lock for the time we traverse the LRU list - this prevents someone
848 * from getting a kref from the dcache, which could cause us trouble (we rip
849 * someone off the list, who isn't unused, and they try to rip them off the
851 void dcache_prune(struct super_block *sb, bool negative_only)
853 struct dentry *d_i, *temp;
854 struct dentry_tailq victims = TAILQ_HEAD_INITIALIZER(victims);
856 spin_lock(&sb->s_dcache_lock);
857 spin_lock(&sb->s_lru_lock);
858 TAILQ_FOREACH_SAFE(d_i, &sb->s_lru_d, d_lru, temp) {
859 if (!(d_i->d_flags & DENTRY_USED)) {
860 if (negative_only && !(d_i->d_flags & DENTRY_NEGATIVE))
862 /* another place where we'd be better off with tools, not sol'ns */
863 hashtable_remove(sb->s_dcache, d_i);
864 TAILQ_REMOVE(&sb->s_lru_d, d_i, d_lru);
865 TAILQ_INSERT_HEAD(&victims, d_i, d_lru);
868 spin_unlock(&sb->s_lru_lock);
869 spin_unlock(&sb->s_dcache_lock);
870 /* Now do the actual freeing, outside of the hash/LRU list locks. This is
871 * necessary since __dentry_free() will decref its parent, which may get
872 * released and try to add itself to the LRU. */
873 TAILQ_FOREACH_SAFE(d_i, &victims, d_lru, temp) {
874 TAILQ_REMOVE(&victims, d_i, d_lru);
875 assert(!kref_refcnt(&d_i->d_kref));
878 /* It is possible at this point that there are new items on the LRU. We
879 * could loop back until that list is empty, if we care about this. */
882 /* Inode Functions */
884 /* Creates and initializes a new inode. Generic fields are filled in.
885 * FS-specific fields are filled in by the callout. Specific fields are filled
886 * in in read_inode() based on what's on the disk for a given i_no, or when the
887 * inode is created (for new objects).
889 * i_no is set by the caller. Note that this means this inode can be for an
890 * inode that is already on disk, or it can be used when creating. */
891 struct inode *get_inode(struct dentry *dentry)
893 struct super_block *sb = dentry->d_sb;
894 /* FS allocs and sets the following: i_op, i_fop, i_pm.pm_op, and any FS
896 struct inode *inode = sb->s_op->alloc_inode(sb);
901 TAILQ_INSERT_HEAD(&sb->s_inodes, inode, i_sb_list); /* weak inode ref */
902 TAILQ_INIT(&inode->i_dentry);
903 TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias); /* weak dentry ref*/
904 /* one for the dentry->d_inode, one passed out */
905 kref_init(&inode->i_kref, inode_release, 2);
906 dentry->d_inode = inode;
907 inode->i_ino = 0; /* set by caller later */
908 inode->i_blksize = sb->s_blocksize;
909 spinlock_init(&inode->i_lock);
910 kref_get(&sb->s_kref, 1); /* could allow the dentry to pin it */
912 inode->i_rdev = 0; /* this has no real meaning yet */
913 inode->i_bdev = sb->s_bdev; /* storing an uncounted ref */
914 inode->i_state = 0; /* need real states, like I_NEW */
915 inode->dirtied_when = 0;
917 atomic_set(&inode->i_writecount, 0);
918 /* Set up the page_map structures. Default is to use the embedded one.
919 * Might push some of this back into specific FSs. For now, the FS tells us
920 * what pm_op they want via i_pm.pm_op, which we set again in pm_init() */
921 inode->i_mapping = &inode->i_pm;
922 pm_init(inode->i_mapping, inode->i_pm.pm_op, inode);
926 /* Helper: loads/ reads in the inode numbered ino and attaches it to dentry */
927 void load_inode(struct dentry *dentry, unsigned long ino)
931 /* look it up in the inode cache first */
932 inode = icache_get(dentry->d_sb, ino);
934 /* connect the dentry to its inode */
935 TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias);
936 dentry->d_inode = inode; /* storing the ref we got from icache_get */
939 /* otherwise, we need to do it manually */
940 inode = get_inode(dentry);
942 dentry->d_sb->s_op->read_inode(inode);
943 /* TODO: race here, two creators could miss in the cache, and then get here.
944 * need a way to sync across a blocking call. needs to be either at this
945 * point in the code or per the ino (dentries could be different) */
946 icache_put(dentry->d_sb, inode);
947 kref_put(&inode->i_kref);
950 /* Helper op, used when creating regular files, directories, symlinks, etc.
951 * Note we make a distinction between the mode and the file type (for now).
952 * After calling this, call the FS specific version (create or mkdir), which
953 * will set the i_ino, the filetype, and do any other FS-specific stuff. Also
954 * note that a lot of inode stuff was initialized in get_inode/alloc_inode. The
955 * stuff here is pertinent to the specific creator (user), mode, and time. Also
956 * note we don't pass this an nd, like Linux does... */
957 static struct inode *create_inode(struct dentry *dentry, int mode)
959 /* note it is the i_ino that uniquely identifies a file in the specific
960 * filesystem. there's a diff between creating an inode (even for an in-use
961 * ino) and then filling it in, and vs creating a brand new one.
962 * get_inode() sets it to 0, and it should be filled in later in an
963 * FS-specific manner. */
964 struct inode *inode = get_inode(dentry);
967 inode->i_mode = mode & S_PMASK; /* note that after this, we have no type */
971 inode->i_atime.tv_sec = 0; /* TODO: now! */
972 inode->i_ctime.tv_sec = 0;
973 inode->i_mtime.tv_sec = 0;
974 inode->i_atime.tv_nsec = 0; /* are these supposed to be the extra ns? */
975 inode->i_ctime.tv_nsec = 0;
976 inode->i_mtime.tv_nsec = 0;
977 inode->i_bdev = inode->i_sb->s_bdev;
978 /* when we have notions of users, do something here: */
984 /* Create a new disk inode in dir associated with dentry, with the given mode.
985 * called when creating a regular file. dir is the directory/parent. dentry is
986 * the dentry of the inode we are creating. Note the lack of the nd... */
987 int create_file(struct inode *dir, struct dentry *dentry, int mode)
989 struct inode *new_file = create_inode(dentry, mode);
992 dir->i_op->create(dir, dentry, mode, 0);
993 icache_put(new_file->i_sb, new_file);
994 kref_put(&new_file->i_kref);
998 /* Creates a new inode for a directory associated with dentry in dir with the
1000 int create_dir(struct inode *dir, struct dentry *dentry, int mode)
1002 struct inode *new_dir = create_inode(dentry, mode);
1005 dir->i_op->mkdir(dir, dentry, mode);
1006 dir->i_nlink++; /* Directories get a hardlink for every child dir */
1007 /* Make sure my parent tracks me. This is okay, since no directory (dir)
1008 * can have more than one dentry */
1009 struct dentry *parent = TAILQ_FIRST(&dir->i_dentry);
1010 assert(parent && parent == TAILQ_LAST(&dir->i_dentry, dentry_tailq));
1011 /* parent dentry tracks dentry as a subdir, weak reference */
1012 TAILQ_INSERT_TAIL(&parent->d_subdirs, dentry, d_subdirs_link);
1013 icache_put(new_dir->i_sb, new_dir);
1014 kref_put(&new_dir->i_kref);
1018 /* Creates a new inode for a symlink associated with dentry in dir, containing
1019 * the symlink symname */
1020 int create_symlink(struct inode *dir, struct dentry *dentry,
1021 const char *symname, int mode)
1023 struct inode *new_sym = create_inode(dentry, mode);
1026 dir->i_op->symlink(dir, dentry, symname);
1027 icache_put(new_sym->i_sb, new_sym);
1028 kref_put(&new_sym->i_kref);
1032 /* Returns 0 if the given mode is acceptable for the inode, and an appropriate
1033 * error code if not. Needs to be writen, based on some sensible rules, and
1034 * will also probably use 'current' */
1035 int check_perms(struct inode *inode, int access_mode)
1037 return 0; /* anything goes! */
1040 /* Called after all external refs are gone to clean up the inode. Once this is
1041 * called, all dentries pointing here are already done (one of them triggered
1042 * this via kref_put(). */
1043 void inode_release(struct kref *kref)
1045 struct inode *inode = container_of(kref, struct inode, i_kref);
1046 TAILQ_REMOVE(&inode->i_sb->s_inodes, inode, i_sb_list);
1047 icache_remove(inode->i_sb, inode->i_ino);
1048 /* Might need to write back or delete the file/inode */
1049 if (inode->i_nlink) {
1050 if (inode->i_state & I_STATE_DIRTY)
1051 inode->i_sb->s_op->write_inode(inode, TRUE);
1053 inode->i_sb->s_op->delete_inode(inode);
1055 if (S_ISFIFO(inode->i_mode)) {
1056 page_decref(kva2page(inode->i_pipe->p_buf));
1057 kfree(inode->i_pipe);
1060 // kref_put(inode->i_bdev->kref); /* assuming it's a bdev, could be a pipe*/
1061 /* Either way, we dealloc the in-memory version */
1062 inode->i_sb->s_op->dealloc_inode(inode); /* FS-specific clean-up */
1063 kref_put(&inode->i_sb->s_kref);
1064 /* TODO: clean this up */
1065 assert(inode->i_mapping == &inode->i_pm);
1066 kmem_cache_free(inode_kcache, inode);
1069 /* Fills in kstat with the stat information for the inode */
1070 void stat_inode(struct inode *inode, struct kstat *kstat)
1072 kstat->st_dev = inode->i_sb->s_dev;
1073 kstat->st_ino = inode->i_ino;
1074 kstat->st_mode = inode->i_mode;
1075 kstat->st_nlink = inode->i_nlink;
1076 kstat->st_uid = inode->i_uid;
1077 kstat->st_gid = inode->i_gid;
1078 kstat->st_rdev = inode->i_rdev;
1079 kstat->st_size = inode->i_size;
1080 kstat->st_blksize = inode->i_blksize;
1081 kstat->st_blocks = inode->i_blocks;
1082 kstat->st_atime = inode->i_atime;
1083 kstat->st_mtime = inode->i_mtime;
1084 kstat->st_ctime = inode->i_ctime;
1087 /* Inode Cache management. In general, search on the ino, get a refcnt'd value
1088 * back. Remove does not give you a reference back - it should only be called
1089 * in inode_release(). */
1090 struct inode *icache_get(struct super_block *sb, unsigned long ino)
1092 /* This is the same style as in pid2proc, it's the "safely create a strong
1093 * reference from a weak one, so long as other strong ones exist" pattern */
1094 spin_lock(&sb->s_icache_lock);
1095 struct inode *inode = hashtable_search(sb->s_icache, (void*)ino);
1097 if (!kref_get_not_zero(&inode->i_kref, 1))
1099 spin_unlock(&sb->s_icache_lock);
1103 void icache_put(struct super_block *sb, struct inode *inode)
1105 spin_lock(&sb->s_icache_lock);
1106 /* there's a race in load_ino() that could trigger this */
1107 assert(!hashtable_search(sb->s_icache, (void*)inode->i_ino));
1108 hashtable_insert(sb->s_icache, (void*)inode->i_ino, inode);
1109 spin_unlock(&sb->s_icache_lock);
1112 struct inode *icache_remove(struct super_block *sb, unsigned long ino)
1114 struct inode *inode;
1115 /* Presumably these hashtable removals could be easier since callers
1116 * actually know who they are (same with the pid2proc hash) */
1117 spin_lock(&sb->s_icache_lock);
1118 inode = hashtable_remove(sb->s_icache, (void*)ino);
1119 spin_unlock(&sb->s_icache_lock);
1120 assert(inode && !kref_refcnt(&inode->i_kref));
1124 /* File functions */
1126 /* Read count bytes from the file into buf, starting at *offset, which is
1127 * increased accordingly, returning the number of bytes transfered. Most
1128 * filesystems will use this function for their f_op->read.
1129 * Note, this uses the page cache. */
1130 ssize_t generic_file_read(struct file *file, char *buf, size_t count,
1136 unsigned long first_idx, last_idx;
1140 /* Consider pushing some error checking higher in the VFS */
1143 if (*offset == file->f_dentry->d_inode->i_size)
1145 /* Make sure we don't go past the end of the file */
1146 if (*offset + count > file->f_dentry->d_inode->i_size) {
1147 count = file->f_dentry->d_inode->i_size - *offset;
1149 page_off = *offset & (PGSIZE - 1);
1150 first_idx = *offset >> PGSHIFT;
1151 last_idx = (*offset + count) >> PGSHIFT;
1152 buf_end = buf + count;
1153 /* For each file page, make sure it's in the page cache, then copy it out.
1154 * TODO: will probably need to consider concurrently truncated files here.*/
1155 for (int i = first_idx; i <= last_idx; i++) {
1156 error = pm_load_page(file->f_mapping, i, &page);
1157 assert(!error); /* TODO: handle ENOMEM and friends */
1158 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
1159 /* TODO: (UMEM) think about this. if it's a user buffer, we're relying
1160 * on current to detect whose it is (which should work for async calls).
1161 * Also, need to propagate errors properly... Probably should do a
1162 * user_mem_check, then free, and also to make a distinction between
1163 * when the kernel wants a read/write (TODO: KFOP) */
1165 memcpy_to_user(current, buf, page2kva(page) + page_off, copy_amt);
1167 memcpy(buf, page2kva(page) + page_off, copy_amt);
1171 page_decref(page); /* it's still in the cache, we just don't need it */
1173 assert(buf == buf_end);
1178 /* Write count bytes from buf to the file, starting at *offset, which is
1179 * increased accordingly, returning the number of bytes transfered. Most
1180 * filesystems will use this function for their f_op->write. Note, this uses
1183 * Changes don't get flushed to disc til there is an fsync, page cache eviction,
1184 * or other means of trying to writeback the pages. */
1185 ssize_t generic_file_write(struct file *file, const char *buf, size_t count,
1191 unsigned long first_idx, last_idx;
1193 const char *buf_end;
1195 /* Consider pushing some error checking higher in the VFS */
1198 /* Extend the file. Should put more checks in here, and maybe do this per
1199 * page in the for loop below. */
1200 if (*offset + count > file->f_dentry->d_inode->i_size)
1201 file->f_dentry->d_inode->i_size = *offset + count;
1202 page_off = *offset & (PGSIZE - 1);
1203 first_idx = *offset >> PGSHIFT;
1204 last_idx = (*offset + count) >> PGSHIFT;
1205 buf_end = buf + count;
1206 /* For each file page, make sure it's in the page cache, then write it.*/
1207 for (int i = first_idx; i <= last_idx; i++) {
1208 error = pm_load_page(file->f_mapping, i, &page);
1209 assert(!error); /* TODO: handle ENOMEM and friends */
1210 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
1211 /* TODO: (UMEM) (KFOP) think about this. if it's a user buffer, we're
1212 * relying on current to detect whose it is (which should work for async
1215 memcpy_from_user(current, page2kva(page) + page_off, buf, copy_amt);
1217 memcpy(page2kva(page) + page_off, buf, copy_amt);
1221 page_decref(page); /* it's still in the cache, we just don't need it */
1223 assert(buf == buf_end);
1228 /* Directories usually use this for their read method, which is the way glibc
1229 * currently expects us to do a readdir (short of doing linux's getdents). Will
1230 * probably need work, based on whatever real programs want. */
1231 ssize_t generic_dir_read(struct file *file, char *u_buf, size_t count,
1234 struct kdirent dir_r = {0}, *dirent = &dir_r;
1236 size_t amt_copied = 0;
1237 char *buf_end = u_buf + count;
1239 if (!S_ISDIR(file->f_dentry->d_inode->i_mode)) {
1245 /* start readdir from where it left off: */
1246 dirent->d_off = *offset;
1248 u_buf + sizeof(struct kdirent) <= buf_end;
1249 u_buf += sizeof(struct kdirent)) {
1250 /* TODO: UMEM/KFOP (pin the u_buf in the syscall, ditch the local copy,
1251 * get rid of this memcpy and reliance on current, etc). Might be
1252 * tricky with the dirent->d_off and trust issues */
1253 retval = file->f_op->readdir(file, dirent);
1258 /* Slight info exposure: could be extra crap after the name in the
1259 * dirent (like the name of a deleted file) */
1261 memcpy_to_user(current, u_buf, dirent, sizeof(struct dirent));
1263 memcpy(u_buf, dirent, sizeof(struct dirent));
1265 amt_copied += sizeof(struct dirent);
1266 /* 0 signals end of directory */
1270 /* Next time read is called, we pick up where we left off */
1271 *offset = dirent->d_off; /* UMEM */
1272 /* important to tell them how much they got. they often keep going til they
1273 * get 0 back (in the case of ls). it's also how much has been read, but it
1274 * isn't how much the f_pos has moved (which is opaque to the VFS). */
1278 /* Opens the file, using permissions from current for lack of a better option.
1279 * It will attempt to create the file if it does not exist and O_CREAT is
1280 * specified. This will return 0 on failure, and set errno. TODO: There's some
1281 * stuff that we don't do, esp related file truncating/creation. flags are for
1282 * opening, the mode is for creating. The flags related to how to create
1283 * (O_CREAT_FLAGS) are handled in this function, not in create_file().
1285 * It's tempting to split this into a do_file_create and a do_file_open, based
1286 * on the O_CREAT flag, but the O_CREAT flag can be ignored if the file exists
1287 * already and O_EXCL isn't specified. We could have open call create if it
1288 * fails, but for now we'll keep it as is. */
1289 struct file *do_file_open(char *path, int flags, int mode)
1291 struct file *file = 0;
1292 struct dentry *file_d;
1293 struct inode *parent_i;
1294 struct nameidata nd_r = {0}, *nd = &nd_r;
1297 /* The file might exist, lets try to just open it right away */
1298 nd->intent = LOOKUP_OPEN;
1299 error = path_lookup(path, LOOKUP_FOLLOW, nd);
1301 /* Still need to make sure we didn't want to O_EXCL create */
1302 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1306 file_d = nd->dentry;
1307 kref_get(&file_d->d_kref, 1);
1310 /* So it didn't already exist, release the path from the previous lookup,
1311 * and then we try to create it. */
1313 /* get the parent, following links. this means you get the parent of the
1314 * final link (which may not be in 'path' in the first place. */
1315 nd->intent = LOOKUP_CREATE;
1316 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1321 /* see if the target is there (shouldn't be), and handle accordingly */
1322 file_d = do_lookup(nd->dentry, nd->last.name);
1324 if (!(flags & O_CREAT)) {
1328 /* Create the inode/file. get a fresh dentry too: */
1329 file_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1332 parent_i = nd->dentry->d_inode;
1333 /* Note that the mode technically should only apply to future opens,
1334 * but we apply it immediately. */
1335 if (create_file(parent_i, file_d, mode)) /* sets errno */
1337 dcache_put(file_d->d_sb, file_d);
1338 } else { /* something already exists */
1339 /* this can happen due to concurrent access, but needs to be thought
1341 panic("File shouldn't be here!");
1342 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1343 /* wanted to create, not open, bail out */
1349 /* now open the file (freshly created or if it already existed). At this
1350 * point, file_d is a refcnt'd dentry, regardless of which branch we took.*/
1351 if (flags & O_TRUNC) {
1352 file_d->d_inode->i_size = 0;
1353 /* TODO: probably should remove the garbage pages from the page map */
1355 file = dentry_open(file_d, flags); /* sets errno */
1356 /* Note the fall through to the exit paths. File is 0 by default and if
1357 * dentry_open fails. */
1359 kref_put(&file_d->d_kref);
1365 /* Path is the location of the symlink, sometimes called the "new path", and
1366 * symname is who we link to, sometimes called the "old path". */
1367 int do_symlink(char *path, const char *symname, int mode)
1369 struct dentry *sym_d;
1370 struct inode *parent_i;
1371 struct nameidata nd_r = {0}, *nd = &nd_r;
1375 nd->intent = LOOKUP_CREATE;
1376 /* get the parent, but don't follow links */
1377 error = path_lookup(path, LOOKUP_PARENT, nd);
1382 /* see if the target is already there, handle accordingly */
1383 sym_d = do_lookup(nd->dentry, nd->last.name);
1388 /* Doesn't already exist, let's try to make it: */
1389 sym_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1392 parent_i = nd->dentry->d_inode;
1393 if (create_symlink(parent_i, sym_d, symname, mode))
1395 dcache_put(sym_d->d_sb, sym_d);
1396 retval = 0; /* Note the fall through to the exit paths */
1398 kref_put(&sym_d->d_kref);
1404 /* Makes a hard link for the file behind old_path to new_path */
1405 int do_link(char *old_path, char *new_path)
1407 struct dentry *link_d, *old_d;
1408 struct inode *inode, *parent_dir;
1409 struct nameidata nd_r = {0}, *nd = &nd_r;
1413 nd->intent = LOOKUP_CREATE;
1414 /* get the absolute parent of the new_path */
1415 error = path_lookup(new_path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1420 parent_dir = nd->dentry->d_inode;
1421 /* see if the new target is already there, handle accordingly */
1422 link_d = do_lookup(nd->dentry, nd->last.name);
1427 /* Doesn't already exist, let's try to make it. Still need to stitch it to
1428 * an inode and set its FS-specific stuff after this.*/
1429 link_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1432 /* Now let's get the old_path target */
1433 old_d = lookup_dentry(old_path, LOOKUP_FOLLOW);
1434 if (!old_d) /* errno set by lookup_dentry */
1436 /* For now, can only link to files */
1437 if (!S_ISREG(old_d->d_inode->i_mode)) {
1441 /* Must be on the same FS */
1442 if (old_d->d_sb != link_d->d_sb) {
1446 /* Do whatever FS specific stuff there is first (which is also a chance to
1448 error = parent_dir->i_op->link(old_d, parent_dir, link_d);
1453 /* Finally stitch it up */
1454 inode = old_d->d_inode;
1455 kref_get(&inode->i_kref, 1);
1456 link_d->d_inode = inode;
1458 TAILQ_INSERT_TAIL(&inode->i_dentry, link_d, d_alias); /* weak ref */
1459 dcache_put(link_d->d_sb, link_d);
1460 retval = 0; /* Note the fall through to the exit paths */
1462 kref_put(&old_d->d_kref);
1464 kref_put(&link_d->d_kref);
1470 /* Unlinks path from the directory tree. Read the Documentation for more info.
1472 int do_unlink(char *path)
1474 struct dentry *dentry;
1475 struct inode *parent_dir;
1476 struct nameidata nd_r = {0}, *nd = &nd_r;
1480 /* get the parent of the target, and don't follow a final link */
1481 error = path_lookup(path, LOOKUP_PARENT, nd);
1486 parent_dir = nd->dentry->d_inode;
1487 /* make sure the target is there */
1488 dentry = do_lookup(nd->dentry, nd->last.name);
1493 /* Make sure the target is not a directory */
1494 if (S_ISDIR(dentry->d_inode->i_mode)) {
1498 /* Remove the dentry from its parent */
1499 error = parent_dir->i_op->unlink(parent_dir, dentry);
1504 /* Now that our parent doesn't track us, we need to make sure we aren't
1505 * findable via the dentry cache. DYING, so we will be freed in
1506 * dentry_release() */
1507 dentry->d_flags |= DENTRY_DYING;
1508 dcache_remove(dentry->d_sb, dentry);
1509 dentry->d_inode->i_nlink--; /* TODO: race here, esp with a decref */
1510 /* At this point, the dentry is unlinked from the FS, and the inode has one
1511 * less link. When the in-memory objects (dentry, inode) are going to be
1512 * released (after all open files are closed, and maybe after entries are
1513 * evicted from the cache), then nlinks will get checked and the FS-file
1514 * will get removed from the disk */
1515 retval = 0; /* Note the fall through to the exit paths */
1517 kref_put(&dentry->d_kref);
1523 /* Checks to see if path can be accessed via mode. Need to actually send the
1524 * mode along somehow, so this doesn't do much now. This is an example of
1525 * decent error propagation from the lower levels via int retvals. */
1526 int do_access(char *path, int mode)
1528 struct nameidata nd_r = {0}, *nd = &nd_r;
1530 nd->intent = LOOKUP_ACCESS;
1531 retval = path_lookup(path, 0, nd);
1536 int do_chmod(char *path, int mode)
1538 struct nameidata nd_r = {0}, *nd = &nd_r;
1540 retval = path_lookup(path, 0, nd);
1543 /* TODO: when we have notions of uid, check for the proc's uid */
1544 if (nd->dentry->d_inode->i_uid != UID_OF_ME)
1548 nd->dentry->d_inode->i_mode |= mode & S_PMASK;
1554 /* Make a directory at path with mode. Returns -1 and sets errno on errors */
1555 int do_mkdir(char *path, int mode)
1557 struct dentry *dentry;
1558 struct inode *parent_i;
1559 struct nameidata nd_r = {0}, *nd = &nd_r;
1563 nd->intent = LOOKUP_CREATE;
1564 /* get the parent, but don't follow links */
1565 error = path_lookup(path, LOOKUP_PARENT, nd);
1570 /* see if the target is already there, handle accordingly */
1571 dentry = do_lookup(nd->dentry, nd->last.name);
1576 /* Doesn't already exist, let's try to make it: */
1577 dentry = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1580 parent_i = nd->dentry->d_inode;
1581 if (create_dir(parent_i, dentry, mode))
1583 dcache_put(dentry->d_sb, dentry);
1584 retval = 0; /* Note the fall through to the exit paths */
1586 kref_put(&dentry->d_kref);
1592 int do_rmdir(char *path)
1594 struct dentry *dentry;
1595 struct inode *parent_i;
1596 struct nameidata nd_r = {0}, *nd = &nd_r;
1600 /* get the parent, following links (probably want this), and we must get a
1601 * directory. Note, current versions of path_lookup can't handle both
1602 * PARENT and DIRECTORY, at least, it doesn't check that *path is a
1604 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW | LOOKUP_DIRECTORY,
1610 /* make sure the target is already there, handle accordingly */
1611 dentry = do_lookup(nd->dentry, nd->last.name);
1616 if (!S_ISDIR(dentry->d_inode->i_mode)) {
1620 if (dentry->d_mount_point) {
1624 /* TODO: make sure we aren't a mount or processes root (EBUSY) */
1625 /* Now for the removal. the FSs will check if they are empty */
1626 parent_i = nd->dentry->d_inode;
1627 error = parent_i->i_op->rmdir(parent_i, dentry);
1632 /* Now that our parent doesn't track us, we need to make sure we aren't
1633 * findable via the dentry cache. DYING, so we will be freed in
1634 * dentry_release() */
1635 dentry->d_flags |= DENTRY_DYING;
1636 dcache_remove(dentry->d_sb, dentry);
1637 /* Decref ourselves, so inode_release() knows we are done */
1638 dentry->d_inode->i_nlink--;
1639 TAILQ_REMOVE(&nd->dentry->d_subdirs, dentry, d_subdirs_link);
1640 parent_i->i_nlink--; /* TODO: race on this, esp since its a decref */
1641 /* we still have d_parent and a kref on our parent, which will go away when
1642 * the in-memory dentry object goes away. */
1643 retval = 0; /* Note the fall through to the exit paths */
1645 kref_put(&dentry->d_kref);
1651 /* Pipes: Doing a simple buffer with reader and writer offsets. Size is power
1652 * of two, so we can easily compute its status and whatnot. */
1654 #define PIPE_SZ (1 << PGSHIFT)
1656 static size_t pipe_get_rd_idx(struct pipe_inode_info *pii)
1658 return pii->p_rd_off & (PIPE_SZ - 1);
1661 static size_t pipe_get_wr_idx(struct pipe_inode_info *pii)
1664 return pii->p_wr_off & (PIPE_SZ - 1);
1667 static bool pipe_is_empty(struct pipe_inode_info *pii)
1669 return __ring_empty(pii->p_wr_off, pii->p_rd_off);
1672 static bool pipe_is_full(struct pipe_inode_info *pii)
1674 return __ring_full(PIPE_SZ, pii->p_wr_off, pii->p_rd_off);
1677 static size_t pipe_nr_full(struct pipe_inode_info *pii)
1679 return __ring_nr_full(pii->p_wr_off, pii->p_rd_off);
1682 static size_t pipe_nr_empty(struct pipe_inode_info *pii)
1684 return __ring_nr_empty(PIPE_SZ, pii->p_wr_off, pii->p_rd_off);
1687 ssize_t pipe_file_read(struct file *file, char *buf, size_t count,
1690 struct pipe_inode_info *pii = file->f_dentry->d_inode->i_pipe;
1691 size_t copy_amt, amt_copied = 0;
1693 cv_lock(&pii->p_cv);
1694 while (pipe_is_empty(pii)) {
1695 /* We wait til the pipe is drained before sending EOF if there are no
1696 * writers (instead of aborting immediately) */
1697 if (!pii->p_nr_writers) {
1698 cv_unlock(&pii->p_cv);
1701 if (file->f_flags & O_NONBLOCK) {
1702 cv_unlock(&pii->p_cv);
1706 cv_wait(&pii->p_cv);
1709 /* We might need to wrap-around with our copy, so we'll do the copy in two
1710 * passes. This will copy up to the end of the buffer, then on the next
1711 * pass will copy the rest to the beginning of the buffer (if necessary) */
1712 for (int i = 0; i < 2; i++) {
1713 copy_amt = MIN(PIPE_SZ - pipe_get_rd_idx(pii),
1714 MIN(pipe_nr_full(pii), count));
1715 assert(current); /* shouldn't pipe from the kernel */
1716 memcpy_to_user(current, buf, pii->p_buf + pipe_get_rd_idx(pii),
1720 pii->p_rd_off += copy_amt;
1721 amt_copied += copy_amt;
1723 /* Just using one CV for both readers and writers. We should rarely have
1724 * multiple readers or writers. */
1726 __cv_broadcast(&pii->p_cv);
1727 cv_unlock(&pii->p_cv);
1731 /* Note: we're not dealing with PIPE_BUF and minimum atomic chunks, unless I
1733 ssize_t pipe_file_write(struct file *file, const char *buf, size_t count,
1736 struct pipe_inode_info *pii = file->f_dentry->d_inode->i_pipe;
1737 size_t copy_amt, amt_copied = 0;
1739 cv_lock(&pii->p_cv);
1740 /* Write aborts right away if there are no readers, regardless of pipe
1742 if (!pii->p_nr_readers) {
1743 cv_unlock(&pii->p_cv);
1747 while (pipe_is_full(pii)) {
1748 if (file->f_flags & O_NONBLOCK) {
1749 cv_unlock(&pii->p_cv);
1753 cv_wait(&pii->p_cv);
1755 /* Still need to check in the loop, in case the last reader left while
1757 if (!pii->p_nr_readers) {
1758 cv_unlock(&pii->p_cv);
1763 /* We might need to wrap-around with our copy, so we'll do the copy in two
1764 * passes. This will copy up to the end of the buffer, then on the next
1765 * pass will copy the rest to the beginning of the buffer (if necessary) */
1766 for (int i = 0; i < 2; i++) {
1767 copy_amt = MIN(PIPE_SZ - pipe_get_wr_idx(pii),
1768 MIN(pipe_nr_empty(pii), count));
1769 assert(current); /* shouldn't pipe from the kernel */
1770 memcpy_from_user(current, pii->p_buf + pipe_get_wr_idx(pii), buf,
1774 pii->p_wr_off += copy_amt;
1775 amt_copied += copy_amt;
1777 /* Just using one CV for both readers and writers. We should rarely have
1778 * multiple readers or writers. */
1780 __cv_broadcast(&pii->p_cv);
1781 cv_unlock(&pii->p_cv);
1785 /* In open and release, we need to track the number of readers and writers,
1786 * which we can differentiate by the file flags. */
1787 int pipe_open(struct inode *inode, struct file *file)
1789 struct pipe_inode_info *pii = inode->i_pipe;
1790 cv_lock(&pii->p_cv);
1791 /* Ugliness due to not using flags for O_RDONLY and friends... */
1792 if (file->f_mode == S_IRUSR) {
1793 pii->p_nr_readers++;
1794 } else if (file->f_mode == S_IWUSR) {
1795 pii->p_nr_writers++;
1797 warn("Bad pipe file flags 0x%x\n", file->f_flags);
1799 cv_unlock(&pii->p_cv);
1803 int pipe_release(struct inode *inode, struct file *file)
1805 struct pipe_inode_info *pii = inode->i_pipe;
1806 cv_lock(&pii->p_cv);
1807 /* Ugliness due to not using flags for O_RDONLY and friends... */
1808 if (file->f_mode == S_IRUSR) {
1809 pii->p_nr_readers--;
1810 } else if (file->f_mode == S_IWUSR) {
1811 pii->p_nr_writers--;
1813 warn("Bad pipe file flags 0x%x\n", file->f_flags);
1815 /* need to wake up any sleeping readers/writers, since we might be done */
1816 __cv_broadcast(&pii->p_cv);
1817 cv_unlock(&pii->p_cv);
1821 struct file_operations pipe_f_op = {
1822 .read = pipe_file_read,
1823 .write = pipe_file_write,
1825 .release = pipe_release,
1829 void pipe_debug(struct file *f)
1831 struct pipe_inode_info *pii = f->f_dentry->d_inode->i_pipe;
1833 printk("PIPE %p\n", pii);
1834 printk("\trdoff %p\n", pii->p_rd_off);
1835 printk("\twroff %p\n", pii->p_wr_off);
1836 printk("\tnr_rds %d\n", pii->p_nr_readers);
1837 printk("\tnr_wrs %d\n", pii->p_nr_writers);
1838 printk("\tcv waiters %d\n", pii->p_cv.nr_waiters);
1842 /* General plan: get a dentry/inode to represent the pipe. We'll alloc it from
1843 * the default_ns SB, but won't actually link it anywhere. It'll only be held
1844 * alive by the krefs, til all the FDs are closed. */
1845 int do_pipe(struct file **pipe_files, int flags)
1847 struct dentry *pipe_d;
1848 struct inode *pipe_i;
1849 struct file *pipe_f_read, *pipe_f_write;
1850 struct super_block *def_sb = default_ns.root->mnt_sb;
1851 struct pipe_inode_info *pii;
1853 pipe_d = get_dentry(def_sb, 0, "pipe");
1856 pipe_d->d_op = &dummy_d_op;
1857 pipe_i = get_inode(pipe_d);
1859 goto error_post_dentry;
1860 /* preemptively mark the dentry for deletion. we have an unlinked dentry
1861 * right off the bat, held in only by the kref chain (pipe_d is the ref). */
1862 pipe_d->d_flags |= DENTRY_DYING;
1863 /* pipe_d->d_inode still has one ref to pipe_i, keeping the inode alive */
1864 kref_put(&pipe_i->i_kref);
1865 /* init inode fields. note we're using the dummy ops for i_op and d_op */
1866 pipe_i->i_mode = S_IRWXU | S_IRWXG | S_IRWXO;
1867 SET_FTYPE(pipe_i->i_mode, __S_IFIFO); /* using type == FIFO */
1868 pipe_i->i_nlink = 1; /* one for the dentry */
1871 pipe_i->i_size = PGSIZE;
1872 pipe_i->i_blocks = 0;
1873 pipe_i->i_atime.tv_sec = 0;
1874 pipe_i->i_atime.tv_nsec = 0;
1875 pipe_i->i_mtime.tv_sec = 0;
1876 pipe_i->i_mtime.tv_nsec = 0;
1877 pipe_i->i_ctime.tv_sec = 0;
1878 pipe_i->i_ctime.tv_nsec = 0;
1879 pipe_i->i_fs_info = 0;
1880 pipe_i->i_op = &dummy_i_op;
1881 pipe_i->i_fop = &pipe_f_op;
1882 pipe_i->i_socket = FALSE;
1883 /* Actually build the pipe. We're using one page, hanging off the
1884 * pipe_inode_info struct. When we release the inode, we free the pipe
1886 pipe_i->i_pipe = kmalloc(sizeof(struct pipe_inode_info), KMALLOC_WAIT);
1887 pii = pipe_i->i_pipe;
1892 pii->p_buf = kpage_zalloc_addr();
1899 pii->p_nr_readers = 0;
1900 pii->p_nr_writers = 0;
1901 cv_init(&pii->p_cv); /* must do this before dentry_open / pipe_open */
1902 /* Now we have an inode for the pipe. We need two files for the read and
1903 * write ends of the pipe. */
1904 flags &= ~(O_ACCMODE); /* avoid user bugs */
1905 pipe_f_read = dentry_open(pipe_d, flags | O_RDONLY);
1908 pipe_f_write = dentry_open(pipe_d, flags | O_WRONLY);
1911 pipe_files[0] = pipe_f_read;
1912 pipe_files[1] = pipe_f_write;
1916 kref_put(&pipe_f_read->f_kref);
1918 page_decref(kva2page(pii->p_buf));
1920 kfree(pipe_i->i_pipe);
1922 /* We don't need to free the pipe_i; putting the dentry will free it */
1924 /* Note we only free the dentry on failure. */
1925 kref_put(&pipe_d->d_kref);
1929 struct file *alloc_file(void)
1931 struct file *file = kmem_cache_alloc(file_kcache, 0);
1936 /* one for the ref passed out*/
1937 kref_init(&file->f_kref, file_release, 1);
1941 /* Opens and returns the file specified by dentry */
1942 struct file *dentry_open(struct dentry *dentry, int flags)
1944 struct inode *inode;
1947 inode = dentry->d_inode;
1948 /* Do the mode first, since we can still error out. f_mode stores how the
1949 * OS file is open, which can be more restrictive than the i_mode */
1950 switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) {
1952 desired_mode = S_IRUSR;
1955 desired_mode = S_IWUSR;
1958 desired_mode = S_IRUSR | S_IWUSR;
1963 if (check_perms(inode, desired_mode))
1965 file = alloc_file();
1968 file->f_mode = desired_mode;
1969 /* Add to the list of all files of this SB */
1970 TAILQ_INSERT_TAIL(&inode->i_sb->s_files, file, f_list);
1971 kref_get(&dentry->d_kref, 1);
1972 file->f_dentry = dentry;
1973 kref_get(&inode->i_sb->s_mount->mnt_kref, 1);
1974 file->f_vfsmnt = inode->i_sb->s_mount; /* saving a ref to the vmnt...*/
1975 file->f_op = inode->i_fop;
1976 /* Don't store open mode or creation flags */
1977 file->f_flags = flags & ~(O_ACCMODE | O_CREAT_FLAGS);
1979 file->f_uid = inode->i_uid;
1980 file->f_gid = inode->i_gid;
1982 // struct event_poll_tailq f_ep_links;
1983 spinlock_init(&file->f_ep_lock);
1984 file->f_privdata = 0; /* prob overriden by the fs */
1985 file->f_mapping = inode->i_mapping;
1986 file->f_op->open(inode, file);
1993 /* Closes a file, fsync, whatever else is necessary. Called when the kref hits
1994 * 0. Note that the file is not refcounted on the s_files list, nor is the
1995 * f_mapping refcounted (it is pinned by the i_mapping). */
1996 void file_release(struct kref *kref)
1998 struct file *file = container_of(kref, struct file, f_kref);
2000 struct super_block *sb = file->f_dentry->d_sb;
2001 spin_lock(&sb->s_lock);
2002 TAILQ_REMOVE(&sb->s_files, file, f_list);
2003 spin_unlock(&sb->s_lock);
2005 /* TODO: fsync (BLK). also, we may want to parallelize the blocking that
2006 * could happen in here (spawn kernel threads)... */
2007 file->f_op->release(file->f_dentry->d_inode, file);
2008 /* Clean up the other refs we hold */
2009 kref_put(&file->f_dentry->d_kref);
2010 kref_put(&file->f_vfsmnt->mnt_kref);
2011 kmem_cache_free(file_kcache, file);
2014 /* Process-related File management functions */
2016 /* Given any FD, get the appropriate file, 0 o/w */
2017 struct file *get_file_from_fd(struct files_struct *open_files, int file_desc)
2019 struct file *retval = 0;
2022 spin_lock(&open_files->lock);
2023 if (open_files->closed) {
2024 spin_unlock(&open_files->lock);
2027 if (file_desc < open_files->max_fdset) {
2028 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
2029 /* while max_files and max_fdset might not line up, we should never
2030 * have a valid fdset higher than files */
2031 assert(file_desc < open_files->max_files);
2032 retval = open_files->fd[file_desc].fd_file;
2033 /* 9ns might be using this one, in which case file == 0 */
2035 kref_get(&retval->f_kref, 1);
2038 spin_unlock(&open_files->lock);
2042 /* 9ns: puts back an FD from the VFS-FD-space. */
2043 int put_fd(struct files_struct *open_files, int file_desc)
2045 if (file_desc < 0) {
2046 warn("Negative FD!\n");
2049 spin_lock(&open_files->lock);
2050 if (file_desc < open_files->max_fdset) {
2051 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
2052 /* while max_files and max_fdset might not line up, we should never
2053 * have a valid fdset higher than files */
2054 assert(file_desc < open_files->max_files);
2055 CLR_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc);
2058 spin_unlock(&open_files->lock);
2062 /* Remove FD from the open files, if it was there, and return f. Currently,
2063 * this decref's f, so the return value is not consumable or even usable. This
2064 * hasn't been thought through yet. */
2065 struct file *put_file_from_fd(struct files_struct *open_files, int file_desc)
2067 struct file *file = 0;
2070 spin_lock(&open_files->lock);
2071 if (file_desc < open_files->max_fdset) {
2072 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
2073 /* while max_files and max_fdset might not line up, we should never
2074 * have a valid fdset higher than files */
2075 assert(file_desc < open_files->max_files);
2076 file = open_files->fd[file_desc].fd_file;
2077 open_files->fd[file_desc].fd_file = 0;
2079 kref_put(&file->f_kref);
2080 CLR_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc);
2083 spin_unlock(&open_files->lock);
2087 static int __get_fd(struct files_struct *open_files, int low_fd)
2090 if ((low_fd < 0) || (low_fd > NR_FILE_DESC_MAX))
2092 if (open_files->closed)
2093 return -EINVAL; /* won't matter, they are dying */
2094 for (int i = low_fd; i < open_files->max_fdset; i++) {
2095 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i))
2098 SET_BITMASK_BIT(open_files->open_fds->fds_bits, slot);
2099 assert(slot < open_files->max_files &&
2100 open_files->fd[slot].fd_file == 0);
2101 if (slot >= open_files->next_fd)
2102 open_files->next_fd = slot + 1;
2105 if (slot == -1) /* should expand the FD array and fd_set */
2106 warn("Ran out of file descriptors, deal with me!");
2110 /* Gets and claims a free FD, used by 9ns. < 0 == error. */
2111 int get_fd(struct files_struct *open_files, int low_fd)
2114 spin_lock(&open_files->lock);
2115 slot = __get_fd(open_files, low_fd);
2116 spin_unlock(&open_files->lock);
2120 /* Inserts the file in the files_struct, returning the corresponding new file
2121 * descriptor, or an error code. We start looking for open fds from low_fd. */
2122 int insert_file(struct files_struct *open_files, struct file *file, int low_fd)
2125 spin_lock(&open_files->lock);
2126 slot = __get_fd(open_files, low_fd);
2128 spin_unlock(&open_files->lock);
2131 assert(slot < open_files->max_files &&
2132 open_files->fd[slot].fd_file == 0);
2133 kref_get(&file->f_kref, 1);
2134 open_files->fd[slot].fd_file = file;
2135 open_files->fd[slot].fd_flags = 0;
2136 spin_unlock(&open_files->lock);
2140 /* Closes all open files. Mostly just a "put" for all files. If cloexec, it
2141 * will only close files that are opened with O_CLOEXEC. */
2142 void close_all_files(struct files_struct *open_files, bool cloexec)
2145 spin_lock(&open_files->lock);
2146 if (open_files->closed) {
2147 spin_unlock(&open_files->lock);
2151 open_files->closed = TRUE;
2152 for (int i = 0; i < open_files->max_fdset; i++) {
2153 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i)) {
2154 /* while max_files and max_fdset might not line up, we should never
2155 * have a valid fdset higher than files */
2156 assert(i < open_files->max_files);
2157 file = open_files->fd[i].fd_file;
2158 /* no file == 9ns uses the FD. they will deal with it */
2161 if (cloexec && !(open_files->fd[i].fd_flags & O_CLOEXEC))
2163 /* Actually close the file */
2164 open_files->fd[i].fd_file = 0;
2166 kref_put(&file->f_kref);
2167 CLR_BITMASK_BIT(open_files->open_fds->fds_bits, i);
2170 spin_unlock(&open_files->lock);
2173 /* Inserts all of the files from src into dst, used by sys_fork(). */
2174 void clone_files(struct files_struct *src, struct files_struct *dst)
2177 spin_lock(&src->lock);
2179 spin_unlock(&src->lock);
2182 spin_lock(&dst->lock);
2184 warn("Destination closed before it opened");
2185 spin_unlock(&dst->lock);
2186 spin_unlock(&src->lock);
2189 for (int i = 0; i < src->max_fdset; i++) {
2190 if (GET_BITMASK_BIT(src->open_fds->fds_bits, i)) {
2191 /* while max_files and max_fdset might not line up, we should never
2192 * have a valid fdset higher than files */
2193 assert(i < src->max_files);
2194 file = src->fd[i].fd_file;
2195 assert(i < dst->max_files && dst->fd[i].fd_file == 0);
2196 SET_BITMASK_BIT(dst->open_fds->fds_bits, i);
2197 dst->fd[i].fd_file = file;
2199 kref_get(&file->f_kref, 1);
2200 if (i >= dst->next_fd)
2201 dst->next_fd = i + 1;
2204 spin_unlock(&dst->lock);
2205 spin_unlock(&src->lock);
2208 /* Change the working directory of the given fs env (one per process, at this
2209 * point). Returns 0 for success, -ERROR for whatever error. */
2210 int do_chdir(struct fs_struct *fs_env, char *path)
2212 struct nameidata nd_r = {0}, *nd = &nd_r;
2214 retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
2216 /* nd->dentry is the place we want our PWD to be */
2217 kref_get(&nd->dentry->d_kref, 1);
2218 kref_put(&fs_env->pwd->d_kref);
2219 fs_env->pwd = nd->dentry;
2225 /* Returns a null-terminated string of up to length cwd_l containing the
2226 * absolute path of fs_env, (up to fs_env's root). Be sure to kfree the char*
2227 * "kfree_this" when you are done with it. We do this since it's easier to
2228 * build this string going backwards. Note cwd_l is not a strlen, it's an
2230 char *do_getcwd(struct fs_struct *fs_env, char **kfree_this, size_t cwd_l)
2232 struct dentry *dentry = fs_env->pwd;
2234 char *path_start, *kbuf;
2240 kbuf = kmalloc(cwd_l, 0);
2246 kbuf[cwd_l - 1] = '\0';
2247 kbuf[cwd_l - 2] = '/';
2248 /* for each dentry in the path, all the way back to the root of fs_env, we
2249 * grab the dentry name, push path_start back enough, and write in the name,
2250 * using /'s to terminate. We skip the root, since we don't want it's
2251 * actual name, just "/", which is set before each loop. */
2252 path_start = kbuf + cwd_l - 2; /* the last byte written */
2253 while (dentry != fs_env->root) {
2254 link_len = dentry->d_name.len; /* this does not count the \0 */
2255 if (path_start - (link_len + 2) < kbuf) {
2260 path_start -= link_len + 1; /* the 1 is for the \0 */
2261 strncpy(path_start, dentry->d_name.name, link_len);
2264 dentry = dentry->d_parent;
2269 static void print_dir(struct dentry *dentry, char *buf, int depth)
2271 struct dentry *child_d;
2272 struct dirent next = {0};
2276 if (!S_ISDIR(dentry->d_inode->i_mode)) {
2277 warn("Thought this was only directories!!");
2280 /* Print this dentry */
2281 printk("%s%s/ nlink: %d\n", buf, dentry->d_name.name,
2282 dentry->d_inode->i_nlink);
2283 if (dentry->d_mount_point) {
2284 dentry = dentry->d_mounted_fs->mnt_root;
2288 /* Set buffer for our kids */
2290 dir = dentry_open(dentry, 0);
2292 panic("Filesystem seems inconsistent - unable to open a dir!");
2293 /* Process every child, recursing on directories */
2295 retval = dir->f_op->readdir(dir, &next);
2297 /* Skip .., ., and empty entries */
2298 if (!strcmp("..", next.d_name) || !strcmp(".", next.d_name) ||
2301 /* there is an entry, now get its dentry */
2302 child_d = do_lookup(dentry, next.d_name);
2304 panic("Inconsistent FS, dirent doesn't have a dentry!");
2305 /* Recurse for directories, or just print the name for others */
2306 switch (child_d->d_inode->i_mode & __S_IFMT) {
2308 print_dir(child_d, buf, depth + 1);
2311 printk("%s%s size(B): %d nlink: %d\n", buf, next.d_name,
2312 child_d->d_inode->i_size, child_d->d_inode->i_nlink);
2315 printk("%s%s -> %s\n", buf, next.d_name,
2316 child_d->d_inode->i_op->readlink(child_d));
2319 printk("%s%s (char device) nlink: %d\n", buf, next.d_name,
2320 child_d->d_inode->i_nlink);
2323 printk("%s%s (block device) nlink: %d\n", buf, next.d_name,
2324 child_d->d_inode->i_nlink);
2327 warn("Look around you! Unknown filetype!");
2329 kref_put(&child_d->d_kref);
2335 /* Reset buffer to the way it was */
2337 kref_put(&dir->f_kref);
2341 int ls_dash_r(char *path)
2343 struct nameidata nd_r = {0}, *nd = &nd_r;
2347 error = path_lookup(path, LOOKUP_ACCESS | LOOKUP_DIRECTORY, nd);
2352 print_dir(nd->dentry, buf, 0);
2357 /* Dummy ops, to catch weird operations we weren't expecting */
2358 int dummy_create(struct inode *dir, struct dentry *dentry, int mode,
2359 struct nameidata *nd)
2361 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2365 struct dentry *dummy_lookup(struct inode *dir, struct dentry *dentry,
2366 struct nameidata *nd)
2368 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2372 int dummy_link(struct dentry *old_dentry, struct inode *dir,
2373 struct dentry *new_dentry)
2375 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2379 int dummy_unlink(struct inode *dir, struct dentry *dentry)
2381 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2385 int dummy_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
2387 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2391 int dummy_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2393 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2397 int dummy_rmdir(struct inode *dir, struct dentry *dentry)
2399 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2403 int dummy_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t rdev)
2405 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2409 int dummy_rename(struct inode *old_dir, struct dentry *old_dentry,
2410 struct inode *new_dir, struct dentry *new_dentry)
2412 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2416 char *dummy_readlink(struct dentry *dentry)
2418 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2422 void dummy_truncate(struct inode *inode)
2424 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2427 int dummy_permission(struct inode *inode, int mode, struct nameidata *nd)
2429 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2433 int dummy_d_revalidate(struct dentry *dir, struct nameidata *nd)
2435 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2439 int dummy_d_hash(struct dentry *dentry, struct qstr *name)
2441 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2445 int dummy_d_compare(struct dentry *dir, struct qstr *name1, struct qstr *name2)
2447 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2451 int dummy_d_delete(struct dentry *dentry)
2453 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2457 int dummy_d_release(struct dentry *dentry)
2459 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2463 void dummy_d_iput(struct dentry *dentry, struct inode *inode)
2465 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2468 struct inode_operations dummy_i_op = {
2483 struct dentry_operations dummy_d_op = {