Skip to contentSkip to conversation

kernel space getcwd()? (using current() to find out cwd)

DISCUSSION Brian J. Watson 1 participant 2 messages Apr 17, 2001

lore
Share & tools
lore
#0 lore raw
Quoted 6 lines

This is probably a stupid question, and probably directed to the wrong list. Apologies in advance, but I'm stumped

I've been working on a kernel module to report on "changed files". It works just fine -- I wrap the orignal system calls with my [...]

At least in the 2.4 kernels, there's already a __d_path() routine (fs/dcache.c) that builds the pathname using the mechanism you discussed.

Here's one way you could use it:

char *
kgetcwd()

{
	char *path = (char *) __get_free_page(GFP_USER);
        struct vfsmnt *pwdmnt;
        struct dentry *pwd;

        if (!path)
                return ERR_PTR(-ENOMEM);

        read_lock(&current->fs->lock);
        pwdmnt = mntget(current->fs->pwdmnt);
        pwd = dget(current->fs->pwd);
        read_unlock(&current->fs->lock);

        spin_lock(&dcache_lock);
        path = __d_path(pwd, pwdmnt, NULL, NULL, path, PAGE_SIZE);
        spin_unlock(&dcache_lock);

        mntput(pwdmnt);
        dput(pwd);

        return path;
}

If you only want the pathname back to the process root, use d_path() instead (and don't grab the dcache_lock).

When you're done with path, free it with free_page() and not kfree().

BTW, I'm not subscribed to the kernel mailing list (I just read it on the web), so please copy me on any response.

--
Brian Watson
Compaq Computer

#1 lore raw
Quoted 1 line · Brian J. Watson
        path = __d_path(pwd, pwdmnt, NULL, NULL, path, PAGE_SIZE);

Oops! That's no good. Here's the new and improved version:

char *
kgetcwd(char **bufp)

{
        char *path, *buf = (char *) __get_free_page(GFP_USER);
        struct vfsmnt *pwdmnt;
        struct dentry *pwd;

        *bufp = NULL;
        if (!buf)
                return ERR_PTR(-ENOMEM);

        read_lock(&current->fs->lock);
        pwdmnt = mntget(current->fs->pwdmnt);
        pwd = dget(current->fs->pwd);
        read_unlock(&current->fs->lock);

        spin_lock(&dcache_lock);
        path = __d_path(pwd, pwdmnt, NULL, NULL, buf, PAGE_SIZE);
        spin_unlock(&dcache_lock);

        mntput(pwdmnt);
        dput(pwd);

        *bufp = buf;
        return path;
}

The returned pointer is for the beginning of the path name. The pointer filled into bufp is for the beginning of the allocated space. To deallocate, call free_page() on the value in bufp.

The reason for the distinction is that __d_path builds the pathname from the end of the buffer, working its way back toward the beginning. Rarely will the string begin at the same address as the allocated buffer.

--
Brian Watson
Compaq Computer