1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Default implementations and global values for the VFS. */
7 #include <vfs.h> // keep this first
20 struct sb_tailq super_blocks = TAILQ_HEAD_INITIALIZER(super_blocks);
21 spinlock_t super_blocks_lock = SPINLOCK_INITIALIZER;
22 struct fs_type_tailq file_systems = TAILQ_HEAD_INITIALIZER(file_systems);
23 struct namespace default_ns;
24 // TODO: temp dcache, holds all dentries ever for now
25 struct dentry_slist dcache = SLIST_HEAD_INITIALIZER(dcache);
26 spinlock_t dcache_lock = SPINLOCK_INITIALIZER;
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 now).
47 * fields related to the actual FS, like the sb and the mnt_root are set in
48 * 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);
105 TAILQ_INSERT_TAIL(&file_systems, &ext2_fs_type, list);
106 TAILQ_FOREACH(fs, &file_systems, list)
107 printk("Supports the %s Filesystem\n", fs->name);
109 /* mounting KFS at the root (/), pending root= parameters */
110 // TODO: linux creates a temp root_fs, then mounts the real root onto that
111 default_ns.root = __mount_fs(&kfs_fs_type, "RAM", NULL, 0, &default_ns);
113 printk("vfs_init() completed\n");
116 /* Builds / populates the qstr of a dentry based on its d_iname. If there is an
117 * l_name, (long), it will use that instead of the inline name. This will
118 * probably change a bit. */
119 void qstr_builder(struct dentry *dentry, char *l_name)
121 dentry->d_name.name = l_name ? l_name : dentry->d_iname;
122 // TODO: pending what we actually do in d_hash
123 //dentry->d_name.hash = dentry->d_op->d_hash(dentry, &dentry->d_name);
124 dentry->d_name.hash = 0xcafebabe;
125 dentry->d_name.len = strnlen(dentry->d_name.name, MAX_FILENAME_SZ);
128 /* Useful little helper - return the string ptr for a given file */
129 char *file_name(struct file *file)
131 return file->f_dentry->d_name.name;
134 /* Some issues with this, coupled closely to fs_lookup. This assumes that
135 * negative dentries are not returned (might differ from linux) */
136 static struct dentry *do_lookup(struct dentry *parent, char *name)
138 struct dentry *dentry;
139 /* TODO: look up in the dentry cache first */
140 dentry = get_dentry(parent->d_sb, parent, name);
141 dentry = parent->d_inode->i_op->lookup(parent->d_inode, dentry, 0);
142 /* insert in dentry cache */
143 /* TODO: if the following are done by us, how do we know the i_ino?
144 * also need to handle inodes that are already read in! For now, we're
145 * going to have the FS handle it in it's lookup() method:
147 * - read in the inode
148 * - put in the inode cache */
152 /* Update ND such that it represents having followed dentry. IAW the nd
153 * refcnting rules, we need to decref any references that were in there before
154 * they get clobbered. */
155 static int next_link(struct dentry *dentry, struct nameidata *nd)
157 assert(nd->dentry && nd->mnt);
158 /* update the dentry */
159 kref_get(&dentry->d_kref, 1);
160 kref_put(&nd->dentry->d_kref);
162 /* update the mount, if we need to */
163 if (dentry->d_sb->s_mount != nd->mnt) {
164 kref_get(&dentry->d_sb->s_mount->mnt_kref, 1);
165 kref_put(&nd->mnt->mnt_kref);
166 nd->mnt = dentry->d_sb->s_mount;
171 /* Walk up one directory, being careful of mountpoints, namespaces, and the top
173 static int climb_up(struct nameidata *nd)
175 printd("CLIMB_UP, from %s\n", nd->dentry->d_name.name);
176 /* Top of the world, just return. Should also check for being at the top of
177 * the current process's namespace (TODO) */
178 if (!nd->dentry->d_parent || (nd->dentry->d_parent == nd->dentry))
180 /* Check if we are at the top of a mount, if so, we need to follow
181 * backwards, and then climb_up from that one. We might need to climb
182 * multiple times if we mount multiple FSs at the same spot (highly
183 * unlikely). This is completely untested. Might recurse instead. */
184 while (nd->mnt->mnt_root == nd->dentry) {
185 if (!nd->mnt->mnt_parent) {
186 warn("Might have expected a parent vfsmount (dentry had a parent)");
189 next_link(nd->mnt->mnt_mountpoint, nd);
191 /* Backwards walk (no mounts or any other issues now). */
192 next_link(nd->dentry->d_parent, nd);
193 printd("CLIMB_UP, to %s\n", nd->dentry->d_name.name);
197 /* nd->dentry might be on a mount point, so we need to move on to the child
199 static int follow_mount(struct nameidata *nd)
201 if (!nd->dentry->d_mount_point)
203 next_link(nd->dentry->d_mounted_fs->mnt_root, nd);
207 static int link_path_walk(char *path, struct nameidata *nd);
209 /* When nd->dentry is for a symlink, this will recurse and follow that symlink,
210 * so that nd contains the results of following the symlink (dentry and mnt).
211 * Returns when it isn't a symlink, 1 on following a link, and < 0 on error. */
212 static int follow_symlink(struct nameidata *nd)
216 if (!S_ISLNK(nd->dentry->d_inode->i_mode))
218 if (nd->depth > MAX_SYMLINK_DEPTH)
220 printd("Following symlink for dentry %08p %s\n", nd->dentry,
221 nd->dentry->d_name.name);
223 symname = nd->dentry->d_inode->i_op->readlink(nd->dentry);
224 /* We need to pin in nd->dentry (the dentry of the symlink), since we need
225 * it's symname's storage to stay in memory throughout the upcoming
226 * link_path_walk(). The last_sym gets decreffed when we path_release() or
227 * follow another symlink. */
229 kref_put(&nd->last_sym->d_kref);
230 kref_get(&nd->dentry->d_kref, 1);
231 nd->last_sym = nd->dentry;
232 /* If this an absolute path in the symlink, we need to free the old path and
233 * start over, otherwise, we continue from the PARENT of nd (the symlink) */
234 if (symname[0] == '/') {
237 nd->dentry = default_ns.root->mnt_root;
239 nd->dentry = current->fs_env.root;
240 nd->mnt = nd->dentry->d_sb->s_mount;
241 kref_get(&nd->mnt->mnt_kref, 1);
242 kref_get(&nd->dentry->d_kref, 1);
246 /* either way, keep on walking in the free world! */
247 retval = link_path_walk(symname, nd);
248 return (retval == 0 ? 1 : retval);
251 /* Little helper, to make it easier to break out of the nested loops. Will also
252 * '\0' out the first slash if it's slashes all the way down. Or turtles. */
253 static bool packed_trailing_slashes(char *first_slash)
255 for (char *i = first_slash; *i == '/'; i++) {
256 if (*(i + 1) == '\0') {
264 /* Simple helper to set nd to track it's last name to be Name. Also be careful
265 * with the storage of name. Don't use and nd's name past the lifetime of the
266 * string used in the path_lookup()/link_path_walk/whatever. Consider replacing
267 * parts of this with a qstr builder. Note this uses the dentry's d_op, which
268 * might not be the dentry we care about. */
269 static void stash_nd_name(struct nameidata *nd, char *name)
271 nd->last.name = name;
272 nd->last.len = strlen(name);
273 nd->last.hash = nd->dentry->d_op->d_hash(nd->dentry, &nd->last);
276 /* Resolves the links in a basic path walk. 0 for success, -EWHATEVER
277 * otherwise. The final lookup is returned via nd. */
278 static int link_path_walk(char *path, struct nameidata *nd)
280 struct dentry *link_dentry;
281 struct inode *link_inode, *nd_inode;
286 /* Prevent crazy recursion */
287 if (nd->depth > MAX_SYMLINK_DEPTH)
289 /* skip all leading /'s */
292 /* if there's nothing left (null terminated), we're done. This should only
293 * happen for "/", which if we wanted a PARENT, should fail (there is no
296 if (nd->flags & LOOKUP_PARENT) {
300 /* o/w, we're good */
303 /* iterate through each intermediate link of the path. in general, nd
304 * tracks where we are in the path, as far as dentries go. once we have the
305 * next dentry, we try to update nd based on that dentry. link is the part
306 * of the path string that we are looking up */
308 nd_inode = nd->dentry->d_inode;
309 if ((error = check_perms(nd_inode, nd->intent)))
311 /* find the next link, break out if it is the end */
312 next_slash = strchr(link, '/');
316 if (packed_trailing_slashes(next_slash)) {
317 nd->flags |= LOOKUP_DIRECTORY;
321 /* skip over any interim ./ */
322 if (!strncmp("./", link, 2))
324 /* Check for "../", walk up */
325 if (!strncmp("../", link, 3)) {
330 link_dentry = do_lookup(nd->dentry, link);
334 /* make link_dentry the current step/answer */
335 next_link(link_dentry, nd);
336 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt dentry */
337 /* we could be on a mountpoint or a symlink - need to follow them */
339 if ((error = follow_symlink(nd)) < 0)
341 /* Turn off a possible DIRECTORY lookup, which could have been set
342 * during the follow_symlink (a symlink could have had a directory at
343 * the end), though it was in the middle of the real path. */
344 nd->flags &= ~LOOKUP_DIRECTORY;
345 if (!S_ISDIR(nd->dentry->d_inode->i_mode))
348 /* move through the path string to the next entry */
349 link = next_slash + 1;
350 /* advance past any other interim slashes. we know we won't hit the end
351 * due to the for loop check above */
355 /* Now, we're on the last link of the path. We need to deal with with . and
356 * .. . This might be weird with PARENT lookups - not sure what semantics
357 * we want exactly. This will give the parent of whatever the PATH was
358 * supposed to look like. Note that ND currently points to the parent of
359 * the last item (link). */
360 if (!strcmp(".", link)) {
361 if (nd->flags & LOOKUP_PARENT) {
362 assert(nd->dentry->d_name.name);
363 stash_nd_name(nd, nd->dentry->d_name.name);
368 if (!strcmp("..", link)) {
370 if (nd->flags & LOOKUP_PARENT) {
371 assert(nd->dentry->d_name.name);
372 stash_nd_name(nd, nd->dentry->d_name.name);
377 /* need to attempt to look it up, in case it's a symlink */
378 link_dentry = do_lookup(nd->dentry, link);
380 /* if there's no dentry, we are okay if we are looking for the parent */
381 if (nd->flags & LOOKUP_PARENT) {
382 assert(strcmp(link, ""));
383 stash_nd_name(nd, link);
389 next_link(link_dentry, nd);
390 kref_put(&link_dentry->d_kref); /* do_lookup gave us a refcnt'd dentry */
391 /* at this point, nd is on the final link, but it might be a symlink */
392 if (nd->flags & LOOKUP_FOLLOW) {
393 error = follow_symlink(nd);
396 /* if we actually followed a symlink, then nd is set and we're done */
400 /* One way or another, nd is on the last element of the path, symlinks and
401 * all. Now we need to climb up to set nd back on the parent, if that's
403 if (nd->flags & LOOKUP_PARENT) {
404 assert(nd->dentry->d_name.name);
405 stash_nd_name(nd, link_dentry->d_name.name);
409 /* now, we have the dentry set, and don't want the parent, but might be on a
410 * mountpoint still. FYI: this hasn't been thought through completely. */
412 /* If we wanted a directory, but didn't get one, error out */
413 if ((nd->flags & LOOKUP_DIRECTORY) && !S_ISDIR(nd->dentry->d_inode->i_mode))
418 /* Given path, return the inode for the final dentry. The ND should be
419 * initialized for the first call - specifically, we need the intent.
420 * LOOKUP_PARENT and friends go in the flags var, which is not the intent.
422 * If path_lookup wants a PARENT, but hits the top of the FS (root or
423 * otherwise), we want it to error out. It's still unclear how we want to
424 * handle processes with roots that aren't root, but at the very least, we don't
425 * want to think we have the parent of /, but have / itself. Due to the way
426 * link_path_walk works, if that happened, we probably don't have a
427 * nd->last.name. This needs more thought (TODO).
429 * Need to be careful too. While the path has been copied-in to the kernel,
430 * it's still user input. */
431 int path_lookup(char *path, int flags, struct nameidata *nd)
434 printd("Path lookup for %s\n", path);
435 /* we allow absolute lookups with no process context */
436 if (path[0] == '/') { /* absolute lookup */
438 nd->dentry = default_ns.root->mnt_root;
440 nd->dentry = current->fs_env.root;
441 } else { /* relative lookup */
443 /* Don't need to lock on the fs_env since we're reading one item */
444 nd->dentry = current->fs_env.pwd;
446 nd->mnt = nd->dentry->d_sb->s_mount;
447 /* Whenever references get put in the nd, incref them. Whenever they are
448 * removed, decref them. */
449 kref_get(&nd->mnt->mnt_kref, 1);
450 kref_get(&nd->dentry->d_kref, 1);
452 nd->depth = 0; /* used in symlink following */
453 retval = link_path_walk(path, nd);
454 /* make sure our PARENT lookup worked */
455 if (!retval && (flags & LOOKUP_PARENT))
456 assert(nd->last.name);
460 /* Call this after any use of path_lookup when you are done with its results,
461 * regardless of whether it succeeded or not. It will free any references */
462 void path_release(struct nameidata *nd)
464 kref_put(&nd->dentry->d_kref);
465 kref_put(&nd->mnt->mnt_kref);
466 /* Free the last symlink dentry used, if there was one */
468 kref_put(&nd->last_sym->d_kref);
469 nd->last_sym = 0; /* catch reuse bugs */
473 /* External version of mount, only call this after having a / mount */
474 int mount_fs(struct fs_type *fs, char *dev_name, char *path, int flags)
476 struct nameidata nd_r = {0}, *nd = &nd_r;
478 retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
481 /* taking the namespace of the vfsmount of path */
482 if (!__mount_fs(fs, dev_name, nd->dentry, flags, nd->mnt->mnt_namespace))
489 /* Superblock functions */
491 /* Helper to alloc and initialize a generic superblock. This handles all the
492 * VFS related things, like lists. Each FS will need to handle its own things
493 * in it's *_get_sb(), usually involving reading off the disc. */
494 struct super_block *get_sb(void)
496 struct super_block *sb = kmalloc(sizeof(struct super_block), 0);
498 spinlock_init(&sb->s_lock);
499 kref_init(&sb->s_kref, fake_release, 1); /* for the ref passed out */
500 TAILQ_INIT(&sb->s_inodes);
501 TAILQ_INIT(&sb->s_dirty_i);
502 TAILQ_INIT(&sb->s_io_wb);
503 SLIST_INIT(&sb->s_anon_d);
504 TAILQ_INIT(&sb->s_files);
505 sb->s_fs_info = 0; // can override somewhere else
509 /* Final stages of initializing a super block, including creating and linking
510 * the root dentry, root inode, vmnt, and sb. The d_op and root_ino are
511 * FS-specific, but otherwise it's FS-independent, tricky, and not worth having
512 * around multiple times.
514 * Not the world's best interface, so it's subject to change, esp since we're
515 * passing (now 3) FS-specific things. */
516 void init_sb(struct super_block *sb, struct vfsmount *vmnt,
517 struct dentry_operations *d_op, unsigned long root_ino,
520 /* Build and init the first dentry / inode. The dentry ref is stored later
521 * by vfsmount's mnt_root. The parent is dealt with later. */
522 struct dentry *d_root = get_dentry(sb, 0, "/"); /* probably right */
524 /* a lot of here on down is normally done in lookup() or create, since
525 * get_dentry isn't a fully usable dentry. The two FS-specific settings are
526 * normally inherited from a parent within the same FS in get_dentry, but we
529 d_root->d_fs_info = d_fs_info;
530 struct inode *inode = get_inode(d_root);
532 panic("This FS sucks!");
533 inode->i_ino = root_ino;
534 /* TODO: add the inode to the appropriate list (off i_list) */
535 /* TODO: do we need to read in the inode? can we do this on demand? */
536 /* if this FS is already mounted, we'll need to do something different. */
537 sb->s_op->read_inode(inode);
538 /* Link the dentry and SB to the VFS mount */
539 vmnt->mnt_root = d_root; /* ref comes from get_dentry */
541 /* If there is no mount point, there is no parent. This is true only for
543 if (vmnt->mnt_mountpoint) {
544 kref_get(&vmnt->mnt_mountpoint->d_kref, 1); /* held by d_root */
545 d_root->d_parent = vmnt->mnt_mountpoint; /* dentry of the root */
547 d_root->d_parent = d_root; /* set root as its own parent */
549 /* insert the dentry into the dentry cache. when's the earliest we can?
550 * when's the earliest we should? what about concurrent accesses to the
551 * same dentry? should be locking the dentry... */
552 dcache_put(d_root); // TODO: should set a d_flag too
553 kref_put(&inode->i_kref); /* give up the ref from get_inode() */
556 /* Dentry Functions */
558 /* Helper to alloc and initialize a generic dentry. The following needs to be
559 * set still: d_op (if no parent), d_fs_info (opt), d_inode, connect the inode
560 * to the dentry (and up the d_kref again), maybe dcache_put(). The inode
561 * stitching is done in get_inode() or lookup (depending on the FS).
562 * The setting of the d_op might be problematic when dealing with mounts. Just
565 * If the name is longer than the inline name, it will kmalloc a buffer, so
566 * don't worry about the storage for *name after calling this. */
567 struct dentry *get_dentry(struct super_block *sb, struct dentry *parent,
571 size_t name_len = strnlen(name, MAX_FILENAME_SZ); /* not including \0! */
572 struct dentry *dentry = kmem_cache_alloc(dentry_kcache, 0);
577 //memset(dentry, 0, sizeof(struct dentry));
578 kref_init(&dentry->d_kref, dentry_release, 1); /* this ref is returned */
579 spinlock_init(&dentry->d_lock);
580 TAILQ_INIT(&dentry->d_subdirs);
582 kref_get(&sb->s_kref, 1);
583 dentry->d_sb = sb; /* storing a ref here... */
584 dentry->d_mount_point = FALSE;
585 dentry->d_mounted_fs = 0;
586 if (parent) { /* no parent for rootfs mount */
587 kref_get(&parent->d_kref, 1);
588 dentry->d_op = parent->d_op; /* d_op set in init_sb for parentless */
590 dentry->d_parent = parent;
591 dentry->d_flags = 0; /* related to its dcache state */
592 dentry->d_fs_info = 0;
593 SLIST_INIT(&dentry->d_bucket);
594 if (name_len < DNAME_INLINE_LEN) {
595 strncpy(dentry->d_iname, name, name_len);
596 dentry->d_iname[name_len] = '\0';
597 qstr_builder(dentry, 0);
599 l_name = kmalloc(name_len + 1, 0);
601 strncpy(l_name, name, name_len);
602 l_name[name_len] = '\0';
603 qstr_builder(dentry, l_name);
605 /* Catch bugs by aggressively zeroing this (o/w we use old stuff) */
610 /* Adds a dentry to the dcache. */
611 void dcache_put(struct dentry *dentry)
613 #if 0 /* pending a more thorough review of the dcache */
614 /* TODO: should set a d_flag too */
615 spin_lock(&dcache_lock);
616 SLIST_INSERT_HEAD(&dcache, dentry, d_hash);
617 spin_unlock(&dcache_lock);
621 /* Cleans up the dentry (after ref == 0). We still may want it, and this is
622 * where we should add it to the dentry cache. (TODO). For now, we do nothing,
623 * since we don't have a dcache. Also, if i_nlink == 0, never cache it.
625 * This has to handle two types of dentries: full ones (ones that had been used)
626 * and ones that had been just for lookups - hence the check for d_inode.
628 * Note that dentries pin and kref their inodes. When all the dentries are
629 * gone, we want the inode to be released via kref. The inode has internal /
630 * weak references to the dentry, which are not refcounted. */
631 void dentry_release(struct kref *kref)
633 struct dentry *dentry = container_of(kref, struct dentry, d_kref);
634 printd("Freeing dentry %08p: %s\n", dentry, dentry->d_name.name);
635 assert(dentry->d_op); /* catch bugs. a while back, some lacked d_op */
636 dentry->d_op->d_release(dentry);
637 /* TODO: check/test the boundaries on this. */
638 if (dentry->d_name.len > DNAME_INLINE_LEN)
639 kfree((void*)dentry->d_name.name);
640 kref_put(&dentry->d_sb->s_kref);
641 if (dentry->d_parent)
642 kref_put(&dentry->d_parent->d_kref);
643 if (dentry->d_mounted_fs)
644 kref_put(&dentry->d_mounted_fs->mnt_kref);
645 if (dentry->d_inode) {
646 TAILQ_REMOVE(&dentry->d_inode->i_dentry, dentry, d_alias);
647 kref_put(&dentry->d_inode->i_kref); /* dentries kref inodes */
649 kmem_cache_free(dentry_kcache, dentry);
652 /* Looks up the dentry for the given path, returning a refcnt'd dentry (or 0).
653 * Permissions are applied for the current user, which is quite a broken system
654 * at the moment. Flags are lookup flags. */
655 struct dentry *lookup_dentry(char *path, int flags)
657 struct dentry *dentry;
658 struct nameidata nd_r = {0}, *nd = &nd_r;
661 error = path_lookup(path, flags, nd);
668 kref_get(&dentry->d_kref, 1);
673 /* Inode Functions */
675 /* Creates and initializes a new inode. Generic fields are filled in.
676 * FS-specific fields are filled in by the callout. Specific fields are filled
677 * in in read_inode() based on what's on the disk for a given i_no, or when the
678 * inode is created (for new objects).
680 * i_no is set by the caller. Note that this means this inode can be for an
681 * inode that is already on disk, or it can be used when creating. */
682 struct inode *get_inode(struct dentry *dentry)
684 struct super_block *sb = dentry->d_sb;
685 /* FS allocs and sets the following: i_op, i_fop, i_pm.pm_op, and any FS
687 struct inode *inode = sb->s_op->alloc_inode(sb);
692 TAILQ_INSERT_HEAD(&sb->s_inodes, inode, i_sb_list); /* weak inode ref */
693 TAILQ_INIT(&inode->i_dentry);
694 TAILQ_INSERT_TAIL(&inode->i_dentry, dentry, d_alias); /* weak dentry ref*/
695 /* one for the dentry->d_inode, one passed out */
696 kref_init(&inode->i_kref, inode_release, 2);
697 dentry->d_inode = inode;
698 inode->i_ino = 0; /* set by caller later */
699 inode->i_blksize = sb->s_blocksize;
700 spinlock_init(&inode->i_lock);
701 kref_get(&sb->s_kref, 1); /* could allow the dentry to pin it */
703 inode->i_rdev = 0; /* this has no real meaning yet */
704 inode->i_bdev = sb->s_bdev; /* storing an uncounted ref */
705 inode->i_state = 0; /* need real states, like I_NEW */
706 inode->dirtied_when = 0;
708 atomic_set(&inode->i_writecount, 0);
709 /* Set up the page_map structures. Default is to use the embedded one.
710 * Might push some of this back into specific FSs. For now, the FS tells us
711 * what pm_op they want via i_pm.pm_op, which we use when we point i_mapping
713 inode->i_mapping = &inode->i_pm;
714 inode->i_mapping->pm_host = inode;
715 radix_tree_init(&inode->i_mapping->pm_tree);
716 spinlock_init(&inode->i_mapping->pm_tree_lock);
717 inode->i_mapping->pm_flags = 0;
721 /* Helper: loads/ reads in the inode numbered ino and attaches it to dentry */
722 void load_inode(struct dentry *dentry, unsigned int ino)
724 struct inode *inode = get_inode(dentry);
726 dentry->d_sb->s_op->read_inode(inode);
727 kref_put(&inode->i_kref);
730 /* Helper op, used when creating regular files, directories, symlinks, etc.
731 * Note we make a distinction between the mode and the file type (for now).
732 * After calling this, call the FS specific version (create or mkdir), which
733 * will set the i_ino, the filetype, and do any other FS-specific stuff. Also
734 * note that a lot of inode stuff was initialized in get_inode/alloc_inode. The
735 * stuff here is pertinent to the specific creator (user), mode, and time. Also
736 * note we don't pass this an nd, like Linux does... */
737 static struct inode *create_inode(struct dentry *dentry, int mode)
739 /* note it is the i_ino that uniquely identifies a file in the specific
740 * filesystem. there's a diff between creating an inode (even for an in-use
741 * ino) and then filling it in, and vs creating a brand new one.
742 * get_inode() sets it to 0, and it should be filled in later in an
743 * FS-specific manner. */
744 struct inode *inode = get_inode(dentry);
747 inode->i_mode = mode & S_PMASK; /* note that after this, we have no type */
751 inode->i_atime.tv_sec = 0; /* TODO: now! */
752 inode->i_ctime.tv_sec = 0;
753 inode->i_mtime.tv_sec = 0;
754 inode->i_atime.tv_nsec = 0; /* are these supposed to be the extra ns? */
755 inode->i_ctime.tv_nsec = 0;
756 inode->i_mtime.tv_nsec = 0;
757 inode->i_bdev = inode->i_sb->s_bdev;
758 /* when we have notions of users, do something here: */
764 /* Create a new disk inode in dir associated with dentry, with the given mode.
765 * called when creating a regular file. dir is the directory/parent. dentry is
766 * the dentry of the inode we are creating. Note the lack of the nd... */
767 int create_file(struct inode *dir, struct dentry *dentry, int mode)
769 struct inode *new_file = create_inode(dentry, mode);
772 dir->i_op->create(dir, dentry, mode, 0);
773 kref_put(&new_file->i_kref);
777 /* Creates a new inode for a directory associated with dentry in dir with the
779 int create_dir(struct inode *dir, struct dentry *dentry, int mode)
781 struct inode *new_dir = create_inode(dentry, mode);
784 dir->i_op->mkdir(dir, dentry, mode);
785 dir->i_nlink++; /* Directories get a hardlink for every child dir */
786 /* Make sure my parent tracks me. This is okay, since no directory (dir)
787 * can have more than one dentry */
788 struct dentry *parent = TAILQ_FIRST(&dir->i_dentry);
789 assert(parent && parent == TAILQ_LAST(&dir->i_dentry, dentry_tailq));
790 /* parent dentry tracks dentry as a subdir, weak reference */
791 TAILQ_INSERT_TAIL(&parent->d_subdirs, dentry, d_subdirs_link);
792 kref_put(&new_dir->i_kref);
796 /* Creates a new inode for a symlink associated with dentry in dir, containing
797 * the symlink symname */
798 int create_symlink(struct inode *dir, struct dentry *dentry,
799 const char *symname, int mode)
801 struct inode *new_sym = create_inode(dentry, mode);
804 dir->i_op->symlink(dir, dentry, symname);
805 kref_put(&new_sym->i_kref);
809 /* Returns 0 if the given mode is acceptable for the inode, and an appropriate
810 * error code if not. Needs to be writen, based on some sensible rules, and
811 * will also probably use 'current' */
812 int check_perms(struct inode *inode, int access_mode)
814 return 0; /* anything goes! */
817 /* Called after all external refs are gone to clean up the inode. Once this is
818 * called, all dentries pointing here are already done (one of them triggered
819 * this via kref_put(). */
820 void inode_release(struct kref *kref)
822 struct inode *inode = container_of(kref, struct inode, i_kref);
823 TAILQ_REMOVE(&inode->i_sb->s_inodes, inode, i_sb_list);
824 /* If we still have links, just dealloc the in-memory inode. if we have no
825 * links, we need to delete it too (which calls destroy). */
827 inode->i_sb->s_op->dealloc_inode(inode);
829 inode->i_sb->s_op->delete_inode(inode);
830 kref_put(&inode->i_sb->s_kref);
831 assert(inode->i_mapping == &inode->i_pm);
832 kmem_cache_free(inode_kcache, inode);
834 // kref_put(inode->i_bdev->kref); /* assuming it's a bdev */
837 /* Fills in kstat with the stat information for the inode */
838 void stat_inode(struct inode *inode, struct kstat *kstat)
840 kstat->st_dev = inode->i_sb->s_dev;
841 kstat->st_ino = inode->i_ino;
842 kstat->st_mode = inode->i_mode;
843 kstat->st_nlink = inode->i_nlink;
844 kstat->st_uid = inode->i_uid;
845 kstat->st_gid = inode->i_gid;
846 kstat->st_rdev = inode->i_rdev;
847 kstat->st_size = inode->i_size;
848 kstat->st_blksize = inode->i_blksize;
849 kstat->st_blocks = inode->i_blocks;
850 kstat->st_atime = inode->i_atime;
851 kstat->st_mtime = inode->i_mtime;
852 kstat->st_ctime = inode->i_ctime;
857 /* Read count bytes from the file into buf, starting at *offset, which is increased
858 * accordingly, returning the number of bytes transfered. Most filesystems will
859 * use this function for their f_op->read. Note, this uses the page cache.
860 * Want to try out page remapping later on... */
861 ssize_t generic_file_read(struct file *file, char *buf, size_t count,
867 unsigned long first_idx, last_idx;
871 /* Consider pushing some error checking higher in the VFS */
874 if (*offset == file->f_dentry->d_inode->i_size)
876 /* Make sure we don't go past the end of the file */
877 if (*offset + count > file->f_dentry->d_inode->i_size) {
878 count = file->f_dentry->d_inode->i_size - *offset;
880 page_off = *offset & (PGSIZE - 1);
881 first_idx = *offset >> PGSHIFT;
882 last_idx = (*offset + count) >> PGSHIFT;
883 buf_end = buf + count;
884 /* For each file page, make sure it's in the page cache, then copy it out.
885 * TODO: will probably need to consider concurrently truncated files here.*/
886 for (int i = first_idx; i <= last_idx; i++) {
887 error = file_load_page(file, i, &page);
888 assert(!error); /* TODO: handle ENOMEM and friends */
889 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
890 /* TODO: (UMEM) think about this. if it's a user buffer, we're relying
891 * on current to detect whose it is (which should work for async calls).
892 * Also, need to propagate errors properly... Probably should do a
893 * user_mem_check, then free, and also to make a distinction between
894 * when the kernel wants a read/write (TODO: KFOP) */
896 memcpy_to_user(current, buf, page2kva(page) + page_off, copy_amt);
898 memcpy(buf, page2kva(page) + page_off, copy_amt);
902 page_decref(page); /* it's still in the cache, we just don't need it */
904 assert(buf == buf_end);
909 /* Write count bytes from buf to the file, starting at *offset, which is increased
910 * accordingly, returning the number of bytes transfered. Most filesystems will
911 * use this function for their f_op->write. Note, this uses the page cache.
912 * Changes don't get flushed to disc til there is an fsync, page cache eviction,
913 * or other means of trying to writeback the pages. */
914 ssize_t generic_file_write(struct file *file, const char *buf, size_t count,
920 unsigned long first_idx, last_idx;
924 /* Consider pushing some error checking higher in the VFS */
927 /* Extend the file. Should put more checks in here, and maybe do this per
928 * page in the for loop below. */
929 if (*offset + count > file->f_dentry->d_inode->i_size)
930 file->f_dentry->d_inode->i_size = *offset + count;
931 page_off = *offset & (PGSIZE - 1);
932 first_idx = *offset >> PGSHIFT;
933 last_idx = (*offset + count) >> PGSHIFT;
934 buf_end = buf + count;
935 /* For each file page, make sure it's in the page cache, then write it.*/
936 for (int i = first_idx; i <= last_idx; i++) {
937 error = file_load_page(file, i, &page);
938 assert(!error); /* TODO: handle ENOMEM and friends */
939 copy_amt = MIN(PGSIZE - page_off, buf_end - buf);
940 /* TODO: (UMEM) (KFOP) think about this. if it's a user buffer, we're
941 * relying on current to detect whose it is (which should work for async
944 memcpy_from_user(current, page2kva(page) + page_off, buf, copy_amt);
946 memcpy(page2kva(page) + page_off, buf, copy_amt);
950 page_decref(page); /* it's still in the cache, we just don't need it */
952 assert(buf == buf_end);
957 /* Directories usually use this for their read method, which is the way glibc
958 * currently expects us to do a readdir (short of doing linux's getdents). Will
959 * probably need work, based on whatever real programs want. */
960 ssize_t generic_dir_read(struct file *file, char *u_buf, size_t count,
963 struct kdirent dir_r = {0}, *dirent = &dir_r;
965 size_t amt_copied = 0;
966 char *buf_end = u_buf + count;
968 if (!S_ISDIR(file->f_dentry->d_inode->i_mode)) {
974 /* start readdir from where it left off: */
975 dirent->d_off = *offset;
976 for (; (u_buf < buf_end) && (retval == 1); u_buf += sizeof(struct kdirent)){
977 /* TODO: UMEM/KFOP (pin the u_buf in the syscall, ditch the local copy,
978 * get rid of this memcpy and reliance on current, etc). Might be
979 * tricky with the dirent->d_off and trust issues */
980 retval = file->f_op->readdir(file, dirent);
985 /* Slight info exposure: could be extra crap after the name in the
986 * dirent (like the name of a deleted file) */
988 memcpy_to_user(current, u_buf, dirent, sizeof(struct dirent));
990 memcpy(u_buf, dirent, sizeof(struct dirent));
992 amt_copied += sizeof(struct dirent);
994 /* Next time read is called, we pick up where we left off */
995 *offset = dirent->d_off; /* UMEM */
996 /* important to tell them how much they got. they often keep going til they
997 * get 0 back (in the case of ls). it's also how much has been read, but it
998 * isn't how much the f_pos has moved (which is opaque to the VFS). */
1002 /* Opens the file, using permissions from current for lack of a better option.
1003 * It will attempt to create the file if it does not exist and O_CREAT is
1004 * specified. This will return 0 on failure, and set errno. TODO: There's some
1005 * stuff that we don't do, esp related file truncating/creation. flags are for
1006 * opening, the mode is for creating. The flags related to how to create
1007 * (O_CREAT_FLAGS) are handled in this function, not in create_file().
1009 * It's tempting to split this into a do_file_create and a do_file_open, based
1010 * on the O_CREAT flag, but the O_CREAT flag can be ignored if the file exists
1011 * already and O_EXCL isn't specified. We could have open call create if it
1012 * fails, but for now we'll keep it as is. */
1013 struct file *do_file_open(char *path, int flags, int mode)
1015 struct file *file = 0;
1016 struct dentry *file_d;
1017 struct inode *parent_i;
1018 struct nameidata nd_r = {0}, *nd = &nd_r;
1021 /* The file might exist, lets try to just open it right away */
1022 nd->intent = LOOKUP_OPEN;
1023 error = path_lookup(path, LOOKUP_FOLLOW, nd);
1025 /* Still need to make sure we didn't want to O_EXCL create */
1026 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1030 file_d = nd->dentry;
1031 kref_get(&file_d->d_kref, 1);
1034 /* So it didn't already exist, release the path from the previous lookup,
1035 * and then we try to create it. */
1037 /* get the parent, following links. this means you get the parent of the
1038 * final link (which may not be in 'path' in the first place. */
1039 nd->intent = LOOKUP_CREATE;
1040 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1045 /* see if the target is there (shouldn't be), and handle accordingly */
1046 file_d = do_lookup(nd->dentry, nd->last.name);
1048 if (!(flags & O_CREAT)) {
1052 /* Create the inode/file. get a fresh dentry too: */
1053 file_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1054 parent_i = nd->dentry->d_inode;
1055 /* Note that the mode technically should only apply to future opens,
1056 * but we apply it immediately. */
1057 if (create_file(parent_i, file_d, mode)) /* sets errno */
1060 } else { /* something already exists */
1061 /* this can happen due to concurrent access, but needs to be thought
1063 panic("File shouldn't be here!");
1064 if ((flags & O_CREAT) && (flags & O_EXCL)) {
1065 /* wanted to create, not open, bail out */
1071 /* now open the file (freshly created or if it already existed). At this
1072 * point, file_d is a refcnt'd dentry, regardless of which branch we took.*/
1073 if (flags & O_TRUNC)
1074 warn("File truncation not supported yet.");
1075 file = dentry_open(file_d, flags); /* sets errno */
1076 /* Note the fall through to the exit paths. File is 0 by default and if
1077 * dentry_open fails. */
1079 kref_put(&file_d->d_kref);
1085 /* Path is the location of the symlink, sometimes called the "new path", and
1086 * symname is who we link to, sometimes called the "old path". */
1087 int do_symlink(char *path, const char *symname, int mode)
1089 struct dentry *sym_d;
1090 struct inode *parent_i;
1091 struct nameidata nd_r = {0}, *nd = &nd_r;
1095 nd->intent = LOOKUP_CREATE;
1096 /* get the parent, but don't follow links */
1097 error = path_lookup(path, LOOKUP_PARENT, nd);
1102 /* see if the target is already there, handle accordingly */
1103 sym_d = do_lookup(nd->dentry, nd->last.name);
1108 /* Doesn't already exist, let's try to make it: */
1109 sym_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1114 parent_i = nd->dentry->d_inode;
1115 if (create_symlink(parent_i, sym_d, symname, mode))
1118 retval = 0; /* Note the fall through to the exit paths */
1120 kref_put(&sym_d->d_kref);
1126 /* Makes a hard link for the file behind old_path to new_path */
1127 int do_link(char *old_path, char *new_path)
1129 struct dentry *link_d, *old_d;
1130 struct inode *inode, *parent_dir;
1131 struct nameidata nd_r = {0}, *nd = &nd_r;
1135 nd->intent = LOOKUP_CREATE;
1136 /* get the absolute parent of the new_path */
1137 error = path_lookup(new_path, LOOKUP_PARENT | LOOKUP_FOLLOW, nd);
1142 parent_dir = nd->dentry->d_inode;
1143 /* see if the new target is already there, handle accordingly */
1144 link_d = do_lookup(nd->dentry, nd->last.name);
1149 /* Doesn't already exist, let's try to make it. Still need to stitch it to
1150 * an inode and set its FS-specific stuff after this.*/
1151 link_d = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1156 /* Now let's get the old_path target */
1157 old_d = lookup_dentry(old_path, LOOKUP_FOLLOW);
1158 if (!old_d) /* errno set by lookup_dentry */
1160 /* For now, can only link to files */
1161 if (!S_ISREG(old_d->d_inode->i_mode)) {
1165 /* Must be on the same FS */
1166 if (old_d->d_sb != link_d->d_sb) {
1170 /* Do whatever FS specific stuff there is first (which is also a chance to
1172 error = parent_dir->i_op->link(old_d, parent_dir, link_d);
1177 /* Finally stitch it up */
1178 inode = old_d->d_inode;
1179 kref_get(&inode->i_kref, 1);
1180 link_d->d_inode = inode;
1182 TAILQ_INSERT_TAIL(&inode->i_dentry, link_d, d_alias); /* weak ref */
1184 retval = 0; /* Note the fall through to the exit paths */
1186 kref_put(&old_d->d_kref);
1188 kref_put(&link_d->d_kref);
1194 /* Unlinks path from the directory tree. Read the Documentation for more info.
1196 int do_unlink(char *path)
1198 struct dentry *dentry;
1199 struct inode *parent_dir;
1200 struct nameidata nd_r = {0}, *nd = &nd_r;
1204 /* get the parent of the target, and don't follow a final link */
1205 error = path_lookup(path, LOOKUP_PARENT, nd);
1210 parent_dir = nd->dentry->d_inode;
1211 /* make sure the target is there */
1212 dentry = do_lookup(nd->dentry, nd->last.name);
1217 /* Make sure the target is not a directory */
1218 if (S_ISDIR(dentry->d_inode->i_mode)) {
1222 /* Remove the dentry from its parent */
1223 error = parent_dir->i_op->unlink(parent_dir, dentry);
1228 kref_put(&dentry->d_parent->d_kref);
1229 dentry->d_parent = 0; /* so we don't double-decref it later */
1230 dentry->d_inode->i_nlink--; /* TODO: race here, esp with a decref */
1231 /* At this point, the dentry is unlinked from the FS, and the inode has one
1232 * less link. When the in-memory objects (dentry, inode) are going to be
1233 * released (after all open files are closed, and maybe after entries are
1234 * evicted from the cache), then nlinks will get checked and the FS-file
1235 * will get removed from the disk */
1236 retval = 0; /* Note the fall through to the exit paths */
1238 kref_put(&dentry->d_kref);
1244 /* Checks to see if path can be accessed via mode. Need to actually send the
1245 * mode along somehow, so this doesn't do much now. This is an example of
1246 * decent error propagation from the lower levels via int retvals. */
1247 int do_access(char *path, int mode)
1249 struct nameidata nd_r = {0}, *nd = &nd_r;
1251 nd->intent = LOOKUP_ACCESS;
1252 retval = path_lookup(path, 0, nd);
1257 int do_chmod(char *path, int mode)
1259 struct nameidata nd_r = {0}, *nd = &nd_r;
1261 retval = path_lookup(path, 0, nd);
1264 /* TODO: when we have notions of uid, check for the proc's uid */
1265 if (nd->dentry->d_inode->i_uid != UID_OF_ME)
1269 nd->dentry->d_inode->i_mode |= mode & S_PMASK;
1275 /* Make a directory at path with mode. Returns -1 and sets errno on errors */
1276 int do_mkdir(char *path, int mode)
1278 struct dentry *dentry;
1279 struct inode *parent_i;
1280 struct nameidata nd_r = {0}, *nd = &nd_r;
1284 nd->intent = LOOKUP_CREATE;
1285 /* get the parent, but don't follow links */
1286 error = path_lookup(path, LOOKUP_PARENT, nd);
1291 /* see if the target is already there, handle accordingly */
1292 dentry = do_lookup(nd->dentry, nd->last.name);
1297 /* Doesn't already exist, let's try to make it: */
1298 dentry = get_dentry(nd->dentry->d_sb, nd->dentry, nd->last.name);
1303 parent_i = nd->dentry->d_inode;
1304 if (create_dir(parent_i, dentry, mode))
1307 retval = 0; /* Note the fall through to the exit paths */
1309 kref_put(&dentry->d_kref);
1315 int do_rmdir(char *path)
1317 struct dentry *dentry;
1318 struct inode *parent_i;
1319 struct nameidata nd_r = {0}, *nd = &nd_r;
1323 /* get the parent, following links (probably want this), and we must get a
1324 * directory. Note, current versions of path_lookup can't handle both
1325 * PARENT and DIRECTORY, at least, it doesn't check that *path is a
1327 error = path_lookup(path, LOOKUP_PARENT | LOOKUP_FOLLOW | LOOKUP_DIRECTORY,
1333 /* make sure the target is already there, handle accordingly */
1334 dentry = do_lookup(nd->dentry, nd->last.name);
1339 if (!S_ISDIR(dentry->d_inode->i_mode)) {
1343 /* TODO: make sure we aren't a mount or processes root (EBUSY) */
1344 /* Now for the removal. the FSs will check if they are empty */
1345 parent_i = nd->dentry->d_inode;
1346 error = parent_i->i_op->rmdir(parent_i, dentry);
1351 /* Decref ourselves, so inode_release() knows we are done */
1352 dentry->d_inode->i_nlink--;
1353 TAILQ_REMOVE(&nd->dentry->d_subdirs, dentry, d_subdirs_link);
1354 parent_i->i_nlink--; /* TODO: race on this, esp since its a decref */
1355 /* we still have d_parent and a kref on our parent, which will go away when
1356 * the in-memory dentry object goes away. */
1357 retval = 0; /* Note the fall through to the exit paths */
1359 kref_put(&dentry->d_kref);
1365 /* Opens and returns the file specified by dentry */
1366 struct file *dentry_open(struct dentry *dentry, int flags)
1368 struct inode *inode;
1370 struct file *file = kmem_cache_alloc(file_kcache, 0);
1375 inode = dentry->d_inode;
1376 /* Do the mode first, since we can still error out. f_mode stores how the
1377 * OS file is open, which can be more restrictive than the i_mode */
1378 switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) {
1380 desired_mode = S_IRUSR;
1383 desired_mode = S_IWUSR;
1386 desired_mode = S_IRUSR | S_IWUSR;
1391 if (check_perms(inode, desired_mode))
1393 file->f_mode = desired_mode;
1394 /* one for the ref passed out, and *none* for the sb TAILQ */
1395 kref_init(&file->f_kref, file_release, 1);
1396 /* Add to the list of all files of this SB */
1397 TAILQ_INSERT_TAIL(&inode->i_sb->s_files, file, f_list);
1398 kref_get(&dentry->d_kref, 1);
1399 file->f_dentry = dentry;
1400 kref_get(&inode->i_sb->s_mount->mnt_kref, 1);
1401 file->f_vfsmnt = inode->i_sb->s_mount; /* saving a ref to the vmnt...*/
1402 file->f_op = inode->i_fop;
1403 /* Don't store open mode or creation flags */
1404 file->f_flags = flags & ~(O_ACCMODE | O_CREAT_FLAGS);
1406 file->f_uid = inode->i_uid;
1407 file->f_gid = inode->i_gid;
1409 // struct event_poll_tailq f_ep_links;
1410 spinlock_init(&file->f_ep_lock);
1411 file->f_fs_info = 0; /* prob overriden by the fs */
1412 file->f_mapping = inode->i_mapping;
1413 file->f_op->open(inode, file);
1417 kmem_cache_free(file_kcache, file);
1421 /* Closes a file, fsync, whatever else is necessary. Called when the kref hits
1422 * 0. Note that the file is not refcounted on the s_files list, nor is the
1423 * f_mapping refcounted (it is pinned by the i_mapping). */
1424 void file_release(struct kref *kref)
1426 struct file *file = container_of(kref, struct file, f_kref);
1428 struct super_block *sb = file->f_dentry->d_sb;
1429 spin_lock(&sb->s_lock);
1430 TAILQ_REMOVE(&sb->s_files, file, f_list);
1431 spin_unlock(&sb->s_lock);
1433 /* TODO: fsync (BLK). also, we may want to parallelize the blocking that
1434 * could happen in here (spawn kernel threads)... */
1435 file->f_op->release(file->f_dentry->d_inode, file);
1436 /* Clean up the other refs we hold */
1437 kref_put(&file->f_dentry->d_kref);
1438 kref_put(&file->f_vfsmnt->mnt_kref);
1439 kmem_cache_free(file_kcache, file);
1442 /* Page cache functions */
1444 /* Looks up the index'th page in the page map, returning an incref'd reference,
1445 * or 0 if it was not in the map. */
1446 struct page *pm_find_page(struct page_map *pm, unsigned long index)
1448 spin_lock(&pm->pm_tree_lock);
1449 struct page *page = (struct page*)radix_lookup(&pm->pm_tree, index);
1452 spin_unlock(&pm->pm_tree_lock);
1456 /* Attempts to insert the page into the page_map, returns 0 for success, or an
1457 * error code if there was one already (EEXIST) or we ran out of memory
1458 * (ENOMEM). On success, this will preemptively lock the page, and will also
1459 * store a reference to the page in the pm. */
1460 int pm_insert_page(struct page_map *pm, unsigned long index, struct page *page)
1463 spin_lock(&pm->pm_tree_lock);
1464 error = radix_insert(&pm->pm_tree, index, page);
1467 page->pg_flags |= PG_LOCKED;
1468 page->pg_mapping = pm;
1469 page->pg_index = index;
1472 spin_unlock(&pm->pm_tree_lock);
1476 /* Removes the page, including its reference. Not sure yet what interface we
1477 * want to this (pm and index or page), and this has never been used. There are
1478 * also issues with when you want to call this, since a page in the cache may be
1479 * mmap'd by someone else. */
1480 int pm_remove_page(struct page_map *pm, struct page *page)
1483 warn("pm_remove_page() hasn't been thought through or tested.");
1484 spin_lock(&pm->pm_tree_lock);
1485 retval = radix_delete(&pm->pm_tree, page->pg_index);
1486 spin_unlock(&pm->pm_tree_lock);
1487 assert(retval == (void*)page);
1489 page->pg_mapping = 0;
1495 /* Makes sure the index'th page from file is loaded in the page cache and
1496 * returns its location via **pp. Note this will give you a refcnt'd reference.
1497 * This may block! TODO: (BLK) */
1498 int file_load_page(struct file *file, unsigned long index, struct page **pp)
1500 struct page_map *pm = file->f_mapping;
1503 bool page_was_mapped = TRUE;
1505 page = pm_find_page(pm, index);
1507 /* kpage_alloc, since we want the page to persist after the proc
1508 * dies (can be used by others, until the inode shuts down). */
1509 if (kpage_alloc(&page))
1511 /* might want to initialize other things, perhaps in page_alloc() */
1513 error = pm_insert_page(pm, index, page);
1516 page_was_mapped = FALSE;
1519 /* the page was mapped already (benign race), just get rid of
1520 * our page and try again (the only case that uses the while) */
1522 page = pm_find_page(pm, index);
1525 /* something is wrong, bail out! */
1531 /* if the page was in the map, we need to do some checks, and might have to
1532 * read in the page later. If the page was freshly inserted to the pm by
1533 * us, we skip this since we are the one doing the readpage(). */
1534 if (page_was_mapped) {
1535 /* is it already here and up to date? if so, we're done */
1536 if (page->pg_flags & PG_UPTODATE)
1538 /* if not, try to lock the page (could BLOCK) */
1540 /* we got it, is our page still in the cache? check the mapping. if
1541 * not, start over, perhaps with EAGAIN and outside support */
1542 if (!page->pg_mapping)
1543 panic("Page is not in the mapping! Haven't implemented this!");
1544 /* double check, are we up to date? if so, we're done */
1545 if (page->pg_flags & PG_UPTODATE) {
1550 /* if we're here, the page is locked by us, and it needs to be read in */
1551 assert(page->pg_mapping == pm);
1552 error = pm->pm_op->readpage(file, page);
1554 /* Try to sleep on the IO. The page will be unlocked when the IO is done */
1557 assert(page->pg_flags & PG_UPTODATE);
1561 /* Process-related File management functions */
1563 /* Given any FD, get the appropriate file, 0 o/w */
1564 struct file *get_file_from_fd(struct files_struct *open_files, int file_desc)
1566 struct file *retval = 0;
1569 spin_lock(&open_files->lock);
1570 if (file_desc < open_files->max_fdset) {
1571 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
1572 /* while max_files and max_fdset might not line up, we should never
1573 * have a valid fdset higher than files */
1574 assert(file_desc < open_files->max_files);
1575 retval = open_files->fd[file_desc];
1577 kref_get(&retval->f_kref, 1);
1580 spin_unlock(&open_files->lock);
1584 /* Remove FD from the open files, if it was there, and return f. Currently,
1585 * this decref's f, so the return value is not consumable or even usable. This
1586 * hasn't been thought through yet. */
1587 struct file *put_file_from_fd(struct files_struct *open_files, int file_desc)
1589 struct file *file = 0;
1592 spin_lock(&open_files->lock);
1593 if (file_desc < open_files->max_fdset) {
1594 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc)) {
1595 /* while max_files and max_fdset might not line up, we should never
1596 * have a valid fdset higher than files */
1597 assert(file_desc < open_files->max_files);
1598 file = open_files->fd[file_desc];
1599 open_files->fd[file_desc] = 0;
1601 kref_put(&file->f_kref);
1602 CLR_BITMASK_BIT(open_files->open_fds->fds_bits, file_desc);
1605 spin_unlock(&open_files->lock);
1609 /* Inserts the file in the files_struct, returning the corresponding new file
1610 * descriptor, or an error code. We start looking for open fds from low_fd. */
1611 int insert_file(struct files_struct *open_files, struct file *file, int low_fd)
1614 if ((low_fd < 0) || (low_fd > NR_FILE_DESC_MAX))
1616 spin_lock(&open_files->lock);
1617 for (int i = low_fd; i < open_files->max_fdset; i++) {
1618 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i))
1621 SET_BITMASK_BIT(open_files->open_fds->fds_bits, slot);
1622 assert(slot < open_files->max_files && open_files->fd[slot] == 0);
1623 kref_get(&file->f_kref, 1);
1624 open_files->fd[slot] = file;
1625 if (slot >= open_files->next_fd)
1626 open_files->next_fd = slot + 1;
1629 if (slot == -1) /* should expand the FD array and fd_set */
1630 warn("Ran out of file descriptors, deal with me!");
1631 spin_unlock(&open_files->lock);
1635 /* Closes all open files. Mostly just a "put" for all files. If cloexec, it
1636 * will only close files that are opened with O_CLOEXEC. */
1637 void close_all_files(struct files_struct *open_files, bool cloexec)
1640 spin_lock(&open_files->lock);
1641 for (int i = 0; i < open_files->max_fdset; i++) {
1642 if (GET_BITMASK_BIT(open_files->open_fds->fds_bits, i)) {
1643 /* while max_files and max_fdset might not line up, we should never
1644 * have a valid fdset higher than files */
1645 assert(i < open_files->max_files);
1646 file = open_files->fd[i];
1647 if (cloexec && !(file->f_flags & O_CLOEXEC))
1649 /* Actually close the file */
1650 open_files->fd[i] = 0;
1652 kref_put(&file->f_kref);
1653 CLR_BITMASK_BIT(open_files->open_fds->fds_bits, i);
1656 spin_unlock(&open_files->lock);
1659 /* Inserts all of the files from src into dst, used by sys_fork(). */
1660 void clone_files(struct files_struct *src, struct files_struct *dst)
1663 spin_lock(&src->lock);
1664 spin_lock(&dst->lock);
1665 for (int i = 0; i < src->max_fdset; i++) {
1666 if (GET_BITMASK_BIT(src->open_fds->fds_bits, i)) {
1667 /* while max_files and max_fdset might not line up, we should never
1668 * have a valid fdset higher than files */
1669 assert(i < src->max_files);
1671 assert(i < dst->max_files && dst->fd[i] == 0);
1672 SET_BITMASK_BIT(dst->open_fds->fds_bits, i);
1675 kref_get(&file->f_kref, 1);
1676 if (i >= dst->next_fd)
1677 dst->next_fd = i + 1;
1680 spin_unlock(&dst->lock);
1681 spin_unlock(&src->lock);
1684 /* Change the working directory of the given fs env (one per process, at this
1685 * point). Returns 0 for success, -ERROR for whatever error. */
1686 int do_chdir(struct fs_struct *fs_env, char *path)
1688 struct nameidata nd_r = {0}, *nd = &nd_r;
1690 retval = path_lookup(path, LOOKUP_DIRECTORY, nd);
1692 /* nd->dentry is the place we want our PWD to be */
1693 kref_get(&nd->dentry->d_kref, 1);
1694 kref_put(&fs_env->pwd->d_kref);
1695 fs_env->pwd = nd->dentry;
1701 /* Returns a null-terminated string of up to length cwd_l containing the
1702 * absolute path of fs_env, (up to fs_env's root). Be sure to kfree the char*
1703 * "kfree_this" when you are done with it. We do this since it's easier to
1704 * build this string going backwards. Note cwd_l is not a strlen, it's an
1706 char *do_getcwd(struct fs_struct *fs_env, char **kfree_this, size_t cwd_l)
1708 struct dentry *dentry = fs_env->pwd;
1710 char *path_start, *kbuf;
1716 kbuf = kmalloc(cwd_l, 0);
1722 kbuf[cwd_l - 1] = '\0';
1723 kbuf[cwd_l - 2] = '/';
1724 /* for each dentry in the path, all the way back to the root of fs_env, we
1725 * grab the dentry name, push path_start back enough, and write in the name,
1726 * using /'s to terminate. We skip the root, since we don't want it's
1727 * actual name, just "/", which is set before each loop. */
1728 path_start = kbuf + cwd_l - 2; /* the last byte written */
1729 while (dentry != fs_env->root) {
1730 link_len = dentry->d_name.len; /* this does not count the \0 */
1731 if (path_start - (link_len + 2) < kbuf) {
1736 path_start -= link_len + 1; /* the 1 is for the \0 */
1737 strncpy(path_start, dentry->d_name.name, link_len);
1740 dentry = dentry->d_parent;
1745 static void print_dir(struct dentry *dentry, char *buf, int depth)
1747 struct dentry *child_d;
1748 struct dirent next = {0};
1752 if (!S_ISDIR(dentry->d_inode->i_mode)) {
1753 warn("Thought this was only directories!!");
1756 /* Print this dentry */
1757 printk("%s%s/ nlink: %d\n", buf, dentry->d_name.name,
1758 dentry->d_inode->i_nlink);
1759 if (dentry->d_mount_point) {
1760 dentry = dentry->d_mounted_fs->mnt_root;
1764 /* Set buffer for our kids */
1766 dir = dentry_open(dentry, 0);
1768 panic("Filesystem seems inconsistent - unable to open a dir!");
1769 /* Process every child, recursing on directories */
1771 retval = dir->f_op->readdir(dir, &next);
1773 /* Skip .., ., and empty entries */
1774 if (!strcmp("..", next.d_name) || !strcmp(".", next.d_name) ||
1777 /* there is an entry, now get its dentry */
1778 child_d = do_lookup(dentry, next.d_name);
1780 panic("Inconsistent FS, dirent doesn't have a dentry!");
1781 /* Recurse for directories, or just print the name for others */
1782 switch (child_d->d_inode->i_mode & __S_IFMT) {
1784 print_dir(child_d, buf, depth + 1);
1787 printk("%s%s size(B): %d nlink: %d\n", buf, next.d_name,
1788 child_d->d_inode->i_size, child_d->d_inode->i_nlink);
1791 printk("%s%s -> %s\n", buf, next.d_name,
1792 child_d->d_inode->i_op->readlink(child_d));
1795 printk("%s%s (char device) nlink: %d\n", buf, next.d_name,
1796 child_d->d_inode->i_nlink);
1799 printk("%s%s (block device) nlink: %d\n", buf, next.d_name,
1800 child_d->d_inode->i_nlink);
1803 warn("Look around you! Unknown filetype!");
1805 kref_put(&child_d->d_kref);
1811 /* Reset buffer to the way it was */
1813 kref_put(&dir->f_kref);
1817 int ls_dash_r(char *path)
1819 struct nameidata nd_r = {0}, *nd = &nd_r;
1823 error = path_lookup(path, LOOKUP_ACCESS | LOOKUP_DIRECTORY, nd);
1828 print_dir(nd->dentry, buf, 0);