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
23 struct sb_tailq super_blocks = TAILQ_HEAD_INITIALIZER(super_blocks);
24 spinlock_t super_blocks_lock = SPINLOCK_INITIALIZER;
25 struct fs_type_tailq file_systems = TAILQ_HEAD_INITIALIZER(file_systems);
26 struct namespace default_ns;
28 struct kmem_cache *dentry_kcache; // not to be confused with the dcache
29 struct kmem_cache *inode_kcache;
30 struct kmem_cache *file_kcache;
32 /* Mounts fs from dev_name at mnt_pt in namespace ns. There could be no mnt_pt,
33 * such as with the root of (the default) namespace. Not sure how it would work
34 * with multiple namespaces on the same FS yet. Note if you mount the same FS
35 * multiple times, you only have one FS still (and one SB). If we ever support
37 struct vfsmount *__mount_fs(struct fs_type *fs, char *dev_name,
38 struct dentry *mnt_pt, int flags,
41 struct super_block *sb;
42 struct vfsmount *vmnt = kmalloc(sizeof(struct vfsmount), 0);
44 /* this first ref is stored in the NS tailq below */
45 kref_init(&vmnt->mnt_kref, fake_release, 1);
46 /* Build the vfsmount, if there is no mnt_pt, mnt is the root vfsmount (for
47 * now). fields related to the actual FS, like the sb and the mnt_root are
48 * set in the fs-specific get_sb() call. */
50 vmnt->mnt_parent = NULL;
51 vmnt->mnt_mountpoint = NULL;
52 } else { /* common case, but won't be tested til we try to mount another FS */
53 mnt_pt->d_mount_point = TRUE;
54 mnt_pt->d_mounted_fs = vmnt;
55 kref_get(&vmnt->mnt_kref, 1); /* held by mnt_pt */
56 vmnt->mnt_parent = mnt_pt->d_sb->s_mount;
57 vmnt->mnt_mountpoint = mnt_pt;
59 TAILQ_INIT(&vmnt->mnt_child_mounts);
60 vmnt->mnt_flags = flags;
61 vmnt->mnt_devname = dev_name;
62 vmnt->mnt_namespace = ns;
63 kref_get(&ns->kref, 1); /* held by vmnt */
65 /* Read in / create the SB */
66 sb = fs->get_sb(fs, flags, dev_name, vmnt);
68 panic("You're FS sucks");
70 /* TODO: consider moving this into get_sb or something, in case the SB
71 * already exists (mounting again) (if we support that) */
72 spin_lock(&super_blocks_lock);
73 TAILQ_INSERT_TAIL(&super_blocks, sb, s_list); /* storing a ref here... */
74 spin_unlock(&super_blocks_lock);
76 /* Update holding NS */
78 TAILQ_INSERT_TAIL(&ns->vfsmounts, vmnt, mnt_list);
79 spin_unlock(&ns->lock);
80 /* note to self: so, right after this point, the NS points to the root FS
81 * mount (we return the mnt, which gets assigned), the root mnt has a dentry
82 * for /, backed by an inode, with a SB prepped and in memory. */
90 dentry_kcache = kmem_cache_create("dentry", sizeof(struct dentry),
91 __alignof__(struct dentry), 0, 0, 0);
92 inode_kcache = kmem_cache_create("inode", sizeof(struct inode),
93 __alignof__(struct inode), 0, 0, 0);
94 file_kcache = kmem_cache_create("file", sizeof(struct file),
95 __alignof__(struct file), 0, 0, 0);
96 /* default NS never dies, +1 to exist */
97 kref_init(&default_ns.kref, fake_release, 1);
98 spinlock_init(&default_ns.lock);
99 default_ns.root = NULL;
100 TAILQ_INIT(&default_ns.vfsmounts);
102 /* build list of all FS's in the system. put yours here. if this is ever
103 * done on the fly, we'll need to lock. */
104 TAILQ_INSERT_TAIL(&file_systems, &kfs_fs_type, list);
106 TAILQ_INSERT_TAIL(&file_systems, &ext2_fs_type, list);
108 TAILQ_FOREACH(fs, &file_systems, list)
109 printk("Supports the %s Filesystem\n", fs->name);
111 /* mounting KFS at the root (/), pending root= parameters */
112 // TODO: linux creates a temp root_fs, then mounts the real root onto that
113 default_ns.root = __mount_fs(&kfs_fs_type, "RAM", NULL, 0, &default_ns);
115 printk("vfs_init() completed\n");
118 /* FS's can provide another, if they want */
119 int generic_dentry_hash(struct dentry *dentry, struct qstr *qstr)
121 unsigned long hash = 5381;
123 for (int i = 0; i < qstr->len; i++) {
124 /* hash * 33 + c, djb2's technique */
125 hash = ((hash << 5) + hash) + qstr->name[i];
130 /* Builds / populates the qstr of a dentry based on its d_iname. If there is an
131 * l_name, (long), it will use that instead of the inline name. This will
132 * probably change a bit. */
133 void qstr_builder(struct dentry *dentry, char *l_name)
135 dentry->d_name.name = l_name ? l_name : dentry->d_iname;
136 dentry->d_name.len = strnlen(dentry->d_name.name, MAX_FILENAME_SZ);
137 dentry->d_name.hash = dentry->d_op->d_hash(dentry, &dentry->d_name);
140 /* Useful little helper - return the string ptr for a given file */
141 char *file_name(struct file *file)
143 return file->f_dentry->d_name.name;
146 static int prepend(char **pbuf, size_t *pbuflen, const char *str, size_t len)
149 return -ENAMETOOLONG;
152 memcpy(*pbuf, str, len);
157 char *dentry_path(struct dentry *dentry, char *path, size_t max_size)
159 size_t csize = max_size;
160 char *path_start = path + max_size, *base;
162 if (prepend(&path_start, &csize, "\0", 1) < 0 || csize < 1)
164 /* Handle the case that the passed dentry is the root. */
165 base = path_start - 1;
167 while (!DENTRY_IS_ROOT(dentry)) {
168 if (prepend(&path_start, &csize, dentry->d_name.name,
169 dentry->d_name.len) < 0 ||
170 prepend(&path_start, &csize, "/", 1) < 0)
173 dentry = dentry->d_parent;
179 /* Some issues with this, coupled closely to fs_lookup.
181 * Note the use of __dentry_free, instead of kref_put. In those cases, we don't
182 * want to treat it like a kref and we have the only reference to it, so it is
183 * okay to do this. It makes dentry_release() easier too. */
184 static struct dentry *do_lookup(struct dentry *parent, char *name)
186 struct dentry *result, *query;
187 query = get_dentry(parent->d_sb, parent, name);
189 warn("OOM in do_lookup(), probably wasn't expected\n");
192 result = dcache_get(parent->d_sb, query);
194 __dentry_free(query);
197 /* No result, check for negative */
198 if (query->d_flags & DENTRY_NEGATIVE) {
199 __dentry_free(query);
202 /* not in the dcache at all, need to consult the FS */
203 result = parent->d_inode->i_op->lookup(parent->d_inode, query, 0);
205 /* Note the USED flag will get turned off when this gets added to the
206 * LRU in dentry_release(). There's a slight race here that we'll panic
207 * on, but I want to catch it (in dcache_put()) for now. */
208 query->d_flags |= DENTRY_NEGATIVE;
209 dcache_put(parent->d_sb, query);
210 kref_put(&query->d_kref);
213 dcache_put(parent->d_sb, result);
214 /* This is because KFS doesn't return the same dentry, but ext2 does. this
215 * is ugly and needs to be fixed. (TODO) */
217 __dentry_free(query);
219 /* TODO: if the following are done by us, how do we know the i_ino?
220 * also need to handle inodes that are already read in! For now, we're
221 * going to have the FS handle it in its lookup() method:
223 * - read in the inode
224 * - put in the inode cache */
228 /* Update ND such that it represents having followed dentry. IAW the nd
229 * refcnting rules, we need to decref any references that were in there before
230 * they get clobbered. */
231 static int next_link(struct dentry *dentry, struct nameidata *nd)
233 assert(nd->dentry && nd->mnt);
234 /* update the dentry */
235 kref_get(&dentry->d_kref, 1);
236 kref_put(&nd->dentry->d_kref);
238 /* update the mount, if we need to */
239 if (dentry->d_sb->s_mount != nd->mnt) {
240 kref_get(&dentry->d_sb->s_mount->mnt_kref, 1);
241 kref_put(&nd->mnt->mnt_kref);
242 nd->mnt = dentry->d_sb->s_mount;
247 /* Walk up one directory, being careful of mountpoints, namespaces, and the top
249 static int climb_up(struct nameidata *nd)
251 printd("CLIMB_UP, from %s\n", nd->dentry->d_name.name);
252 /* Top of the world, just return. Should also check for being at the top of
253 * the current process's namespace (TODO) */
254 if (!nd->dentry->d_parent || (nd->dentry->d_parent == nd->dentry))
256 /* Check if we are at the top of a mount, if so, we need to follow
257 * backwards, and then climb_up from that one. We might need to climb
258 * multiple times if we mount multiple FSs at the same spot (highly
259 * unlikely). This is completely untested. Might recurse instead. */
260 while (nd->mnt->mnt_root == nd->dentry) {
261 if (!nd->mnt->mnt_parent) {
262 warn("Might have expected a parent vfsmount (dentry had a parent)");
265 next_link(nd->mnt->mnt_mountpoint, nd);
267 /* Backwards walk (no mounts or any other issues now). */
268 next_link(nd->dentry->d_parent, nd);
269 printd("CLIMB_UP, to %s\n", nd->dentry->d_name.name);
273 /* nd->dentry might be on a mount point, so we need to move on to the child
275 static int follow_mount(struct nameidata *nd)
277 if (!nd->dentry->d_mount_point)
279 next_link(nd->dentry->d_mounted_fs->mnt_root, nd);
283 static int link_path_walk(char *path, struct nameidata *nd);
285 /* When nd->dentry is for a symlink, this will recurse and follow that symlink,
286 * so that nd contains the results of following the symlink (dentry and mnt).
287 * Returns when it isn't a symlink, 1 on following a link, and < 0 on error. */
288 static int follow_symlink(struct nameidata *nd)
292 if (!S_ISLNK(nd->dentry->d_inode->i_mode))
294 if (nd->depth > MAX_SYMLINK_DEPTH)
296 printd("Following symlink for dentry %p %s\n", nd->dentry,
297 nd->dentry->d_name.name);
299 symname = nd->dentry->d_inode->i_op->readlink(nd->dentry);
300 /* We need to pin in nd->dentry (the dentry of the symlink), since we need
301 * its symname's storage to stay in memory throughout the upcoming
302 * link_path_walk(). The last_sym gets decreffed when we path_release() or
303 * follow another symlink. */
305 kref_put(&nd->last_sym->d_kref);
306 kref_get(&nd->dentry->d_kref, 1);
307 nd->last_sym = nd->dentry;
308 /* If this an absolute path in the symlink, we need to free the old path and
309 * start over, otherwise, we continue from the PARENT of nd (the symlink) */
310 if (symname[0] == '/') {
313 nd->dentry = default_ns.root->mnt_root;
315 nd->dentry = current->fs_env.root;
316 nd->mnt = nd->dentry->d_sb->s_mount;
317 kref_get(&nd->mnt->mnt_kref, 1);
318 kref_get(&nd->dentry->d_kref, 1);
322 /* either way, keep on walking in the free world! */
323 retval = link_path_walk(symname, nd);
324 return (retval == 0 ? 1 : retval);
327 /* Little helper, to make it easier to break out of the nested loops. Will also
328 * '\0' out the first slash if it's slashes all the way down. Or turtles. */
329 static bool packed_trailing_slashes(char *first_slash)
331 for (char *i = first_slash; *i == '/'; i++) {
332 if (*(i + 1) == '\0') {
340 /* Simple helper to set nd to track its last name to be Name. Also be careful
341 * with the storage of name. Don't use and nd's name past the lifetime of the
342 * string used in the path_lookup()/link_path_walk/whatever. Consider replacing
343 * parts of this with a qstr builder. Note this uses the dentry's d_op, which
344 * might not be the dentry we care about. */
345 static void stash_nd_name(struct nameidata *nd, char *name)
347 nd->last.name = name;
348 nd->last.len = strlen(name);
349 nd->last.hash = nd->dentry->d_op->d_hash(nd->dentry, &nd->last);
352 /* Resolves the links in a basic path walk. 0 for success, -EWHATEVER
353 * otherwise. The final lookup is returned via nd. */
354 static int link_path_walk(char *path, struct nameidata *nd)
356 struct dentry *link_dentry;
357 struct inode *link_inode, *nd_inode;
362 /* Prevent crazy recursion */
363 if (nd->depth > MAX_SYMLINK_DEPTH)
365 /* skip all leading /'s */
368 /* if there's nothing left (null terminated), we're done. This should only
369 * happen for "/", which if we wanted a PARENT, should fail (there is no
372 if (nd->flags & LOOKUP_PARENT) {
376 /* o/w, we're good */
379 /* iterate through each intermediate link of the path. in general, nd
380 * tracks where we are in the path, as far as dentries go. once we have the
381 * next dentry, we try to update nd based on that dentry. link is the part
382 * of the path string that we are looking up */
384 nd_inode = nd->dentry->d_inode;
385 if ((error = check_perms(nd_inode, nd->intent)))
387 /* find the next link, break out if it is the end */
388 next_slash = strchr(link, '/');
392 if (packed_trailing_slashes(next_slash)) {
393 nd->flags |= LOOKUP_DIRECTORY;
397 /* skip over any interim ./ */
398 if (!strncmp("./", link, 2))
400 /* Check for "../", walk up */
401 if (!strncmp("../", link, 3)) {
406 link_dentry = do_lookup(nd->dentry, link);
410 /* make link_dentry the current step/answer */
411 next_link(link_dentry, nd);
412 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt dentry */
413 /* we could be on a mountpoint or a symlink - need to follow them */
415 if ((error = follow_symlink(nd)) < 0)
417 /* Turn off a possible DIRECTORY lookup, which could have been set
418 * during the follow_symlink (a symlink could have had a directory at
419 * the end), though it was in the middle of the real path. */
420 nd->flags &= ~LOOKUP_DIRECTORY;
421 if (!S_ISDIR(nd->dentry->d_inode->i_mode))
424 /* move through the path string to the next entry */
425 link = next_slash + 1;
426 /* advance past any other interim slashes. we know we won't hit the end
427 * due to the for loop check above */
431 /* Now, we're on the last link of the path. We need to deal with with . and
432 * .. . This might be weird with PARENT lookups - not sure what semantics
433 * we want exactly. This will give the parent of whatever the PATH was
434 * supposed to look like. Note that ND currently points to the parent of
435 * the last item (link). */
436 if (!strcmp(".", link)) {
437 if (nd->flags & LOOKUP_PARENT) {
438 assert(nd->dentry->d_name.name);
439 stash_nd_name(nd, nd->dentry->d_name.name);
444 if (!strcmp("..", link)) {
446 if (nd->flags & LOOKUP_PARENT) {
447 assert(nd->dentry->d_name.name);
448 stash_nd_name(nd, nd->dentry->d_name.name);
453 /* need to attempt to look it up, in case it's a symlink */
454 link_dentry = do_lookup(nd->dentry, link);
456 /* if there's no dentry, we are okay if we are looking for the parent */
457 if (nd->flags & LOOKUP_PARENT) {
458 assert(strcmp(link, ""));
459 stash_nd_name(nd, link);
465 next_link(link_dentry, nd);
466 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt'd dentry */
467 /* at this point, nd is on the final link, but it might be a symlink */
468 if (nd->flags & LOOKUP_FOLLOW) {
469 error = follow_symlink(nd);
472 /* if we actually followed a symlink, then nd is set and we're done */
476 /* One way or another, nd is on the last element of the path, symlinks and
477 * all. Now we need to climb up to set nd back on the parent, if that's
479 if (nd->flags & LOOKUP_PARENT) {
480 assert(nd->dentry->d_name.name);
481 stash_nd_name(nd, link_dentry->d_name.name);
485 /* now, we have the dentry set, and don't want the parent, but might be on a
486 * mountpoint still. FYI: this hasn't been thought through completely. */
488 /* If we wanted a directory, but didn't get one, error out */
489 if ((nd->flags & LOOKUP_DIRECTORY) && !S_ISDIR(nd->dentry->d_inode->i_mode))
494 /* Given path, return the inode for the final dentry. The ND should be
495 * initialized for the first call - specifically, we need the intent.
496 * LOOKUP_PARENT and friends go in the flags var, which is not the intent.
498 * If path_lookup wants a PARENT, but hits the top of the FS (root or
499 * otherwise), we want it to error out. It's still unclear how we want to
500 * handle processes with roots that aren't root, but at the very least, we don't
501 * want to think we have the parent of /, but have / itself. Due to the way
502 * link_path_walk works, if that happened, we probably don't have a
503 * nd->last.name. This needs more thought (TODO).
505 * Need to be careful too. While the path has been copied-in to the kernel,
506 * it's still user input. */
507 int path_lookup(char *path, int flags, struct nameidata *nd)
510 printd("Path lookup for %s\n", path);
511 /* we allow absolute lookups with no process context */
512 /* TODO: RCU read lock on pwd or kref_not_zero in a loop. concurrent chdir
513 * could decref nd->dentry before we get to incref it below. */
514 if (path[0] == '/') { /* absolute lookup */
516 nd->dentry = default_ns.root->mnt_root;
518 nd->dentry = current->fs_env.root;
519 } else { /* relative lookup */
521 /* Don't need to lock on the fs_env since we're reading one item */
522 nd->dentry = current->fs_env.pwd;
524 nd->mnt = nd->dentry->d_sb->s_mount;
525 /* Whenever references get put in the nd, incref them. Whenever they are
526 * removed, decref them. */
527 kref_get(&nd->mnt->mnt_kref, 1);
528 kref_get(&nd->dentry->d_kref, 1);
530 nd->depth = 0; /* used in symlink following */
531 retval = link_path_walk(path, nd);
532 /* make sure our PARENT lookup worked */
533 if (!retval && (flags & LOOKUP_PARENT))
534 assert(nd->last.name);
538 /* Call this after any use of path_lookup when you are done with its results,
539 * regardless of whether it succeeded or not. It will free any references */
540 void path_release(struct nameidata *nd)
542 kref_put(&nd->dentry->d_kref);
543 kref_put(&nd->mnt->mnt_kref);
544 /* Free the last symlink dentry used, if there was one */
546 kref_put(&nd->last_sym->d_kref);
547 nd->last_sym = 0; /* catch reuse bugs */
551 /* External version of mount, only call this after having a / mount */
552 int mount_fs(struct fs_type *fs, char *dev_name, char *path, int flags)
554 struct nameidata nd_r = {0}, *nd = &nd_r;
556 retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
559 /* taking the namespace of the vfsmount of path */
560 if (!__mount_fs(fs, dev_name, nd->dentry, flags, nd->mnt->mnt_namespace))
567 /* Superblock functions */
569 /* Dentry "hash" function for the hash table to use. Since we already have the
570 * hash in the qstr, we don't need to rehash. Also, note we'll be using the
571 * dentry in question as both the key and the value. */
572 static size_t __dcache_hash(void *k)
574 return (size_t)((struct dentry*)k)->d_name.hash;
577 /* Dentry cache hashtable equality function. This means we need to pass in some
578 * minimal dentry when doing a lookup. */
579 static ssize_t __dcache_eq(void *k1, void *k2)
581 if (((struct dentry*)k1)->d_parent != ((struct dentry*)k2)->d_parent)
583 /* TODO: use the FS-specific string comparison */
584 return !strcmp(((struct dentry*)k1)->d_name.name,
585 ((struct dentry*)k2)->d_name.name);
588 /* Helper to alloc and initialize a generic superblock. This handles all the
589 * VFS related things, like lists. Each FS will need to handle its own things
590 * in its *_get_sb(), usually involving reading off the disc. */
591 struct super_block *get_sb(void)
593 struct super_block *sb = kmalloc(sizeof(struct super_block), 0);
595 spinlock_init(&sb->s_lock);
596 kref_init(&sb->s_kref, fake_release, 1); /* for the ref passed out */
597 TAILQ_INIT(&sb->s_inodes);
598 TAILQ_INIT(&sb->s_dirty_i);
599 TAILQ_INIT(&sb->s_io_wb);
600 TAILQ_INIT(&sb->s_lru_d);
601 TAILQ_INIT(&sb->s_files);
602 sb->s_dcache = create_hashtable(100, __dcache_hash, __dcache_eq);
603 sb->s_icache = create_hashtable(100, __generic_hash, __generic_eq);
604 spinlock_init(&sb->s_lru_lock);
605 spinlock_init(&sb->s_dcache_lock);
606 spinlock_init(&sb->s_icache_lock);
607 sb->s_fs_info = 0; // can override somewhere else
611 /* Final stages of initializing a super block, including creating and linking
612 * the root dentry, root inode, vmnt, and sb. The d_op and root_ino are
613 * FS-specific, but otherwise its FS-independent, tricky, and not worth having
614 * around multiple times.
616 * Not the world's best interface, so it's subject to change, esp since we're
617 * passing (now 3) FS-specific things. */
618 void init_sb(struct super_block *sb, struct vfsmount *vmnt,
619 struct dentry_operations *d_op, unsigned long root_ino,
622 /* Build and init the first dentry / inode. The dentry ref is stored later
623 * by vfsmount's mnt_root. The parent is dealt with later. */
624 struct dentry *d_root = get_dentry_with_ops(sb, 0, "/", d_op);
627 panic("OOM! init_sb() can't fail yet!");
628 /* a lot of here on down is normally done in lookup() or create, since
629 * get_dentry isn't a fully usable dentry. The two FS-specific settings are
630 * normally inherited from a parent within the same FS in get_dentry, but we
633 d_root->d_fs_info = d_fs_info;
634 struct inode *inode = get_inode(d_root);
636 panic("This FS sucks!");
637 inode->i_ino = root_ino;
638 /* TODO: add the inode to the appropriate list (off i_list) */
639 /* TODO: do we need to read in the inode? can we do this on demand? */
640 /* if this FS is already mounted, we'll need to do something different. */
641 sb->s_op->read_inode(inode);
642 icache_put(sb, inode);
643 /* Link the dentry and SB to the VFS mount */
644 vmnt->mnt_root = d_root; /* ref comes from get_dentry */
646 /* If there is no mount point, there is no parent. This is true only for
648 if (vmnt->mnt_mountpoint) {
649 kref_get(&vmnt->mnt_mountpoint->d_kref, 1); /* held by d_root */
650 d_root->d_parent = vmnt->mnt_mountpoint; /* dentry of the root */
652 d_root->d_parent = d_root; /* set root as its own parent */
654 /* insert the dentry into the dentry cache. when's the earliest we can?
655 * when's the earliest we should? what about concurrent accesses to the
656 * same dentry? should be locking the dentry... */
657 dcache_put(sb, d_root);
658 kref_put(&inode->i_kref); /* give up the ref from get_inode() */
661 /* Dentry Functions */
663 static void dentry_set_name(struct dentry *dentry, char *name)
665 size_t name_len = strnlen(name, MAX_FILENAME_SZ); /* not including \0! */
667 if (name_len < DNAME_INLINE_LEN) {
668 strlcpy(dentry->d_iname, name, name_len + 1);
669 qstr_builder(dentry, 0);
671 l_name = kmalloc(name_len + 1, 0);
673 strlcpy(l_name, name, name_len + 1);
674 qstr_builder(dentry, l_name);
678 /* Gets a dentry. If there is no parent, use d_op. Only called directly by
679 * superblock init code. */
680 struct dentry *get_dentry_with_ops(struct super_block *sb,
681 struct dentry *parent, char *name,
682 struct dentry_operations *d_op)
685 struct dentry *dentry = kmem_cache_alloc(dentry_kcache, 0);
691 //memset(dentry, 0, sizeof(struct dentry));
692 kref_init(&dentry->d_kref, dentry_release, 1); /* this ref is returned */
693 spinlock_init(&dentry->d_lock);
694 TAILQ_INIT(&dentry->d_subdirs);
696 kref_get(&sb->s_kref, 1);
697 dentry->d_sb = sb; /* storing a ref here... */
698 dentry->d_mount_point = FALSE;
699 dentry->d_mounted_fs = 0;
700 if (parent) { /* no parent for rootfs mount */
701 kref_get(&parent->d_kref, 1);
702 dentry->d_op = parent->d_op; /* d_op set in init_sb for parentless */
706 dentry->d_parent = parent;
707 dentry->d_flags = DENTRY_USED;
708 dentry->d_fs_info = 0;
709 dentry_set_name(dentry, name);
710 /* Catch bugs by aggressively zeroing this (o/w we use old stuff) */
715 /* Helper to alloc and initialize a generic dentry. The following needs to be
716 * set still: d_op (if no parent), d_fs_info (opt), d_inode, connect the inode
717 * to the dentry (and up the d_kref again), maybe dcache_put(). The inode
718 * stitching is done in get_inode() or lookup (depending on the FS).
719 * The setting of the d_op might be problematic when dealing with mounts. Just
722 * If the name is longer than the inline name, it will kmalloc a buffer, so
723 * don't worry about the storage for *name after calling this. */
724 struct dentry *get_dentry(struct super_block *sb, struct dentry *parent,
727 return get_dentry_with_ops(sb, parent, name, 0);
730 /* Called when the dentry is unreferenced (after kref == 0). This works closely
731 * with the resurrection in dcache_get().
733 * The dentry is still in the dcache, but needs to be un-USED and added to the
734 * LRU dentry list. Even dentries that were used in a failed lookup need to be
735 * cached - they ought to be the negative dentries. Note that all dentries have
736 * parents, even negative ones (it is needed to find it in the dcache). */
737 void dentry_release(struct kref *kref)
739 struct dentry *dentry = container_of(kref, struct dentry, d_kref);
741 printd("'Releasing' dentry %p: %s\n", dentry, dentry->d_name.name);
742 /* DYING dentries (recently unlinked / rmdir'd) just get freed */
743 if (dentry->d_flags & DENTRY_DYING) {
744 __dentry_free(dentry);
747 /* This lock ensures the USED state and the TAILQ membership is in sync.
748 * Also used to check the refcnt, though that might not be necessary. */
749 spin_lock(&dentry->d_lock);
750 /* While locked, we need to double check the kref, in case someone already
751 * reup'd it. Re-up? you're crazy! Reee-up, you're outta yo mind! */
752 if (!kref_refcnt(&dentry->d_kref)) {
753 /* Note this is where negative dentries get set UNUSED */
754 if (dentry->d_flags & DENTRY_USED) {
755 dentry->d_flags &= ~DENTRY_USED;
756 spin_lock(&dentry->d_sb->s_lru_lock);
757 TAILQ_INSERT_TAIL(&dentry->d_sb->s_lru_d, dentry, d_lru);
758 spin_unlock(&dentry->d_sb->s_lru_lock);
760 /* and make sure it wasn't USED, then UNUSED again */
761 /* TODO: think about issues with this */
762 warn("This should be rare. Tell brho this happened.");
765 spin_unlock(&dentry->d_lock);
768 /* Called when we really dealloc and get rid of a dentry (like when it is
769 * removed from the dcache, either for memory or correctness reasons)
771 * This has to handle two types of dentries: full ones (ones that had been used)
772 * and ones that had been just for lookups - hence the check for d_inode.
774 * Note that dentries pin and kref their inodes. When all the dentries are
775 * gone, we want the inode to be released via kref. The inode has internal /
776 * weak references to the dentry, which are not refcounted. */
777 void __dentry_free(struct dentry *dentry)
780 printd("Freeing dentry %p: %s\n", dentry, dentry->d_name.name);
781 assert(dentry->d_op); /* catch bugs. a while back, some lacked d_op */
782 dentry->d_op->d_release(dentry);
783 /* TODO: check/test the boundaries on this. */
784 if (dentry->d_name.len > DNAME_INLINE_LEN)
785 kfree((void*)dentry->d_name.name);
786 kref_put(&dentry->d_sb->s_kref);
787 if (dentry->d_parent)
788 kref_put(&dentry->d_parent->d_kref);
789 if (dentry->d_mounted_fs)
790 kref_put(&dentry->d_mounted_fs->mnt_kref);
791 if (dentry->d_inode) {
792 TAILQ_REMOVE(&dentry->d_inode->i_dentry, dentry, d_alias);
793 kref_put(&dentry->d_inode->i_kref); /* dentries kref inodes */
795 kmem_cache_free(dentry_kcache, dentry);
798 /* Looks up the dentry for the given path, returning a refcnt'd dentry (or 0).
799 * Permissions are applied for the current user, which is quite a broken system
800 * at the moment. Flags are lookup flags. */
801 struct dentry *lookup_dentry(char *path, int flags)
803 struct dentry *dentry;
804 struct nameidata nd_r = {0}, *nd = &nd_r;
807 error = path_lookup(path, flags, nd);
814 kref_get(&dentry->d_kref, 1);
819 /* Get a dentry from the dcache. At a minimum, we need the name hash and parent
820 * in what_i_want, though most uses will probably be from a get_dentry() call.
821 * We pass in the SB in the off chance that we don't want to use a get'd dentry.
823 * The unusual variable name (instead of just "key" or something) is named after
824 * ex-SPC Castro's porn folder. Caller deals with the memory for what_i_want.
826 * If the dentry is negative, we don't return the actual result - instead, we
827 * set the negative flag in 'what i want'. The reason is we don't want to
828 * kref_get() and then immediately put (causing dentry_release()). This also
829 * means that dentry_release() should never get someone who wasn't USED (barring
830 * the race, which it handles). And we don't need to ever have a dentry set as
831 * USED and NEGATIVE (which is always wrong, but would be needed for a cleaner
834 * This is where we do the "kref resurrection" - we are returning a kref'd
835 * object, even if it wasn't kref'd before. This means the dcache does NOT hold
836 * krefs (it is a weak/internal ref), but it is a source of kref generation. We
837 * sync up with the possible freeing of the dentry by locking the table. See
838 * Doc/kref for more info. */
839 struct dentry *dcache_get(struct super_block *sb, struct dentry *what_i_want)
841 struct dentry *found;
842 /* This lock protects the hash, as well as ensures the returned object
843 * doesn't get deleted/freed out from under us */
844 spin_lock(&sb->s_dcache_lock);
845 found = hashtable_search(sb->s_dcache, what_i_want);
847 if (found->d_flags & DENTRY_NEGATIVE) {
848 what_i_want->d_flags |= DENTRY_NEGATIVE;
849 spin_unlock(&sb->s_dcache_lock);
852 spin_lock(&found->d_lock);
853 __kref_get(&found->d_kref, 1); /* prob could be done outside the lock*/
854 /* If we're here (after kreffing) and it is not USED, we are the one who
855 * should resurrect */
856 if (!(found->d_flags & DENTRY_USED)) {
857 found->d_flags |= DENTRY_USED;
858 spin_lock(&sb->s_lru_lock);
859 TAILQ_REMOVE(&sb->s_lru_d, found, d_lru);
860 spin_unlock(&sb->s_lru_lock);
862 spin_unlock(&found->d_lock);
864 spin_unlock(&sb->s_dcache_lock);
868 /* Adds a dentry to the dcache. Note the *dentry is both the key and the value.
869 * If the value was already in there (which can happen iff it was negative), for
870 * now we'll remove it and put the new one in there. */
871 void dcache_put(struct super_block *sb, struct dentry *key_val)
875 spin_lock(&sb->s_dcache_lock);
876 old = hashtable_remove(sb->s_dcache, key_val);
877 /* if it is old and non-negative, our caller lost a race with someone else
878 * adding the dentry. but since we yanked it out, like a bunch of idiots,
879 * we still have to put it back. should be fairly rare. */
880 if (old && (old->d_flags & DENTRY_NEGATIVE)) {
881 /* This is possible, but rare for now (about to be put on the LRU) */
882 assert(!(old->d_flags & DENTRY_USED));
883 assert(!kref_refcnt(&old->d_kref));
884 spin_lock(&sb->s_lru_lock);
885 TAILQ_REMOVE(&sb->s_lru_d, old, d_lru);
886 spin_unlock(&sb->s_lru_lock);
887 /* TODO: this seems suspect. isn't this the same memory as key_val?
888 * in which case, we just adjust the flags (remove NEG) and reinsert? */
889 assert(old != key_val); // checking TODO comment
892 /* this returns 0 on failure (TODO: Fix this ghetto shit) */
893 retval = hashtable_insert(sb->s_dcache, key_val, key_val);
895 spin_unlock(&sb->s_dcache_lock);
898 /* Will remove and return the dentry. Caller deallocs the key, but the retval
899 * won't have a reference. * Returns 0 if it wasn't found. Callers can't
900 * assume much - they should not use the reference they *get back*, (if they
901 * already had one for key, they can use that). There may be other users out
903 struct dentry *dcache_remove(struct super_block *sb, struct dentry *key)
905 struct dentry *retval;
906 spin_lock(&sb->s_dcache_lock);
907 retval = hashtable_remove(sb->s_dcache, key);
908 spin_unlock(&sb->s_dcache_lock);
912 /* This will clean out the LRU list, which are the unused dentries of the dentry
913 * cache. This will optionally only free the negative ones. Note that we grab
914 * the hash lock for the time we traverse the LRU list - this prevents someone
915 * from getting a kref from the dcache, which could cause us trouble (we rip
916 * someone off the list, who isn't unused, and they try to rip them off the
918 void dcache_prune(struct super_block *sb, bool negative_only)
920 struct dentry *d_i, *temp;
921 struct dentry_tailq victims = TAILQ_HEAD_INITIALIZER(victims);
923 spin_lock(&sb->s_dcache_lock);
924 spin_lock(&sb->s_lru_lock);
925 TAILQ_FOREACH_SAFE(d_i, &sb->s_lru_d, d_lru, temp) {
926 if (!(d_i->d_flags & DENTRY_USED)) {
927 if (negative_only && !(d_i->d_flags & DENTRY_NEGATIVE))
929 /* another place where we'd be better off with tools, not sol'ns */
930 hashtable_remove(sb->s_dcache, d_i);
931 TAILQ_REMOVE(&sb->s_lru_d, d_i, d_lru);
932 TAILQ_INSERT_HEAD(&victims, d_i, d_lru);
935 spin_unlock(&sb->s_lru_lock);
936 spin_unlock(&sb->s_dcache_lock);
937 /* Now do the actual freeing, outside of the hash/LRU list locks. This is
938 * necessary since __dentry_free() will decref its parent, which may get
939 * released and try to add itself to the LRU. */
940 TAILQ_FOREACH_SAFE(d_i, &victims, d_lru, temp) {
941 TAILQ_REMOVE(&victims, d_i, d_lru);
942 assert(!kref_refcnt(&d_i->d_kref));
945 /* It is possible at this point that there are new items on the LRU. We
946 * could loop back until that list is empty, if we care about this. */
949 /* Inode Functions */
951 /* Creates and initializes a new inode. Generic fields are filled in.
952 * FS-specific fields are filled in by the callout. Specific fields are filled
953 * in in read_inode() based on what's on the disk for a given i_no, or when the
954 * inode is created (for new objects).
956 * i_no is set by the caller. Note that this means this inode can be for an
957 * inode that is already on disk, or it can be used when creating. */
958 struct inode *get_inode(struct dentry *dentry)
960 struct super_block *sb = dentry->d_sb;
961 /* FS allocs and sets the following: i_op, i_fop, i_pm.pm_op, and any FS
963 struct inode *inode = sb->s_op->alloc_inode(sb);
968 TAILQ_INSERT_HEAD(&sb->s_inodes, inode, i_sb_list); /* weak inode ref */
969 TAILQ_INIT(&inode->i_dentry);
970 TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias); /* weak dentry ref*/
971 /* one for the dentry->d_inode, one passed out */
972 kref_init(&inode->i_kref, inode_release, 2);
973 dentry->d_inode = inode;
974 inode->i_ino = 0; /* set by caller later */
975 inode->i_blksize = sb->s_blocksize;
976 spinlock_init(&inode->i_lock);
977 kref_get(&sb->s_kref, 1); /* could allow the dentry to pin it */
979 inode->i_rdev = 0; /* this has no real meaning yet */
980 inode->i_bdev = sb->s_bdev; /* storing an uncounted ref */
981 inode->i_state = 0; /* need real states, like I_NEW */
982 inode->dirtied_when = 0;
984 atomic_set(&inode->i_writecount, 0);
985 /* Set up the page_map structures. Default is to use the embedded one.
986 * Might push some of this back into specific FSs. For now, the FS tells us
987 * what pm_op they want via i_pm.pm_op, which we set again in pm_init() */
988 inode->i_mapping = &inode->i_pm;
989 pm_init(inode->i_mapping, inode->i_pm.pm_op, inode);
993 /* Helper: loads/ reads in the inode numbered ino and attaches it to dentry */
994 void load_inode(struct dentry *dentry, unsigned long ino)
998 /* look it up in the inode cache first */
999 inode = icache_get(dentry->d_sb, ino);
1001 /* connect the dentry to its inode */
1002 TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias);
1003 dentry->d_inode = inode; /* storing the ref we got from icache_get */
1006 /* otherwise, we need to do it manually */
1007 inode = get_inode(dentry);
1009 dentry->d_sb->s_op->read_inode(inode);
1010 /* TODO: race here, two creators could miss in the cache, and then get here.
1011 * need a way to sync across a blocking call. needs to be either at this
1012 * point in the code or per the ino (dentries could be different) */
1013 icache_put(dentry->d_sb, inode);
1014 kref_put(&inode->i_kref);
1017 /* Helper op, used when creating regular files, directories, symlinks, etc.
1018 * Note we make a distinction between the mode and the file type (for now).
1019 * After calling this, call the FS specific version (create or mkdir), which
1020 * will set the i_ino, the filetype, and do any other FS-specific stuff. Also
1021 * note that a lot of inode stuff was initialized in get_inode/alloc_inode. The
1022 * stuff here is pertinent to the specific creator (user), mode, and time. Also
1023 * note we don't pass this an nd, like Linux does... */
1024 static struct inode *create_inode(struct dentry *dentry, int mode)
1026 struct timespec now = nsec2timespec(epoch_nsec());
1027 /* note it is the i_ino that uniquely identifies a file in the specific
1028 * filesystem. there's a diff between creating an inode (even for an in-use
1029 * ino) and then filling it in, and vs creating a brand new one.
1030 * get_inode() sets it to 0, and it should be filled in later in an
1031 * FS-specific manner. */
1032 struct inode *inode = get_inode(dentry);
1035 inode->i_mode = mode & S_PMASK; /* note that after this, we have no type */
1038 inode->i_blocks = 0;
1039 inode->i_atime.tv_sec = now.tv_sec;
1040 inode->i_ctime.tv_sec = now.tv_sec;
1041 inode->i_mtime.tv_sec = now.tv_sec;
1042 inode->i_atime.tv_nsec = now.tv_nsec;
1043 inode->i_ctime.tv_nsec = now.tv_nsec;
1044 inode->i_mtime.tv_nsec = now.tv_nsec;
1045 inode->i_bdev = inode->i_sb->s_bdev;
1046 /* when we have notions of users, do something here: */
1052 /* Create a new disk inode in dir associated with dentry, with the given mode.
1053 * called when creating a regular file. dir is the directory/parent. dentry is
1054 * the dentry of the inode we are creating. Note the lack of the nd... */
1055 int create_file(struct inode *dir, struct dentry *dentry, int mode)
1057 struct inode *new_file = create_inode(dentry, mode);
1060 dir->i_op->create(dir, dentry, mode, 0);
1061 icache_put(new_file->i_sb, new_file);
1062 kref_put(&new_file->i_kref);
1066 /* Creates a new inode for a directory associated with dentry in dir with the
1068 int create_dir(struct inode *dir, struct dentry *dentry, int mode)
1070 struct inode *new_dir = create_inode(dentry, mode);
1073 dir->i_op->mkdir(dir, dentry, mode);
1074 dir->i_nlink++; /* Directories get a hardlink for every child dir */
1075 /* Make sure my parent tracks me. This is okay, since no directory (dir)
1076 * can have more than one dentry */
1077 struct dentry *parent = TAILQ_FIRST(&dir->i_dentry);
1078 assert(parent && parent == TAILQ_LAST(&dir->i_dentry, dentry_tailq));
1079 /* parent dentry tracks dentry as a subdir, weak reference */
1080 TAILQ_INSERT_TAIL(&parent->d_subdirs, dentry, d_subdirs_link);
1081 icache_put(new_dir->i_sb, new_dir);
1082 kref_put(&new_dir->i_kref);
1086 /* Creates a new inode for a symlink associated with dentry in dir, containing
1087 * the symlink symname */
1088 int create_symlink(struct inode *dir, struct dentry *dentry,
1089 const char *symname, int mode)
1091 struct inode *new_sym = create_inode(dentry, mode);
1094 dir->i_op->symlink(dir, dentry, symname);
1095 icache_put(new_sym->i_sb, new_sym);
1096 kref_put(&new_sym->i_kref);
1100 /* Returns 0 if the given mode is acceptable for the inode, and an appropriate
1101 * error code if not. Needs to be writen, based on some sensible rules, and
1102 * will also probably use 'current' */
1103 int check_perms(struct inode *inode, int access_mode)
1105 return 0; /* anything goes! */
1108 /* Called after all external refs are gone to clean up the inode. Once this is
1109 * called, all dentries pointing here are already done (one of them triggered
1110 * this via kref_put(). */
1111 void inode_release(struct kref *kref)
1113 struct inode *inode = container_of(kref, struct inode, i_kref);
1114 TAILQ_REMOVE(&inode->i_sb->s_inodes, inode, i_sb_list);
1115 icache_remove(inode->i_sb, inode->i_ino);
1116 /* Might need to write back or delete the file/inode */
1117 if (inode->i_nlink) {
1118 if (inode->i_state & I_STATE_DIRTY)
1119 inode->i_sb->s_op->write_inode(inode, TRUE);
1121 inode->i_sb->s_op->delete_inode(inode);
1123 if (S_ISFIFO(inode->i_mode)) {
1124 page_decref(kva2page(inode->i_pipe->p_buf));
1125 kfree(inode->i_pipe);
1128 // kref_put(inode->i_bdev->kref); /* assuming it's a bdev, could be a pipe*/
1129 /* Either way, we dealloc the in-memory version */
1130 inode->i_sb->s_op->dealloc_inode(inode); /* FS-specific clean-up */
1131 kref_put(&inode->i_sb->s_kref);
1132 /* TODO: clean this up */
1133 assert(inode->i_mapping == &inode->i_pm);
1134 kmem_cache_free(inode_kcache, inode);
1137 /* Fills in kstat with the stat information for the inode */
1138 void stat_inode(struct inode *inode, struct kstat *kstat)
1140 kstat->st_dev = inode->i_sb->s_dev;
1141 kstat->st_ino = inode->i_ino;
1142 kstat->st_mode = inode->i_mode;
1143 kstat->st_nlink = inode->i_nlink;
1144 kstat->st_uid = inode->i_uid;
1145 kstat->st_gid = inode->i_gid;
1146 kstat->st_rdev = inode->i_rdev;
1147 kstat->st_size = inode->i_size;
1148 kstat->st_blksize = inode->i_blksize;
1149 kstat->st_blocks = inode->i_blocks;
1150 kstat->st_atim = inode->i_atime;
1151 kstat->st_mtim = inode->i_mtime;
1152 kstat->st_ctim = inode->i_ctime;
1155 void print_kstat(struct kstat *kstat)
1157 printk("kstat info for %p:\n", kstat);
1158 printk("\tst_dev : %p\n", kstat->st_dev);
1159 printk("\tst_ino : %p\n", kstat->st_ino);
1160 printk("\tst_mode : %p\n", kstat->st_mode);
1161 printk("\tst_nlink : %p\n", kstat->st_nlink);
1162 printk("\tst_uid : %p\n", kstat->st_uid);
1163 printk("\tst_gid : %p\n", kstat->st_gid);
1164 printk("\tst_rdev : %p\n", kstat->st_rdev);
1165 printk("\tst_size : %p\n", kstat->st_size);
1166 printk("\tst_blksize: %p\n", kstat->st_blksize);
1167 printk("\tst_blocks : %p\n", kstat->st_blocks);
1168 printk("\tst_atime : %p\n", kstat->st_atim);
1169 printk("\tst_mtime : %p\n", kstat->st_mtim);
1170 printk("\tst_ctime : %p\n", kstat->st_ctim);
1173 /* Inode Cache management. In general, search on the ino, get a refcnt'd value
1174 * back. Remove does not give you a reference back - it should only be called
1175 * in inode_release(). */
1176 struct inode *icache_get(struct super_block *sb, unsigned long ino)
1178 /* This is the same style as in pid2proc, it's the "safely create a strong
1179 * reference from a weak one, so long as other strong ones exist" pattern */
1180 spin_lock(&sb->s_icache_lock);
1181 struct inode *inode = hashtable_search(sb->s_icache, (void*)ino);
1183 if (!kref_get_not_zero(&inode->i_kref, 1))
1185 spin_unlock(&sb->s_icache_lock);
1189 void icache_put(struct super_block *sb, struct inode *inode)
1191 spin_lock(&sb->s_icache_lock);
1192 /* there's a race in load_ino() that could trigger this */
1193 assert(!hashtable_search(sb->s_icache, (void*)inode->i_ino));
1194 hashtable_insert(sb->s_icache, (void*)inode->i_ino, inode);
1195 spin_unlock(&sb->s_icache_lock);
1198 struct inode *icache_remove(struct super_block *sb, unsigned long ino)
1200 struct inode *inode;
1201 /* Presumably these hashtable removals could be easier since callers
1202 * actually know who they are (same with the pid2proc hash) */
1203 spin_lock(&sb->s_icache_lock);
1204 inode = hashtable_remove(sb->s_icache, (void*)ino);
1205 spin_unlock(&sb->s_icache_lock);
1206 assert(inode && !kref_refcnt(&inode->i_kref));
1210 /* File functions */
1212 /* Read count bytes from the file into buf, starting at *offset, which is
1213 * increased accordingly, returning the number of bytes transfered. Most
1214 * filesystems will use this function for their f_op->read.
1215 * Note, this uses the page cache. */
1216 ssize_t generic_file_read(struct file *file, char *buf, size_t count,
1222 unsigned long first_idx, last_idx;
1225 /* read in offset, in case of a concurrent reader/writer, so we don't screw
1226 * up our math for count, the idxs, etc. */
1227 off64_t orig_off = ACCESS_ONCE(*offset);
1229 /* Consider pushing some error checking higher in the VFS */
1232 if (!(file->f_flags & O_READ)) {
1236 if (orig_off >= file->f_dentry->d_inode->i_size)
1238 /* Make sure we don't go past the end of the file */
1239 if (orig_off + count > file->f_dentry->d_inode->i_size) {
1240 count = file->f_dentry->d_inode->i_size - orig_off;
1242 assert((long)count > 0);
1243 page_off = orig_off & (PGSIZE - 1);
1244 first_idx = orig_off >> PGSHIFT;
1245 last_idx = (orig_off + count) >> PGSHIFT;
1246 buf_end = buf + count;
1247 /* For each file page, make sure it's in the page cache, then copy it out.
1248 * TODO: will probably need to consider concurrently truncated files here.*/
1249 for (int i = first_idx; i <= last_idx; i++) {
1250 error = pm_load_page(file->f_mapping, i, &page);
1251 assert(!error); /* TODO: handle ENOMEM and friends */
1252 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
1253 /* TODO: (KFOP) Probably shouldn't do this. Either memcpy directly, or
1254 * split out the is_user_r(w)addr from copy_{to,from}_user() */
1255 if (!is_ktask(per_cpu_info[core_id()].cur_kthread))
1256 memcpy_to_user(current, buf, page2kva(page) + page_off, copy_amt);
1258 memcpy(buf, page2kva(page) + page_off, copy_amt);
1261 pm_put_page(page); /* it's still in the cache, we just don't need it */
1263 assert(buf == buf_end);
1264 /* could have concurrent file ops that screw with offset, so userspace isn't
1265 * safe. but at least it'll be a value that one of the concurrent ops could
1266 * have produced (compared to *offset_changed_concurrently += count. */
1267 *offset = orig_off + count;
1271 /* Write count bytes from buf to the file, starting at *offset, which is
1272 * increased accordingly, returning the number of bytes transfered. Most
1273 * filesystems will use this function for their f_op->write. Note, this uses
1276 * Changes don't get flushed to disc til there is an fsync, page cache eviction,
1277 * or other means of trying to writeback the pages. */
1278 ssize_t generic_file_write(struct file *file, const char *buf, size_t count,
1284 unsigned long first_idx, last_idx;
1286 const char *buf_end;
1287 off64_t orig_off = ACCESS_ONCE(*offset);
1289 /* Consider pushing some error checking higher in the VFS */
1292 if (!(file->f_flags & O_WRITE)) {
1296 if (file->f_flags & O_APPEND) {
1297 spin_lock(&file->f_dentry->d_inode->i_lock);
1298 orig_off = file->f_dentry->d_inode->i_size;
1299 /* setting the filesize here, instead of during the extend-check, since
1300 * we need to atomically reserve space and set our write position. */
1301 file->f_dentry->d_inode->i_size += count;
1302 spin_unlock(&file->f_dentry->d_inode->i_lock);
1304 if (orig_off + count > file->f_dentry->d_inode->i_size) {
1305 /* lock for writes to i_size. we allow lockless reads. recheck
1306 * i_size in case of concurrent writers since our orig check. */
1307 spin_lock(&file->f_dentry->d_inode->i_lock);
1308 if (orig_off + count > file->f_dentry->d_inode->i_size)
1309 file->f_dentry->d_inode->i_size = orig_off + count;
1310 spin_unlock(&file->f_dentry->d_inode->i_lock);
1313 page_off = orig_off & (PGSIZE - 1);
1314 first_idx = orig_off >> PGSHIFT;
1315 last_idx = (orig_off + count) >> PGSHIFT;
1316 buf_end = buf + count;
1317 /* For each file page, make sure it's in the page cache, then write it.*/
1318 for (int i = first_idx; i <= last_idx; i++) {
1319 error = pm_load_page(file->f_mapping, i, &page);
1320 assert(!error); /* TODO: handle ENOMEM and friends */
1321 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
1322 /* TODO: (UMEM) (KFOP) think about this. */
1323 if (!is_ktask(per_cpu_info[core_id()].cur_kthread))
1324 memcpy_from_user(current, page2kva(page) + page_off, buf, copy_amt);
1326 memcpy(page2kva(page) + page_off, buf, copy_amt);
1329 atomic_or(&page->pg_flags, PG_DIRTY);
1330 pm_put_page(page); /* it's still in the cache, we just don't need it */
1332 assert(buf == buf_end);
1333 *offset = orig_off + count;
1337 /* Directories usually use this for their read method, which is the way glibc
1338 * currently expects us to do a readdir (short of doing linux's getdents). Will
1339 * probably need work, based on whatever real programs want. */
1340 ssize_t generic_dir_read(struct file *file, char *u_buf, size_t count,
1343 struct kdirent dir_r = {0}, *dirent = &dir_r;
1345 size_t amt_copied = 0;
1346 char *buf_end = u_buf + count;
1348 if (!S_ISDIR(file->f_dentry->d_inode->i_mode)) {
1354 if (!(file->f_flags & O_READ)) {
1358 /* start readdir from where it left off: */
1359 dirent->d_off = *offset;
1361 u_buf + sizeof(struct kdirent) <= buf_end;
1362 u_buf += sizeof(struct kdirent)) {
1363 /* TODO: UMEM/KFOP (pin the u_buf in the syscall, ditch the local copy,
1364 * get rid of this memcpy and reliance on current, etc). Might be
1365 * tricky with the dirent->d_off and trust issues */
1366 retval = file->f_op->readdir(file, dirent);
1371 /* Slight info exposure: could be extra crap after the name in the
1372 * dirent (like the name of a deleted file) */
1373 if (!is_ktask(per_cpu_info[core_id()].cur_kthread))
1374 memcpy_to_user(current, u_buf, dirent, sizeof(struct dirent));
1376 memcpy(u_buf, dirent, sizeof(struct dirent));
1377 amt_copied += sizeof(struct dirent);
1378 /* 0 signals end of directory */
1382 /* Next time read is called, we pick up where we left off */
1383 *offset = dirent->d_off; /* UMEM */
1384 /* important to tell them how much they got. they often keep going til they
1385 * get 0 back (in the case of ls). It's also how much has been read, but it
1386 * isn't how much the f_pos has moved (which is opaque to the VFS). */
1390 /* Opens the file, using permissions from current for lack of a better option.
1391 * It will attempt to create the file if it does not exist and O_CREAT is
1392 * specified. This will return 0 on failure, and set errno. TODO: There's some
1393 * stuff that we don't do, esp related file truncating/creation. flags are for
1394 * opening, the mode is for creating. The flags related to how to create
1395 * (O_CREAT_FLAGS) are handled in this function, not in create_file().
1397 * It's tempting to split this into a do_file_create and a do_file_open, based
1398 * on the O_CREAT flag, but the O_CREAT flag can be ignored if the file exists
1399 * already and O_EXCL isn't specified. We could have open call create if it
1400 * fails, but for now we'll keep it as is. */
1401 struct file *do_file_open(char *path, int flags, int mode)
1403 struct file *file = 0;
1404 struct dentry *file_d;
1405 struct inode *parent_i;
1406 struct nameidata nd_r = {0}, *nd = &nd_r;
1408 unsigned long nr_pages;
1410 /* The file might exist, lets try to just open it right away */
1411 nd->intent = LOOKUP_OPEN;
1412 error = path_lookup(path, LOOKUP_FOLLOW, nd);
1414 if (S_ISDIR(nd->dentry->d_inode->i_mode) && (flags & O_WRITE)) {
1418 /* Also need to make sure we didn't want to O_EXCL create */
1419 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1423 file_d = nd->dentry;
1424 kref_get(&file_d->d_kref, 1);
1427 if (!(flags & O_CREAT)) {
1431 /* So it didn't already exist, release the path from the previous lookup,
1432 * and then we try to create it. */
1434 /* get the parent, following links. this means you get the parent of the
1435 * final link (which may not be in 'path' in the first place. */
1436 nd->intent = LOOKUP_CREATE;
1437 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1442 /* see if the target is there (shouldn't be), and handle accordingly */
1443 file_d = do_lookup(nd->dentry, nd->last.name);
1445 if (!(flags & O_CREAT)) {
1446 warn("Extremely unlikely race, probably a bug");
1450 /* Create the inode/file. get a fresh dentry too: */
1451 file_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1454 parent_i = nd->dentry->d_inode;
1455 /* Note that the mode technically should only apply to future opens,
1456 * but we apply it immediately. */
1457 if (create_file(parent_i, file_d, mode)) /* sets errno */
1459 dcache_put(file_d->d_sb, file_d);
1460 } else { /* something already exists */
1461 /* this can happen due to concurrent access, but needs to be thought
1463 panic("File shouldn't be here!");
1464 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1465 /* wanted to create, not open, bail out */
1471 /* now open the file (freshly created or if it already existed). At this
1472 * point, file_d is a refcnt'd dentry, regardless of which branch we took.*/
1473 if (flags & O_TRUNC) {
1474 spin_lock(&file_d->d_inode->i_lock);
1475 nr_pages = ROUNDUP(file_d->d_inode->i_size, PGSIZE) >> PGSHIFT;
1476 file_d->d_inode->i_size = 0;
1477 spin_unlock(&file_d->d_inode->i_lock);
1478 pm_remove_contig(file_d->d_inode->i_mapping, 0, nr_pages);
1480 file = dentry_open(file_d, flags); /* sets errno */
1481 /* Note the fall through to the exit paths. File is 0 by default and if
1482 * dentry_open fails. */
1484 kref_put(&file_d->d_kref);
1490 /* Path is the location of the symlink, sometimes called the "new path", and
1491 * symname is who we link to, sometimes called the "old path". */
1492 int do_symlink(char *path, const char *symname, int mode)
1494 struct dentry *sym_d;
1495 struct inode *parent_i;
1496 struct nameidata nd_r = {0}, *nd = &nd_r;
1500 nd->intent = LOOKUP_CREATE;
1501 /* get the parent, but don't follow links */
1502 error = path_lookup(path, LOOKUP_PARENT, nd);
1507 /* see if the target is already there, handle accordingly */
1508 sym_d = do_lookup(nd->dentry, nd->last.name);
1513 /* Doesn't already exist, let's try to make it: */
1514 sym_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1517 parent_i = nd->dentry->d_inode;
1518 if (create_symlink(parent_i, sym_d, symname, mode))
1520 dcache_put(sym_d->d_sb, sym_d);
1521 retval = 0; /* Note the fall through to the exit paths */
1523 kref_put(&sym_d->d_kref);
1529 /* Makes a hard link for the file behind old_path to new_path */
1530 int do_link(char *old_path, char *new_path)
1532 struct dentry *link_d, *old_d;
1533 struct inode *inode, *parent_dir;
1534 struct nameidata nd_r = {0}, *nd = &nd_r;
1538 nd->intent = LOOKUP_CREATE;
1539 /* get the absolute parent of the new_path */
1540 error = path_lookup(new_path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1545 parent_dir = nd->dentry->d_inode;
1546 /* see if the new target is already there, handle accordingly */
1547 link_d = do_lookup(nd->dentry, nd->last.name);
1552 /* Doesn't already exist, let's try to make it. Still need to stitch it to
1553 * an inode and set its FS-specific stuff after this.*/
1554 link_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1557 /* Now let's get the old_path target */
1558 old_d = lookup_dentry(old_path, LOOKUP_FOLLOW);
1559 if (!old_d) /* errno set by lookup_dentry */
1561 /* For now, can only link to files */
1562 if (!S_ISREG(old_d->d_inode->i_mode)) {
1566 /* Must be on the same FS */
1567 if (old_d->d_sb != link_d->d_sb) {
1571 /* Do whatever FS specific stuff there is first (which is also a chance to
1573 error = parent_dir->i_op->link(old_d, parent_dir, link_d);
1578 /* Finally stitch it up */
1579 inode = old_d->d_inode;
1580 kref_get(&inode->i_kref, 1);
1581 link_d->d_inode = inode;
1583 TAILQ_INSERT_TAIL(&inode->i_dentry, link_d, d_alias); /* weak ref */
1584 dcache_put(link_d->d_sb, link_d);
1585 retval = 0; /* Note the fall through to the exit paths */
1587 kref_put(&old_d->d_kref);
1589 kref_put(&link_d->d_kref);
1595 /* Unlinks path from the directory tree. Read the Documentation for more info.
1597 int do_unlink(char *path)
1599 struct dentry *dentry;
1600 struct inode *parent_dir;
1601 struct nameidata nd_r = {0}, *nd = &nd_r;
1605 /* get the parent of the target, and don't follow a final link */
1606 error = path_lookup(path, LOOKUP_PARENT, nd);
1611 parent_dir = nd->dentry->d_inode;
1612 /* make sure the target is there */
1613 dentry = do_lookup(nd->dentry, nd->last.name);
1618 /* Make sure the target is not a directory */
1619 if (S_ISDIR(dentry->d_inode->i_mode)) {
1623 /* Remove the dentry from its parent */
1624 error = parent_dir->i_op->unlink(parent_dir, dentry);
1629 /* Now that our parent doesn't track us, we need to make sure we aren't
1630 * findable via the dentry cache. DYING, so we will be freed in
1631 * dentry_release() */
1632 dentry->d_flags |= DENTRY_DYING;
1633 dcache_remove(dentry->d_sb, dentry);
1634 dentry->d_inode->i_nlink--; /* TODO: race here, esp with a decref */
1635 /* At this point, the dentry is unlinked from the FS, and the inode has one
1636 * less link. When the in-memory objects (dentry, inode) are going to be
1637 * released (after all open files are closed, and maybe after entries are
1638 * evicted from the cache), then nlinks will get checked and the FS-file
1639 * will get removed from the disk */
1640 retval = 0; /* Note the fall through to the exit paths */
1642 kref_put(&dentry->d_kref);
1648 /* Checks to see if path can be accessed via mode. Need to actually send the
1649 * mode along somehow, so this doesn't do much now. This is an example of
1650 * decent error propagation from the lower levels via int retvals. */
1651 int do_access(char *path, int mode)
1653 struct nameidata nd_r = {0}, *nd = &nd_r;
1655 nd->intent = LOOKUP_ACCESS;
1656 retval = path_lookup(path, 0, nd);
1661 int do_file_chmod(struct file *file, int mode)
1663 int old_mode_ftype = file->f_dentry->d_inode->i_mode & __S_IFMT;
1665 /* TODO: when we have notions of uid, check for the proc's uid */
1666 if (file->f_dentry->d_inode->i_uid != UID_OF_ME)
1670 file->f_dentry->d_inode->i_mode = (mode & S_PMASK) | old_mode_ftype;
1674 /* Make a directory at path with mode. Returns -1 and sets errno on errors */
1675 int do_mkdir(char *path, int mode)
1677 struct dentry *dentry;
1678 struct inode *parent_i;
1679 struct nameidata nd_r = {0}, *nd = &nd_r;
1683 /* The dir might exist and might be /, so we can't look for the parent */
1684 nd->intent = LOOKUP_OPEN;
1685 error = path_lookup(path, LOOKUP_FOLLOW, nd);
1691 nd->intent = LOOKUP_CREATE;
1692 /* get the parent, but don't follow links */
1693 error = path_lookup(path, LOOKUP_PARENT, nd);
1698 /* Doesn't already exist, let's try to make it: */
1699 dentry = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1702 parent_i = nd->dentry->d_inode;
1703 if (create_dir(parent_i, dentry, mode))
1705 dcache_put(dentry->d_sb, dentry);
1706 retval = 0; /* Note the fall through to the exit paths */
1708 kref_put(&dentry->d_kref);
1714 int do_rmdir(char *path)
1716 struct dentry *dentry;
1717 struct inode *parent_i;
1718 struct nameidata nd_r = {0}, *nd = &nd_r;
1722 /* get the parent, following links (probably want this), and we must get a
1723 * directory. Note, current versions of path_lookup can't handle both
1724 * PARENT and DIRECTORY, at least, it doesn't check that *path is a
1726 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW | LOOKUP_DIRECTORY,
1732 /* make sure the target is already there, handle accordingly */
1733 dentry = do_lookup(nd->dentry, nd->last.name);
1738 if (!S_ISDIR(dentry->d_inode->i_mode)) {
1742 if (dentry->d_mount_point) {
1746 /* TODO: make sure we aren't a mount or processes root (EBUSY) */
1747 /* Now for the removal. the FSs will check if they are empty */
1748 parent_i = nd->dentry->d_inode;
1749 error = parent_i->i_op->rmdir(parent_i, dentry);
1754 /* Now that our parent doesn't track us, we need to make sure we aren't
1755 * findable via the dentry cache. DYING, so we will be freed in
1756 * dentry_release() */
1757 dentry->d_flags |= DENTRY_DYING;
1758 dcache_remove(dentry->d_sb, dentry);
1759 /* Decref ourselves, so inode_release() knows we are done */
1760 dentry->d_inode->i_nlink--;
1761 TAILQ_REMOVE(&nd->dentry->d_subdirs, dentry, d_subdirs_link);
1762 parent_i->i_nlink--; /* TODO: race on this, esp since its a decref */
1763 /* we still have d_parent and a kref on our parent, which will go away when
1764 * the in-memory dentry object goes away. */
1765 retval = 0; /* Note the fall through to the exit paths */
1767 kref_put(&dentry->d_kref);
1773 /* Pipes: Doing a simple buffer with reader and writer offsets. Size is power
1774 * of two, so we can easily compute its status and whatnot. */
1776 #define PIPE_SZ (1 << PGSHIFT)
1778 static size_t pipe_get_rd_idx(struct pipe_inode_info *pii)
1780 return pii->p_rd_off & (PIPE_SZ - 1);
1783 static size_t pipe_get_wr_idx(struct pipe_inode_info *pii)
1786 return pii->p_wr_off & (PIPE_SZ - 1);
1789 static bool pipe_is_empty(struct pipe_inode_info *pii)
1791 return __ring_empty(pii->p_wr_off, pii->p_rd_off);
1794 static bool pipe_is_full(struct pipe_inode_info *pii)
1796 return __ring_full(PIPE_SZ, pii->p_wr_off, pii->p_rd_off);
1799 static size_t pipe_nr_full(struct pipe_inode_info *pii)
1801 return __ring_nr_full(pii->p_wr_off, pii->p_rd_off);
1804 static size_t pipe_nr_empty(struct pipe_inode_info *pii)
1806 return __ring_nr_empty(PIPE_SZ, pii->p_wr_off, pii->p_rd_off);
1809 ssize_t pipe_file_read(struct file *file, char *buf, size_t count,
1812 struct pipe_inode_info *pii = file->f_dentry->d_inode->i_pipe;
1813 size_t copy_amt, amt_copied = 0;
1815 cv_lock(&pii->p_cv);
1816 while (pipe_is_empty(pii)) {
1817 /* We wait til the pipe is drained before sending EOF if there are no
1818 * writers (instead of aborting immediately) */
1819 if (!pii->p_nr_writers) {
1820 cv_unlock(&pii->p_cv);
1823 if (file->f_flags & O_NONBLOCK) {
1824 cv_unlock(&pii->p_cv);
1828 cv_wait(&pii->p_cv);
1831 /* We might need to wrap-around with our copy, so we'll do the copy in two
1832 * passes. This will copy up to the end of the buffer, then on the next
1833 * pass will copy the rest to the beginning of the buffer (if necessary) */
1834 for (int i = 0; i < 2; i++) {
1835 copy_amt = MIN(PIPE_SZ - pipe_get_rd_idx(pii),
1836 MIN(pipe_nr_full(pii), count));
1837 assert(current); /* shouldn't pipe from the kernel */
1838 memcpy_to_user(current, buf, pii->p_buf + pipe_get_rd_idx(pii),
1842 pii->p_rd_off += copy_amt;
1843 amt_copied += copy_amt;
1845 /* Just using one CV for both readers and writers. We should rarely have
1846 * multiple readers or writers. */
1848 __cv_broadcast(&pii->p_cv);
1849 cv_unlock(&pii->p_cv);
1853 /* Note: we're not dealing with PIPE_BUF and minimum atomic chunks, unless I
1855 ssize_t pipe_file_write(struct file *file, const char *buf, size_t count,
1858 struct pipe_inode_info *pii = file->f_dentry->d_inode->i_pipe;
1859 size_t copy_amt, amt_copied = 0;
1861 cv_lock(&pii->p_cv);
1862 /* Write aborts right away if there are no readers, regardless of pipe
1864 if (!pii->p_nr_readers) {
1865 cv_unlock(&pii->p_cv);
1869 while (pipe_is_full(pii)) {
1870 if (file->f_flags & O_NONBLOCK) {
1871 cv_unlock(&pii->p_cv);
1875 cv_wait(&pii->p_cv);
1877 /* Still need to check in the loop, in case the last reader left while
1879 if (!pii->p_nr_readers) {
1880 cv_unlock(&pii->p_cv);
1885 /* We might need to wrap-around with our copy, so we'll do the copy in two
1886 * passes. This will copy up to the end of the buffer, then on the next
1887 * pass will copy the rest to the beginning of the buffer (if necessary) */
1888 for (int i = 0; i < 2; i++) {
1889 copy_amt = MIN(PIPE_SZ - pipe_get_wr_idx(pii),
1890 MIN(pipe_nr_empty(pii), count));
1891 assert(current); /* shouldn't pipe from the kernel */
1892 memcpy_from_user(current, pii->p_buf + pipe_get_wr_idx(pii), buf,
1896 pii->p_wr_off += copy_amt;
1897 amt_copied += copy_amt;
1899 /* Just using one CV for both readers and writers. We should rarely have
1900 * multiple readers or writers. */
1902 __cv_broadcast(&pii->p_cv);
1903 cv_unlock(&pii->p_cv);
1907 /* In open and release, we need to track the number of readers and writers,
1908 * which we can differentiate by the file flags. */
1909 int pipe_open(struct inode *inode, struct file *file)
1911 struct pipe_inode_info *pii = inode->i_pipe;
1912 cv_lock(&pii->p_cv);
1913 /* Ugliness due to not using flags for O_RDONLY and friends... */
1914 if (file->f_mode == S_IRUSR) {
1915 pii->p_nr_readers++;
1916 } else if (file->f_mode == S_IWUSR) {
1917 pii->p_nr_writers++;
1919 warn("Bad pipe file flags 0x%x\n", file->f_flags);
1921 cv_unlock(&pii->p_cv);
1925 int pipe_release(struct inode *inode, struct file *file)
1927 struct pipe_inode_info *pii = inode->i_pipe;
1928 cv_lock(&pii->p_cv);
1929 /* Ugliness due to not using flags for O_RDONLY and friends... */
1930 if (file->f_mode == S_IRUSR) {
1931 pii->p_nr_readers--;
1932 } else if (file->f_mode == S_IWUSR) {
1933 pii->p_nr_writers--;
1935 warn("Bad pipe file flags 0x%x\n", file->f_flags);
1937 /* need to wake up any sleeping readers/writers, since we might be done */
1938 __cv_broadcast(&pii->p_cv);
1939 cv_unlock(&pii->p_cv);
1943 struct file_operations pipe_f_op = {
1944 .read = pipe_file_read,
1945 .write = pipe_file_write,
1947 .release = pipe_release,
1951 void pipe_debug(struct file *f)
1953 struct pipe_inode_info *pii = f->f_dentry->d_inode->i_pipe;
1955 printk("PIPE %p\n", pii);
1956 printk("\trdoff %p\n", pii->p_rd_off);
1957 printk("\twroff %p\n", pii->p_wr_off);
1958 printk("\tnr_rds %d\n", pii->p_nr_readers);
1959 printk("\tnr_wrs %d\n", pii->p_nr_writers);
1960 printk("\tcv waiters %d\n", pii->p_cv.nr_waiters);
1964 /* General plan: get a dentry/inode to represent the pipe. We'll alloc it from
1965 * the default_ns SB, but won't actually link it anywhere. It'll only be held
1966 * alive by the krefs, til all the FDs are closed. */
1967 int do_pipe(struct file **pipe_files, int flags)
1969 struct dentry *pipe_d;
1970 struct inode *pipe_i;
1971 struct file *pipe_f_read, *pipe_f_write;
1972 struct super_block *def_sb = default_ns.root->mnt_sb;
1973 struct pipe_inode_info *pii;
1975 pipe_d = get_dentry(def_sb, 0, "pipe");
1978 pipe_d->d_op = &dummy_d_op;
1979 pipe_i = get_inode(pipe_d);
1981 goto error_post_dentry;
1982 /* preemptively mark the dentry for deletion. we have an unlinked dentry
1983 * right off the bat, held in only by the kref chain (pipe_d is the ref). */
1984 pipe_d->d_flags |= DENTRY_DYING;
1985 /* pipe_d->d_inode still has one ref to pipe_i, keeping the inode alive */
1986 kref_put(&pipe_i->i_kref);
1987 /* init inode fields. note we're using the dummy ops for i_op and d_op */
1988 pipe_i->i_mode = S_IRWXU | S_IRWXG | S_IRWXO;
1989 SET_FTYPE(pipe_i->i_mode, __S_IFIFO); /* using type == FIFO */
1990 pipe_i->i_nlink = 1; /* one for the dentry */
1993 pipe_i->i_size = PGSIZE;
1994 pipe_i->i_blocks = 0;
1995 pipe_i->i_atime.tv_sec = 0;
1996 pipe_i->i_atime.tv_nsec = 0;
1997 pipe_i->i_mtime.tv_sec = 0;
1998 pipe_i->i_mtime.tv_nsec = 0;
1999 pipe_i->i_ctime.tv_sec = 0;
2000 pipe_i->i_ctime.tv_nsec = 0;
2001 pipe_i->i_fs_info = 0;
2002 pipe_i->i_op = &dummy_i_op;
2003 pipe_i->i_fop = &pipe_f_op;
2004 pipe_i->i_socket = FALSE;
2005 /* Actually build the pipe. We're using one page, hanging off the
2006 * pipe_inode_info struct. When we release the inode, we free the pipe
2008 pipe_i->i_pipe = kmalloc(sizeof(struct pipe_inode_info), MEM_WAIT);
2009 pii = pipe_i->i_pipe;
2014 pii->p_buf = kpage_zalloc_addr();
2021 pii->p_nr_readers = 0;
2022 pii->p_nr_writers = 0;
2023 cv_init(&pii->p_cv); /* must do this before dentry_open / pipe_open */
2024 /* Now we have an inode for the pipe. We need two files for the read and
2025 * write ends of the pipe. */
2026 flags &= ~(O_ACCMODE); /* avoid user bugs */
2027 pipe_f_read = dentry_open(pipe_d, flags | O_RDONLY);
2030 pipe_f_write = dentry_open(pipe_d, flags | O_WRONLY);
2033 pipe_files[0] = pipe_f_read;
2034 pipe_files[1] = pipe_f_write;
2038 kref_put(&pipe_f_read->f_kref);
2040 page_decref(kva2page(pii->p_buf));
2042 kfree(pipe_i->i_pipe);
2044 /* We don't need to free the pipe_i; putting the dentry will free it */
2046 /* Note we only free the dentry on failure. */
2047 kref_put(&pipe_d->d_kref);
2051 int do_rename(char *old_path, char *new_path)
2053 struct nameidata nd_old = {0}, *nd_o = &nd_old;
2054 struct nameidata nd_new = {0}, *nd_n = &nd_new;
2055 struct dentry *old_dir_d, *new_dir_d;
2056 struct inode *old_dir_i, *new_dir_i;
2057 struct dentry *old_d, *new_d, *unlink_d;
2060 struct timespec now;
2062 nd_o->intent = LOOKUP_ACCESS; /* maybe, might need another type */
2064 /* get the parent, but don't follow links */
2065 error = path_lookup(old_path, LOOKUP_PARENT | LOOKUP_DIRECTORY, nd_o);
2071 old_dir_d = nd_o->dentry;
2072 old_dir_i = old_dir_d->d_inode;
2074 old_d = do_lookup(old_dir_d, nd_o->last.name);
2081 nd_n->intent = LOOKUP_CREATE;
2082 error = path_lookup(new_path, LOOKUP_PARENT | LOOKUP_DIRECTORY, nd_n);
2086 goto out_paths_and_src;
2088 new_dir_d = nd_n->dentry;
2089 new_dir_i = new_dir_d->d_inode;
2090 /* TODO if new_dir == old_dir, we might be able to simplify things */
2092 if (new_dir_i->i_sb != old_dir_i->i_sb) {
2095 goto out_paths_and_src;
2097 /* TODO: check_perms is lousy, want to just say "writable" here */
2098 if (check_perms(old_dir_i, S_IWUSR) || check_perms(new_dir_i, S_IWUSR)) {
2101 goto out_paths_and_src;
2103 /* TODO: if we're doing a rename that moves a directory, we need to make
2104 * sure the new_path doesn't include the old_path. It's not as simple as
2105 * just checking, since there could be a concurrent rename that breaks the
2106 * check later. e.g. what if new_dir's parent is being moved into a child
2109 * linux has a per-fs rename mutex for these scenarios, so only one can
2110 * proceed at a time. i don't see another way to deal with it either.
2111 * maybe something like flagging all dentries on the new_path with "do not
2114 /* TODO: this is all very racy. right after we do a new_d lookup, someone
2115 * else could create or unlink new_d. need to lock here, or else push this
2118 * For any locking scheme, we probably need to lock both the old and new
2119 * dirs. To prevent deadlock, we need a total ordering of all inodes (or
2120 * dentries, if we locking them instead). inode number or struct inode*
2121 * will work for this. */
2122 new_d = do_lookup(new_dir_d, nd_n->last.name);
2124 if (new_d->d_inode == old_d->d_inode)
2125 goto out_paths_and_refs; /* rename does nothing */
2126 /* TODO: Here's a bunch of other racy checks we need to do, maybe in the
2129 * if src is a dir, dst must be an empty dir if it exists (RACYx2)
2130 * racing on dst being created and it getting new entries
2131 * if src is a file, dst must be a file if it exists (RACY)
2132 * racing on dst being created and still being a file
2133 * racing on dst being unlinked and a new one being added
2135 /* TODO: we should allow empty dirs */
2136 if (S_ISDIR(new_d->d_inode->i_mode)) {
2139 goto out_paths_and_refs;
2141 /* TODO: need this to be atomic with rename */
2142 error = new_dir_i->i_op->unlink(new_dir_i, new_d);
2146 goto out_paths_and_refs;
2148 new_d->d_flags |= DENTRY_DYING;
2149 /* TODO: racy with other lookups on new_d */
2150 dcache_remove(new_d->d_sb, new_d);
2151 new_d->d_inode->i_nlink--; /* TODO: race here, esp with a decref */
2152 kref_put(&new_d->d_kref);
2154 /* new_d is just a vessel for the name. somewhat lousy. */
2155 new_d = get_dentry(new_dir_d->d_sb, new_dir_d, nd_n->last.name);
2157 /* TODO: more races. need to remove old_d from the dcache, since we're
2158 * about to change its parentage. could be readded concurrently. */
2159 dcache_remove(old_dir_d->d_sb, old_d);
2160 error = new_dir_i->i_op->rename(old_dir_i, old_d, new_dir_i, new_d);
2162 /* TODO: oh crap, we already unlinked! now we're screwed, and violated
2163 * our atomicity requirements. */
2164 printk("[kernel] rename failed, you might have lost data\n");
2167 goto out_paths_and_refs;
2170 /* old_dir loses old_d, new_dir gains old_d, renamed to new_d. this is
2171 * particularly cumbersome since there are two levels here: the FS has its
2172 * info about where things are, and the VFS has its dentry tree. and it's
2173 * all racy (TODO). */
2174 dentry_set_name(old_d, new_d->d_name.name);
2175 old_d->d_parent = new_d->d_parent;
2176 if (S_ISDIR(old_d->d_inode->i_mode)) {
2177 TAILQ_REMOVE(&old_dir_d->d_subdirs, old_d, d_subdirs_link);
2178 old_dir_i->i_nlink--; /* TODO: racy, etc */
2179 TAILQ_INSERT_TAIL(&new_dir_d->d_subdirs, old_d, d_subdirs_link);
2180 new_dir_i->i_nlink--; /* TODO: racy, etc */
2183 /* and then the third level: dcache stuff. we could have old versions of
2184 * old_d or negative versions of new_d sitting around. dcache_put should
2185 * replace a potentially negative dentry for new_d (now called old_d) */
2186 dcache_put(old_dir_d->d_sb, old_d);
2188 /* TODO could have a helper for this, but it's going away soon */
2189 now = nsec2timespec(epoch_nsec());
2190 old_dir_i->i_ctime.tv_sec = now.tv_sec;
2191 old_dir_i->i_mtime.tv_sec = now.tv_sec;
2192 old_dir_i->i_ctime.tv_nsec = now.tv_nsec;
2193 old_dir_i->i_mtime.tv_nsec = now.tv_nsec;
2194 new_dir_i->i_ctime.tv_sec = now.tv_sec;
2195 new_dir_i->i_mtime.tv_sec = now.tv_sec;
2196 new_dir_i->i_ctime.tv_nsec = now.tv_nsec;
2197 new_dir_i->i_mtime.tv_nsec = now.tv_nsec;
2201 kref_put(&new_d->d_kref);
2203 kref_put(&old_d->d_kref);
2211 int do_truncate(struct inode *inode, off64_t len)
2214 struct timespec now;
2220 printk("[kernel] truncate for > petabyte, probably a bug\n");
2221 /* continuing, not too concerned. could set EINVAL or EFBIG */
2223 spin_lock(&inode->i_lock);
2224 old_len = inode->i_size;
2225 if (old_len == len) {
2226 spin_unlock(&inode->i_lock);
2229 inode->i_size = len;
2230 /* truncate can't block, since we're holding the spinlock. but it can rely
2231 * on that lock being held */
2232 inode->i_op->truncate(inode);
2233 spin_unlock(&inode->i_lock);
2235 if (old_len < len) {
2236 pm_remove_contig(inode->i_mapping, old_len >> PGSHIFT,
2237 (len >> PGSHIFT) - (old_len >> PGSHIFT));
2239 now = nsec2timespec(epoch_nsec());
2240 inode->i_ctime.tv_sec = now.tv_sec;
2241 inode->i_mtime.tv_sec = now.tv_sec;
2242 inode->i_ctime.tv_nsec = now.tv_nsec;
2243 inode->i_mtime.tv_nsec = now.tv_nsec;
2247 struct file *alloc_file(void)
2249 struct file *file = kmem_cache_alloc(file_kcache, 0);
2254 /* one for the ref passed out*/
2255 kref_init(&file->f_kref, file_release, 1);
2259 /* Opens and returns the file specified by dentry */
2260 struct file *dentry_open(struct dentry *dentry, int flags)
2262 struct inode *inode;
2265 inode = dentry->d_inode;
2266 /* f_mode stores how the OS file is open, which can be more restrictive than
2268 desired_mode = omode_to_rwx(flags & O_ACCMODE);
2269 if (check_perms(inode, desired_mode))
2271 file = alloc_file();
2274 file->f_mode = desired_mode;
2275 /* Add to the list of all files of this SB */
2276 TAILQ_INSERT_TAIL(&inode->i_sb->s_files, file, f_list);
2277 kref_get(&dentry->d_kref, 1);
2278 file->f_dentry = dentry;
2279 kref_get(&inode->i_sb->s_mount->mnt_kref, 1);
2280 file->f_vfsmnt = inode->i_sb->s_mount; /* saving a ref to the vmnt...*/
2281 file->f_op = inode->i_fop;
2282 /* Don't store creation flags */
2283 file->f_flags = flags & ~O_CREAT_FLAGS;
2285 file->f_uid = inode->i_uid;
2286 file->f_gid = inode->i_gid;
2288 // struct event_poll_tailq f_ep_links;
2289 spinlock_init(&file->f_ep_lock);
2290 file->f_privdata = 0; /* prob overriden by the fs */
2291 file->f_mapping = inode->i_mapping;
2292 file->f_op->open(inode, file);
2299 /* Closes a file, fsync, whatever else is necessary. Called when the kref hits
2300 * 0. Note that the file is not refcounted on the s_files list, nor is the
2301 * f_mapping refcounted (it is pinned by the i_mapping). */
2302 void file_release(struct kref *kref)
2304 struct file *file = container_of(kref, struct file, f_kref);
2306 struct super_block *sb = file->f_dentry->d_sb;
2307 spin_lock(&sb->s_lock);
2308 TAILQ_REMOVE(&sb->s_files, file, f_list);
2309 spin_unlock(&sb->s_lock);
2311 /* TODO: fsync (BLK). also, we may want to parallelize the blocking that
2312 * could happen in here (spawn kernel threads)... */
2313 file->f_op->release(file->f_dentry->d_inode, file);
2314 /* Clean up the other refs we hold */
2315 kref_put(&file->f_dentry->d_kref);
2316 kref_put(&file->f_vfsmnt->mnt_kref);
2317 kmem_cache_free(file_kcache, file);
2320 ssize_t kread_file(struct file *file, void *buf, size_t sz)
2322 /* TODO: (KFOP) (VFS kernel read/writes need to be from a ktask) */
2323 uintptr_t old_ret = switch_to_ktask();
2325 ssize_t cpy_amt = file->f_op->read(file, buf, sz, &dummy);
2327 switch_back_from_ktask(old_ret);
2331 /* Reads the contents of an entire file into a buffer, returning that buffer.
2332 * On error, prints something useful and returns 0 */
2333 void *kread_whole_file(struct file *file)
2339 size = file->f_dentry->d_inode->i_size;
2340 contents = kmalloc(size, MEM_WAIT);
2341 cpy_amt = kread_file(file, contents, size);
2343 printk("Error %d reading file %s\n", get_errno(), file_name(file));
2347 if (cpy_amt != size) {
2348 printk("Read %d, needed %d for file %s\n", cpy_amt, size,
2356 /* Process-related File management functions */
2358 /* Given any FD, get the appropriate object, 0 o/w. Set vfs if you're looking
2359 * for a file, o/w a chan. Set incref if you want a reference count (which is a
2360 * 9ns thing, you can't use the pointer if you didn't incref). */
2361 void *lookup_fd(struct fd_table *fdt, int fd, bool incref, bool vfs)
2366 spin_lock(&fdt->lock);
2368 spin_unlock(&fdt->lock);
2371 if (fd < fdt->max_fdset) {
2372 if (GET_BITMASK_BIT(fdt->open_fds->fds_bits, fd)) {
2373 /* while max_files and max_fdset might not line up, we should never
2374 * have a valid fdset higher than files */
2375 assert(fd < fdt->max_files);
2377 retval = fdt->fd[fd].fd_file;
2379 retval = fdt->fd[fd].fd_chan;
2380 /* retval could be 0 if we asked for the wrong one (e.g. it's a
2381 * file, but we asked for a chan) */
2382 if (retval && incref) {
2384 kref_get(&((struct file*)retval)->f_kref, 1);
2386 chan_incref((struct chan*)retval);
2390 spin_unlock(&fdt->lock);
2394 /* Given any FD, get the appropriate file, 0 o/w */
2395 struct file *get_file_from_fd(struct fd_table *open_files, int file_desc)
2397 return lookup_fd(open_files, file_desc, TRUE, TRUE);
2400 /* Grow the vfs fd set */
2401 static int grow_fd_set(struct fd_table *open_files)
2404 struct file_desc *nfd, *ofd;
2406 /* Only update open_fds once. If currently pointing to open_fds_init, then
2407 * update it to point to a newly allocated fd_set with space for
2408 * NR_FILE_DESC_MAX */
2409 if (open_files->open_fds == (struct fd_set*)&open_files->open_fds_init) {
2410 open_files->open_fds = kzmalloc(sizeof(struct fd_set), 0);
2411 memmove(open_files->open_fds, &open_files->open_fds_init,
2412 sizeof(struct small_fd_set));
2415 /* Grow the open_files->fd array in increments of NR_OPEN_FILES_DEFAULT */
2416 n = open_files->max_files + NR_OPEN_FILES_DEFAULT;
2417 if (n > NR_FILE_DESC_MAX)
2419 nfd = kzmalloc(n * sizeof(struct file_desc), 0);
2423 /* Move the old array on top of the new one */
2424 ofd = open_files->fd;
2425 memmove(nfd, ofd, open_files->max_files * sizeof(struct file_desc));
2427 /* Update the array and the maxes for both max_files and max_fdset */
2428 open_files->fd = nfd;
2429 open_files->max_files = n;
2430 open_files->max_fdset = n;
2432 /* Only free the old one if it wasn't pointing to open_files->fd_array */
2433 if (ofd != open_files->fd_array)
2438 /* Free the vfs fd set if necessary */
2439 static void free_fd_set(struct fd_table *open_files)
2442 if (open_files->open_fds != (struct fd_set*)&open_files->open_fds_init) {
2443 assert(open_files->fd != open_files->fd_array);
2444 /* need to reset the pointers to the internal addrs, in case we take a
2445 * look while debugging. 0 them out, since they have old data. our
2446 * current versions should all be closed. */
2447 memset(&open_files->open_fds_init, 0, sizeof(struct small_fd_set));
2448 memset(&open_files->fd_array, 0, sizeof(open_files->fd_array));
2450 free_me = open_files->open_fds;
2451 open_files->open_fds = (struct fd_set*)&open_files->open_fds_init;
2454 free_me = open_files->fd;
2455 open_files->fd = open_files->fd_array;
2460 /* If FD is in the group, remove it, decref it, and return TRUE. */
2461 bool close_fd(struct fd_table *fdt, int fd)
2463 struct file *file = 0;
2464 struct chan *chan = 0;
2465 struct fd_tap *tap = 0;
2469 spin_lock(&fdt->lock);
2470 if (fd < fdt->max_fdset) {
2471 if (GET_BITMASK_BIT(fdt->open_fds->fds_bits, fd)) {
2472 /* while max_files and max_fdset might not line up, we should never
2473 * have a valid fdset higher than files */
2474 assert(fd < fdt->max_files);
2475 file = fdt->fd[fd].fd_file;
2476 chan = fdt->fd[fd].fd_chan;
2477 tap = fdt->fd[fd].fd_tap;
2478 fdt->fd[fd].fd_file = 0;
2479 fdt->fd[fd].fd_chan = 0;
2480 fdt->fd[fd].fd_tap = 0;
2481 CLR_BITMASK_BIT(fdt->open_fds->fds_bits, fd);
2482 if (fd < fdt->hint_min_fd)
2483 fdt->hint_min_fd = fd;
2487 spin_unlock(&fdt->lock);
2488 /* Need to decref/cclose outside of the lock; they could sleep */
2490 kref_put(&file->f_kref);
2494 kref_put(&tap->kref);
2498 void put_file_from_fd(struct fd_table *open_files, int file_desc)
2500 close_fd(open_files, file_desc);
2503 static int __get_fd(struct fd_table *open_files, int low_fd, bool must_use_low)
2507 bool update_hint = TRUE;
2508 if ((low_fd < 0) || (low_fd > NR_FILE_DESC_MAX))
2510 if (open_files->closed)
2511 return -EINVAL; /* won't matter, they are dying */
2512 if (must_use_low && GET_BITMASK_BIT(open_files->open_fds->fds_bits, low_fd))
2514 if (low_fd > open_files->hint_min_fd)
2515 update_hint = FALSE;
2517 low_fd = open_files->hint_min_fd;
2518 /* Loop until we have a valid slot (we grow the fd_array at the bottom of
2519 * the loop if we haven't found a slot in the current array */
2520 while (slot == -1) {
2521 for (low_fd; low_fd < open_files->max_fdset; low_fd++) {
2522 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, low_fd))
2525 SET_BITMASK_BIT(open_files->open_fds->fds_bits, slot);
2526 assert(slot < open_files->max_files &&
2527 open_files->fd[slot].fd_file == 0);
2528 /* We know slot >= hint, since we started with the hint */
2530 open_files->hint_min_fd = slot + 1;
2534 if ((error = grow_fd_set(open_files)))
2541 /* Insert a file or chan (obj, chosen by vfs) into the fd group with fd_flags.
2542 * If must_use_low, then we have to insert at FD = low_fd. o/w we start looking
2543 * for empty slots at low_fd. */
2544 int insert_obj_fdt(struct fd_table *fdt, void *obj, int low_fd, int fd_flags,
2545 bool must_use_low, bool vfs)
2548 spin_lock(&fdt->lock);
2549 slot = __get_fd(fdt, low_fd, must_use_low);
2551 spin_unlock(&fdt->lock);
2554 assert(slot < fdt->max_files &&
2555 fdt->fd[slot].fd_file == 0);
2557 kref_get(&((struct file*)obj)->f_kref, 1);
2558 fdt->fd[slot].fd_file = obj;
2559 fdt->fd[slot].fd_chan = 0;
2561 chan_incref((struct chan*)obj);
2562 fdt->fd[slot].fd_file = 0;
2563 fdt->fd[slot].fd_chan = obj;
2565 fdt->fd[slot].fd_flags = fd_flags;
2566 spin_unlock(&fdt->lock);
2570 /* Inserts the file in the fd_table, returning the corresponding new file
2571 * descriptor, or an error code. We start looking for open fds from low_fd.
2573 * Passing cloexec is a bit cheap, since we might want to expand it to support
2574 * more FD options in the future. */
2575 int insert_file(struct fd_table *open_files, struct file *file, int low_fd,
2576 bool must, bool cloexec)
2578 return insert_obj_fdt(open_files, file, low_fd, cloexec ? FD_CLOEXEC : 0,
2582 /* Closes all open files. Mostly just a "put" for all files. If cloexec, it
2583 * will only close the FDs with FD_CLOEXEC (opened with O_CLOEXEC or fcntld).
2585 * Notes on concurrency:
2586 * - Can't hold spinlocks while we call cclose, since it might sleep eventually.
2587 * - We're called from proc_destroy, so we could have concurrent openers trying
2588 * to add to the group (other syscalls), hence the "closed" flag.
2589 * - dot and slash chans are dealt with in proc_free. its difficult to close
2590 * and zero those with concurrent syscalls, since those are a source of krefs.
2591 * - Once we lock and set closed, no further additions can happen. To simplify
2592 * our closes, we also allow multiple calls to this func (though that should
2593 * never happen with the current code). */
2594 void close_fdt(struct fd_table *fdt, bool cloexec)
2598 struct file_desc *to_close;
2601 to_close = kzmalloc(sizeof(struct file_desc) * fdt->max_files,
2603 spin_lock(&fdt->lock);
2605 spin_unlock(&fdt->lock);
2609 for (int i = 0; i < fdt->max_fdset; i++) {
2610 if (GET_BITMASK_BIT(fdt->open_fds->fds_bits, i)) {
2611 /* while max_files and max_fdset might not line up, we should never
2612 * have a valid fdset higher than files */
2613 assert(i < fdt->max_files);
2614 if (cloexec && !(fdt->fd[i].fd_flags & FD_CLOEXEC))
2616 file = fdt->fd[i].fd_file;
2617 chan = fdt->fd[i].fd_chan;
2618 to_close[idx].fd_tap = fdt->fd[i].fd_tap;
2619 fdt->fd[i].fd_tap = 0;
2621 fdt->fd[i].fd_file = 0;
2622 to_close[idx++].fd_file = file;
2624 fdt->fd[i].fd_chan = 0;
2625 to_close[idx++].fd_chan = chan;
2627 CLR_BITMASK_BIT(fdt->open_fds->fds_bits, i);
2630 /* it's just a hint, we can build back up from being 0 */
2631 fdt->hint_min_fd = 0;
2636 spin_unlock(&fdt->lock);
2637 /* We go through some hoops to close/decref outside the lock. Nice for not
2638 * holding the lock for a while; critical in case the decref/cclose sleeps
2640 for (int i = 0; i < idx; i++) {
2641 if (to_close[i].fd_file)
2642 kref_put(&to_close[i].fd_file->f_kref);
2644 cclose(to_close[i].fd_chan);
2645 if (to_close[i].fd_tap)
2646 kref_put(&to_close[i].fd_tap->kref);
2651 /* Inserts all of the files from src into dst, used by sys_fork(). */
2652 void clone_fdt(struct fd_table *src, struct fd_table *dst)
2658 spin_lock(&src->lock);
2660 spin_unlock(&src->lock);
2663 spin_lock(&dst->lock);
2665 warn("Destination closed before it opened");
2666 spin_unlock(&dst->lock);
2667 spin_unlock(&src->lock);
2670 while (src->max_files > dst->max_files) {
2671 ret = grow_fd_set(dst);
2673 set_error(-ret, "Failed to grow for a clone_fdt");
2674 spin_unlock(&dst->lock);
2675 spin_unlock(&src->lock);
2679 for (int i = 0; i < src->max_fdset; i++) {
2680 if (GET_BITMASK_BIT(src->open_fds->fds_bits, i)) {
2681 /* while max_files and max_fdset might not line up, we should never
2682 * have a valid fdset higher than files */
2683 assert(i < src->max_files);
2684 file = src->fd[i].fd_file;
2685 chan = src->fd[i].fd_chan;
2686 assert(i < dst->max_files && dst->fd[i].fd_file == 0);
2687 SET_BITMASK_BIT(dst->open_fds->fds_bits, i);
2688 dst->fd[i].fd_file = file;
2689 dst->fd[i].fd_chan = chan;
2691 kref_get(&file->f_kref, 1);
2696 dst->hint_min_fd = src->hint_min_fd;
2697 spin_unlock(&dst->lock);
2698 spin_unlock(&src->lock);
2701 static void __chpwd(struct fs_struct *fs_env, struct dentry *new_pwd)
2703 struct dentry *old_pwd;
2704 kref_get(&new_pwd->d_kref, 1);
2705 /* writer lock, make sure we replace pwd with ours. could also CAS.
2706 * readers don't lock at all, so they need to either loop, or we need to
2707 * delay releasing old_pwd til an RCU grace period. */
2708 spin_lock(&fs_env->lock);
2709 old_pwd = fs_env->pwd;
2710 fs_env->pwd = new_pwd;
2711 spin_unlock(&fs_env->lock);
2712 kref_put(&old_pwd->d_kref);
2715 /* Change the working directory of the given fs env (one per process, at this
2716 * point). Returns 0 for success, sets errno and returns -1 otherwise. */
2717 int do_chdir(struct fs_struct *fs_env, char *path)
2719 struct nameidata nd_r = {0}, *nd = &nd_r;
2721 error = path_lookup(path, LOOKUP_DIRECTORY, nd);
2727 /* nd->dentry is the place we want our PWD to be */
2728 __chpwd(fs_env, nd->dentry);
2733 int do_fchdir(struct fs_struct *fs_env, struct file *file)
2735 if ((file->f_dentry->d_inode->i_mode & __S_IFMT) != __S_IFDIR) {
2739 __chpwd(fs_env, file->f_dentry);
2743 /* Returns a null-terminated string of up to length cwd_l containing the
2744 * absolute path of fs_env, (up to fs_env's root). Be sure to kfree the char*
2745 * "kfree_this" when you are done with it. We do this since it's easier to
2746 * build this string going backwards. Note cwd_l is not a strlen, it's an
2748 char *do_getcwd(struct fs_struct *fs_env, char **kfree_this, size_t cwd_l)
2750 struct dentry *dentry = fs_env->pwd;
2752 char *path_start, *kbuf;
2758 kbuf = kmalloc(cwd_l, 0);
2764 kbuf[cwd_l - 1] = '\0';
2765 kbuf[cwd_l - 2] = '/';
2766 /* for each dentry in the path, all the way back to the root of fs_env, we
2767 * grab the dentry name, push path_start back enough, and write in the name,
2768 * using /'s to terminate. We skip the root, since we don't want its
2769 * actual name, just "/", which is set before each loop. */
2770 path_start = kbuf + cwd_l - 2; /* the last byte written */
2771 while (dentry != fs_env->root) {
2772 link_len = dentry->d_name.len; /* this does not count the \0 */
2773 if (path_start - (link_len + 2) < kbuf) {
2778 path_start -= link_len;
2779 memmove(path_start, dentry->d_name.name, link_len);
2782 dentry = dentry->d_parent;
2787 static void print_dir(struct dentry *dentry, char *buf, int depth)
2789 struct dentry *child_d;
2790 struct dirent next = {0};
2794 if (!S_ISDIR(dentry->d_inode->i_mode)) {
2795 warn("Thought this was only directories!!");
2798 /* Print this dentry */
2799 printk("%s%s/ nlink: %d\n", buf, dentry->d_name.name,
2800 dentry->d_inode->i_nlink);
2801 if (dentry->d_mount_point) {
2802 dentry = dentry->d_mounted_fs->mnt_root;
2806 /* Set buffer for our kids */
2808 dir = dentry_open(dentry, 0);
2810 panic("Filesystem seems inconsistent - unable to open a dir!");
2811 /* Process every child, recursing on directories */
2813 retval = dir->f_op->readdir(dir, &next);
2815 /* Skip .., ., and empty entries */
2816 if (!strcmp("..", next.d_name) || !strcmp(".", next.d_name) ||
2819 /* there is an entry, now get its dentry */
2820 child_d = do_lookup(dentry, next.d_name);
2822 panic("Inconsistent FS, dirent doesn't have a dentry!");
2823 /* Recurse for directories, or just print the name for others */
2824 switch (child_d->d_inode->i_mode & __S_IFMT) {
2826 print_dir(child_d, buf, depth + 1);
2829 printk("%s%s size(B): %d nlink: %d\n", buf, next.d_name,
2830 child_d->d_inode->i_size, child_d->d_inode->i_nlink);
2833 printk("%s%s -> %s\n", buf, next.d_name,
2834 child_d->d_inode->i_op->readlink(child_d));
2837 printk("%s%s (char device) nlink: %d\n", buf, next.d_name,
2838 child_d->d_inode->i_nlink);
2841 printk("%s%s (block device) nlink: %d\n", buf, next.d_name,
2842 child_d->d_inode->i_nlink);
2845 warn("Look around you! Unknown filetype!");
2847 kref_put(&child_d->d_kref);
2853 /* Reset buffer to the way it was */
2855 kref_put(&dir->f_kref);
2859 int ls_dash_r(char *path)
2861 struct nameidata nd_r = {0}, *nd = &nd_r;
2865 error = path_lookup(path, LOOKUP_ACCESS | LOOKUP_DIRECTORY, nd);
2870 print_dir(nd->dentry, buf, 0);
2875 /* Dummy ops, to catch weird operations we weren't expecting */
2876 int dummy_create(struct inode *dir, struct dentry *dentry, int mode,
2877 struct nameidata *nd)
2879 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2883 struct dentry *dummy_lookup(struct inode *dir, struct dentry *dentry,
2884 struct nameidata *nd)
2886 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2890 int dummy_link(struct dentry *old_dentry, struct inode *dir,
2891 struct dentry *new_dentry)
2893 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2897 int dummy_unlink(struct inode *dir, struct dentry *dentry)
2899 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2903 int dummy_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
2905 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2909 int dummy_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2911 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2915 int dummy_rmdir(struct inode *dir, struct dentry *dentry)
2917 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2921 int dummy_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t rdev)
2923 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2927 int dummy_rename(struct inode *old_dir, struct dentry *old_dentry,
2928 struct inode *new_dir, struct dentry *new_dentry)
2930 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2934 char *dummy_readlink(struct dentry *dentry)
2936 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2940 void dummy_truncate(struct inode *inode)
2942 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2945 int dummy_permission(struct inode *inode, int mode, struct nameidata *nd)
2947 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2951 int dummy_d_revalidate(struct dentry *dir, struct nameidata *nd)
2953 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2957 int dummy_d_hash(struct dentry *dentry, struct qstr *name)
2959 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2963 int dummy_d_compare(struct dentry *dir, struct qstr *name1, struct qstr *name2)
2965 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2969 int dummy_d_delete(struct dentry *dentry)
2971 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2975 int dummy_d_release(struct dentry *dentry)
2977 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2981 void dummy_d_iput(struct dentry *dentry, struct inode *inode)
2983 printk("Dummy VFS function %s called!\n", __FUNCTION__);
2986 struct inode_operations dummy_i_op = {
3001 struct dentry_operations dummy_d_op = {