• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  inode.c - part of debugfs, a tiny little debug file system
4  *
5  *  Copyright (C) 2004,2019 Greg Kroah-Hartman <greg@kroah.com>
6  *  Copyright (C) 2004 IBM Inc.
7  *  Copyright (C) 2019 Linux Foundation <gregkh@linuxfoundation.org>
8  *
9  *  debugfs is for people to use instead of /proc or /sys.
10  *  See ./Documentation/core-api/kernel-api.rst for more details.
11  */
12 
13 #define pr_fmt(fmt)	"debugfs: " fmt
14 
15 #include <linux/module.h>
16 #include <linux/fs.h>
17 #include <linux/fs_context.h>
18 #include <linux/fs_parser.h>
19 #include <linux/pagemap.h>
20 #include <linux/init.h>
21 #include <linux/kobject.h>
22 #include <linux/namei.h>
23 #include <linux/debugfs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/string.h>
26 #include <linux/seq_file.h>
27 #include <linux/magic.h>
28 #include <linux/slab.h>
29 #include <linux/security.h>
30 
31 #include "internal.h"
32 
33 #define DEBUGFS_DEFAULT_MODE	0700
34 
35 static struct vfsmount *debugfs_mount;
36 static int debugfs_mount_count;
37 static bool debugfs_registered;
38 static unsigned int debugfs_allow __ro_after_init = DEFAULT_DEBUGFS_ALLOW_BITS;
39 
40 /*
41  * Don't allow access attributes to be changed whilst the kernel is locked down
42  * so that we can use the file mode as part of a heuristic to determine whether
43  * to lock down individual files.
44  */
debugfs_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * ia)45 static int debugfs_setattr(struct mnt_idmap *idmap,
46 			   struct dentry *dentry, struct iattr *ia)
47 {
48 	int ret;
49 
50 	if (ia->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)) {
51 		ret = security_locked_down(LOCKDOWN_DEBUGFS);
52 		if (ret)
53 			return ret;
54 	}
55 	return simple_setattr(&nop_mnt_idmap, dentry, ia);
56 }
57 
58 static const struct inode_operations debugfs_file_inode_operations = {
59 	.setattr	= debugfs_setattr,
60 };
61 static const struct inode_operations debugfs_dir_inode_operations = {
62 	.lookup		= simple_lookup,
63 	.setattr	= debugfs_setattr,
64 };
65 static const struct inode_operations debugfs_symlink_inode_operations = {
66 	.get_link	= simple_get_link,
67 	.setattr	= debugfs_setattr,
68 };
69 
debugfs_get_inode(struct super_block * sb)70 static struct inode *debugfs_get_inode(struct super_block *sb)
71 {
72 	struct inode *inode = new_inode(sb);
73 	if (inode) {
74 		inode->i_ino = get_next_ino();
75 		simple_inode_init_ts(inode);
76 	}
77 	return inode;
78 }
79 
80 struct debugfs_fs_info {
81 	kuid_t uid;
82 	kgid_t gid;
83 	umode_t mode;
84 	/* Opt_* bitfield. */
85 	unsigned int opts;
86 };
87 
88 enum {
89 	Opt_uid,
90 	Opt_gid,
91 	Opt_mode,
92 	Opt_source,
93 };
94 
95 static const struct fs_parameter_spec debugfs_param_specs[] = {
96 	fsparam_gid	("gid",		Opt_gid),
97 	fsparam_u32oct	("mode",	Opt_mode),
98 	fsparam_uid	("uid",		Opt_uid),
99 	fsparam_string	("source",	Opt_source),
100 	{}
101 };
102 
debugfs_parse_param(struct fs_context * fc,struct fs_parameter * param)103 static int debugfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
104 {
105 	struct debugfs_fs_info *opts = fc->s_fs_info;
106 	struct fs_parse_result result;
107 	int opt;
108 
109 	opt = fs_parse(fc, debugfs_param_specs, param, &result);
110 	if (opt < 0) {
111 		/*
112                 * We might like to report bad mount options here; but
113                 * traditionally debugfs has ignored all mount options
114                 */
115 		if (opt == -ENOPARAM)
116 			return 0;
117 
118 		return opt;
119 	}
120 
121 	switch (opt) {
122 	case Opt_uid:
123 		opts->uid = result.uid;
124 		break;
125 	case Opt_gid:
126 		opts->gid = result.gid;
127 		break;
128 	case Opt_mode:
129 		opts->mode = result.uint_32 & S_IALLUGO;
130 		break;
131 	case Opt_source:
132 		if (fc->source)
133 			return invalfc(fc, "Multiple sources specified");
134 		fc->source = param->string;
135 		param->string = NULL;
136 		break;
137 	/*
138 	 * We might like to report bad mount options here;
139 	 * but traditionally debugfs has ignored all mount options
140 	 */
141 	}
142 
143 	opts->opts |= BIT(opt);
144 
145 	return 0;
146 }
147 
_debugfs_apply_options(struct super_block * sb,bool remount)148 static void _debugfs_apply_options(struct super_block *sb, bool remount)
149 {
150 	struct debugfs_fs_info *fsi = sb->s_fs_info;
151 	struct inode *inode = d_inode(sb->s_root);
152 
153 	/*
154 	 * On remount, only reset mode/uid/gid if they were provided as mount
155 	 * options.
156 	 */
157 
158 	if (!remount || fsi->opts & BIT(Opt_mode)) {
159 		inode->i_mode &= ~S_IALLUGO;
160 		inode->i_mode |= fsi->mode;
161 	}
162 
163 	if (!remount || fsi->opts & BIT(Opt_uid))
164 		inode->i_uid = fsi->uid;
165 
166 	if (!remount || fsi->opts & BIT(Opt_gid))
167 		inode->i_gid = fsi->gid;
168 }
169 
debugfs_apply_options(struct super_block * sb)170 static void debugfs_apply_options(struct super_block *sb)
171 {
172 	_debugfs_apply_options(sb, false);
173 }
174 
debugfs_apply_options_remount(struct super_block * sb)175 static void debugfs_apply_options_remount(struct super_block *sb)
176 {
177 	_debugfs_apply_options(sb, true);
178 }
179 
debugfs_reconfigure(struct fs_context * fc)180 static int debugfs_reconfigure(struct fs_context *fc)
181 {
182 	struct super_block *sb = fc->root->d_sb;
183 	struct debugfs_fs_info *sb_opts = sb->s_fs_info;
184 	struct debugfs_fs_info *new_opts = fc->s_fs_info;
185 
186 	if (!new_opts)
187 		return 0;
188 
189 	sync_filesystem(sb);
190 
191 	/* structure copy of new mount options to sb */
192 	*sb_opts = *new_opts;
193 	debugfs_apply_options_remount(sb);
194 
195 	return 0;
196 }
197 
debugfs_show_options(struct seq_file * m,struct dentry * root)198 static int debugfs_show_options(struct seq_file *m, struct dentry *root)
199 {
200 	struct debugfs_fs_info *fsi = root->d_sb->s_fs_info;
201 
202 	if (!uid_eq(fsi->uid, GLOBAL_ROOT_UID))
203 		seq_printf(m, ",uid=%u",
204 			   from_kuid_munged(&init_user_ns, fsi->uid));
205 	if (!gid_eq(fsi->gid, GLOBAL_ROOT_GID))
206 		seq_printf(m, ",gid=%u",
207 			   from_kgid_munged(&init_user_ns, fsi->gid));
208 	if (fsi->mode != DEBUGFS_DEFAULT_MODE)
209 		seq_printf(m, ",mode=%o", fsi->mode);
210 
211 	return 0;
212 }
213 
debugfs_free_inode(struct inode * inode)214 static void debugfs_free_inode(struct inode *inode)
215 {
216 	if (S_ISLNK(inode->i_mode))
217 		kfree(inode->i_link);
218 	free_inode_nonrcu(inode);
219 }
220 
221 static const struct super_operations debugfs_super_operations = {
222 	.statfs		= simple_statfs,
223 	.show_options	= debugfs_show_options,
224 	.free_inode	= debugfs_free_inode,
225 };
226 
debugfs_release_dentry(struct dentry * dentry)227 static void debugfs_release_dentry(struct dentry *dentry)
228 {
229 	struct debugfs_fsdata *fsd = dentry->d_fsdata;
230 
231 	if ((unsigned long)fsd & DEBUGFS_FSDATA_IS_REAL_FOPS_BIT)
232 		return;
233 
234 	/* check it wasn't a dir (no fsdata) or automount (no real_fops) */
235 	if (fsd && fsd->real_fops) {
236 		WARN_ON(!list_empty(&fsd->cancellations));
237 		mutex_destroy(&fsd->cancellations_mtx);
238 	}
239 
240 	kfree(fsd);
241 }
242 
debugfs_automount(struct path * path)243 static struct vfsmount *debugfs_automount(struct path *path)
244 {
245 	struct debugfs_fsdata *fsd = path->dentry->d_fsdata;
246 
247 	return fsd->automount(path->dentry, d_inode(path->dentry)->i_private);
248 }
249 
250 static const struct dentry_operations debugfs_dops = {
251 	.d_delete = always_delete_dentry,
252 	.d_release = debugfs_release_dentry,
253 	.d_automount = debugfs_automount,
254 };
255 
debugfs_fill_super(struct super_block * sb,struct fs_context * fc)256 static int debugfs_fill_super(struct super_block *sb, struct fs_context *fc)
257 {
258 	static const struct tree_descr debug_files[] = {{""}};
259 	int err;
260 
261 	err = simple_fill_super(sb, DEBUGFS_MAGIC, debug_files);
262 	if (err)
263 		return err;
264 
265 	sb->s_op = &debugfs_super_operations;
266 	sb->s_d_op = &debugfs_dops;
267 
268 	debugfs_apply_options(sb);
269 
270 	return 0;
271 }
272 
debugfs_get_tree(struct fs_context * fc)273 static int debugfs_get_tree(struct fs_context *fc)
274 {
275 	int err;
276 
277 	if (!(debugfs_allow & DEBUGFS_ALLOW_API))
278 		return -EPERM;
279 
280 	err = get_tree_single(fc, debugfs_fill_super);
281 	if (err)
282 		return err;
283 
284 	return debugfs_reconfigure(fc);
285 }
286 
debugfs_free_fc(struct fs_context * fc)287 static void debugfs_free_fc(struct fs_context *fc)
288 {
289 	kfree(fc->s_fs_info);
290 }
291 
292 static const struct fs_context_operations debugfs_context_ops = {
293 	.free		= debugfs_free_fc,
294 	.parse_param	= debugfs_parse_param,
295 	.get_tree	= debugfs_get_tree,
296 	.reconfigure	= debugfs_reconfigure,
297 };
298 
debugfs_init_fs_context(struct fs_context * fc)299 static int debugfs_init_fs_context(struct fs_context *fc)
300 {
301 	struct debugfs_fs_info *fsi;
302 
303 	fsi = kzalloc(sizeof(struct debugfs_fs_info), GFP_KERNEL);
304 	if (!fsi)
305 		return -ENOMEM;
306 
307 	fsi->mode = DEBUGFS_DEFAULT_MODE;
308 
309 	fc->s_fs_info = fsi;
310 	fc->ops = &debugfs_context_ops;
311 	return 0;
312 }
313 
314 static struct file_system_type debug_fs_type = {
315 	.owner =	THIS_MODULE,
316 	.name =		"debugfs",
317 	.init_fs_context = debugfs_init_fs_context,
318 	.parameters =	debugfs_param_specs,
319 	.kill_sb =	kill_litter_super,
320 };
321 MODULE_ALIAS_FS("debugfs");
322 
323 /**
324  * debugfs_lookup() - look up an existing debugfs file
325  * @name: a pointer to a string containing the name of the file to look up.
326  * @parent: a pointer to the parent dentry of the file.
327  *
328  * This function will return a pointer to a dentry if it succeeds.  If the file
329  * doesn't exist or an error occurs, %NULL will be returned.  The returned
330  * dentry must be passed to dput() when it is no longer needed.
331  *
332  * If debugfs is not enabled in the kernel, the value -%ENODEV will be
333  * returned.
334  */
debugfs_lookup(const char * name,struct dentry * parent)335 struct dentry *debugfs_lookup(const char *name, struct dentry *parent)
336 {
337 	struct dentry *dentry;
338 
339 	if (!debugfs_initialized() || IS_ERR_OR_NULL(name) || IS_ERR(parent))
340 		return NULL;
341 
342 	if (!parent)
343 		parent = debugfs_mount->mnt_root;
344 
345 	dentry = lookup_positive_unlocked(name, parent, strlen(name));
346 	if (IS_ERR(dentry))
347 		return NULL;
348 	return dentry;
349 }
350 EXPORT_SYMBOL_GPL(debugfs_lookup);
351 
start_creating(const char * name,struct dentry * parent)352 static struct dentry *start_creating(const char *name, struct dentry *parent)
353 {
354 	struct dentry *dentry;
355 	int error;
356 
357 	if (!(debugfs_allow & DEBUGFS_ALLOW_API))
358 		return ERR_PTR(-EPERM);
359 
360 	if (!debugfs_initialized())
361 		return ERR_PTR(-ENOENT);
362 
363 	pr_debug("creating file '%s'\n", name);
364 
365 	if (IS_ERR(parent))
366 		return parent;
367 
368 	error = simple_pin_fs(&debug_fs_type, &debugfs_mount,
369 			      &debugfs_mount_count);
370 	if (error) {
371 		pr_err("Unable to pin filesystem for file '%s'\n", name);
372 		return ERR_PTR(error);
373 	}
374 
375 	/* If the parent is not specified, we create it in the root.
376 	 * We need the root dentry to do this, which is in the super
377 	 * block. A pointer to that is in the struct vfsmount that we
378 	 * have around.
379 	 */
380 	if (!parent)
381 		parent = debugfs_mount->mnt_root;
382 
383 	inode_lock(d_inode(parent));
384 	if (unlikely(IS_DEADDIR(d_inode(parent))))
385 		dentry = ERR_PTR(-ENOENT);
386 	else
387 		dentry = lookup_one_len(name, parent, strlen(name));
388 	if (!IS_ERR(dentry) && d_really_is_positive(dentry)) {
389 		if (d_is_dir(dentry))
390 			pr_err("Directory '%s' with parent '%s' already present!\n",
391 			       name, parent->d_name.name);
392 		else
393 			pr_err("File '%s' in directory '%s' already present!\n",
394 			       name, parent->d_name.name);
395 		dput(dentry);
396 		dentry = ERR_PTR(-EEXIST);
397 	}
398 
399 	if (IS_ERR(dentry)) {
400 		inode_unlock(d_inode(parent));
401 		simple_release_fs(&debugfs_mount, &debugfs_mount_count);
402 	}
403 
404 	return dentry;
405 }
406 
failed_creating(struct dentry * dentry)407 static struct dentry *failed_creating(struct dentry *dentry)
408 {
409 	inode_unlock(d_inode(dentry->d_parent));
410 	dput(dentry);
411 	simple_release_fs(&debugfs_mount, &debugfs_mount_count);
412 	return ERR_PTR(-ENOMEM);
413 }
414 
end_creating(struct dentry * dentry)415 static struct dentry *end_creating(struct dentry *dentry)
416 {
417 	inode_unlock(d_inode(dentry->d_parent));
418 	return dentry;
419 }
420 
__debugfs_create_file(const char * name,umode_t mode,struct dentry * parent,void * data,const struct file_operations * proxy_fops,const struct file_operations * real_fops)421 static struct dentry *__debugfs_create_file(const char *name, umode_t mode,
422 				struct dentry *parent, void *data,
423 				const struct file_operations *proxy_fops,
424 				const struct file_operations *real_fops)
425 {
426 	struct dentry *dentry;
427 	struct inode *inode;
428 
429 	if (!(mode & S_IFMT))
430 		mode |= S_IFREG;
431 	BUG_ON(!S_ISREG(mode));
432 	dentry = start_creating(name, parent);
433 
434 	if (IS_ERR(dentry))
435 		return dentry;
436 
437 	if (!(debugfs_allow & DEBUGFS_ALLOW_API)) {
438 		failed_creating(dentry);
439 		return ERR_PTR(-EPERM);
440 	}
441 
442 	inode = debugfs_get_inode(dentry->d_sb);
443 	if (unlikely(!inode)) {
444 		pr_err("out of free dentries, can not create file '%s'\n",
445 		       name);
446 		return failed_creating(dentry);
447 	}
448 
449 	inode->i_mode = mode;
450 	inode->i_private = data;
451 
452 	inode->i_op = &debugfs_file_inode_operations;
453 	inode->i_fop = proxy_fops;
454 	dentry->d_fsdata = (void *)((unsigned long)real_fops |
455 				DEBUGFS_FSDATA_IS_REAL_FOPS_BIT);
456 
457 	d_instantiate(dentry, inode);
458 	fsnotify_create(d_inode(dentry->d_parent), dentry);
459 	return end_creating(dentry);
460 }
461 
462 /**
463  * debugfs_create_file - create a file in the debugfs filesystem
464  * @name: a pointer to a string containing the name of the file to create.
465  * @mode: the permission that the file should have.
466  * @parent: a pointer to the parent dentry for this file.  This should be a
467  *          directory dentry if set.  If this parameter is NULL, then the
468  *          file will be created in the root of the debugfs filesystem.
469  * @data: a pointer to something that the caller will want to get to later
470  *        on.  The inode.i_private pointer will point to this value on
471  *        the open() call.
472  * @fops: a pointer to a struct file_operations that should be used for
473  *        this file.
474  *
475  * This is the basic "create a file" function for debugfs.  It allows for a
476  * wide range of flexibility in creating a file, or a directory (if you want
477  * to create a directory, the debugfs_create_dir() function is
478  * recommended to be used instead.)
479  *
480  * This function will return a pointer to a dentry if it succeeds.  This
481  * pointer must be passed to the debugfs_remove() function when the file is
482  * to be removed (no automatic cleanup happens if your module is unloaded,
483  * you are responsible here.)  If an error occurs, ERR_PTR(-ERROR) will be
484  * returned.
485  *
486  * If debugfs is not enabled in the kernel, the value -%ENODEV will be
487  * returned.
488  *
489  * NOTE: it's expected that most callers should _ignore_ the errors returned
490  * by this function. Other debugfs functions handle the fact that the "dentry"
491  * passed to them could be an error and they don't crash in that case.
492  * Drivers should generally work fine even if debugfs fails to init anyway.
493  */
debugfs_create_file(const char * name,umode_t mode,struct dentry * parent,void * data,const struct file_operations * fops)494 struct dentry *debugfs_create_file(const char *name, umode_t mode,
495 				   struct dentry *parent, void *data,
496 				   const struct file_operations *fops)
497 {
498 
499 	return __debugfs_create_file(name, mode, parent, data,
500 				fops ? &debugfs_full_proxy_file_operations :
501 					&debugfs_noop_file_operations,
502 				fops);
503 }
504 EXPORT_SYMBOL_GPL(debugfs_create_file);
505 
506 /**
507  * debugfs_create_file_unsafe - create a file in the debugfs filesystem
508  * @name: a pointer to a string containing the name of the file to create.
509  * @mode: the permission that the file should have.
510  * @parent: a pointer to the parent dentry for this file.  This should be a
511  *          directory dentry if set.  If this parameter is NULL, then the
512  *          file will be created in the root of the debugfs filesystem.
513  * @data: a pointer to something that the caller will want to get to later
514  *        on.  The inode.i_private pointer will point to this value on
515  *        the open() call.
516  * @fops: a pointer to a struct file_operations that should be used for
517  *        this file.
518  *
519  * debugfs_create_file_unsafe() is completely analogous to
520  * debugfs_create_file(), the only difference being that the fops
521  * handed it will not get protected against file removals by the
522  * debugfs core.
523  *
524  * It is your responsibility to protect your struct file_operation
525  * methods against file removals by means of debugfs_file_get()
526  * and debugfs_file_put(). ->open() is still protected by
527  * debugfs though.
528  *
529  * Any struct file_operations defined by means of
530  * DEFINE_DEBUGFS_ATTRIBUTE() is protected against file removals and
531  * thus, may be used here.
532  */
debugfs_create_file_unsafe(const char * name,umode_t mode,struct dentry * parent,void * data,const struct file_operations * fops)533 struct dentry *debugfs_create_file_unsafe(const char *name, umode_t mode,
534 				   struct dentry *parent, void *data,
535 				   const struct file_operations *fops)
536 {
537 
538 	return __debugfs_create_file(name, mode, parent, data,
539 				fops ? &debugfs_open_proxy_file_operations :
540 					&debugfs_noop_file_operations,
541 				fops);
542 }
543 EXPORT_SYMBOL_GPL(debugfs_create_file_unsafe);
544 
545 /**
546  * debugfs_create_file_size - create a file in the debugfs filesystem
547  * @name: a pointer to a string containing the name of the file to create.
548  * @mode: the permission that the file should have.
549  * @parent: a pointer to the parent dentry for this file.  This should be a
550  *          directory dentry if set.  If this parameter is NULL, then the
551  *          file will be created in the root of the debugfs filesystem.
552  * @data: a pointer to something that the caller will want to get to later
553  *        on.  The inode.i_private pointer will point to this value on
554  *        the open() call.
555  * @fops: a pointer to a struct file_operations that should be used for
556  *        this file.
557  * @file_size: initial file size
558  *
559  * This is the basic "create a file" function for debugfs.  It allows for a
560  * wide range of flexibility in creating a file, or a directory (if you want
561  * to create a directory, the debugfs_create_dir() function is
562  * recommended to be used instead.)
563  */
debugfs_create_file_size(const char * name,umode_t mode,struct dentry * parent,void * data,const struct file_operations * fops,loff_t file_size)564 void debugfs_create_file_size(const char *name, umode_t mode,
565 			      struct dentry *parent, void *data,
566 			      const struct file_operations *fops,
567 			      loff_t file_size)
568 {
569 	struct dentry *de = debugfs_create_file(name, mode, parent, data, fops);
570 
571 	if (!IS_ERR(de))
572 		d_inode(de)->i_size = file_size;
573 }
574 EXPORT_SYMBOL_GPL(debugfs_create_file_size);
575 
576 /**
577  * debugfs_create_dir - create a directory in the debugfs filesystem
578  * @name: a pointer to a string containing the name of the directory to
579  *        create.
580  * @parent: a pointer to the parent dentry for this file.  This should be a
581  *          directory dentry if set.  If this parameter is NULL, then the
582  *          directory will be created in the root of the debugfs filesystem.
583  *
584  * This function creates a directory in debugfs with the given name.
585  *
586  * This function will return a pointer to a dentry if it succeeds.  This
587  * pointer must be passed to the debugfs_remove() function when the file is
588  * to be removed (no automatic cleanup happens if your module is unloaded,
589  * you are responsible here.)  If an error occurs, ERR_PTR(-ERROR) will be
590  * returned.
591  *
592  * If debugfs is not enabled in the kernel, the value -%ENODEV will be
593  * returned.
594  *
595  * NOTE: it's expected that most callers should _ignore_ the errors returned
596  * by this function. Other debugfs functions handle the fact that the "dentry"
597  * passed to them could be an error and they don't crash in that case.
598  * Drivers should generally work fine even if debugfs fails to init anyway.
599  */
debugfs_create_dir(const char * name,struct dentry * parent)600 struct dentry *debugfs_create_dir(const char *name, struct dentry *parent)
601 {
602 	struct dentry *dentry = start_creating(name, parent);
603 	struct inode *inode;
604 
605 	if (IS_ERR(dentry))
606 		return dentry;
607 
608 	if (!(debugfs_allow & DEBUGFS_ALLOW_API)) {
609 		failed_creating(dentry);
610 		return ERR_PTR(-EPERM);
611 	}
612 
613 	inode = debugfs_get_inode(dentry->d_sb);
614 	if (unlikely(!inode)) {
615 		pr_err("out of free dentries, can not create directory '%s'\n",
616 		       name);
617 		return failed_creating(dentry);
618 	}
619 
620 	inode->i_mode = S_IFDIR | S_IRWXU | S_IRUGO | S_IXUGO;
621 	inode->i_op = &debugfs_dir_inode_operations;
622 	inode->i_fop = &simple_dir_operations;
623 
624 	/* directory inodes start off with i_nlink == 2 (for "." entry) */
625 	inc_nlink(inode);
626 	d_instantiate(dentry, inode);
627 	inc_nlink(d_inode(dentry->d_parent));
628 	fsnotify_mkdir(d_inode(dentry->d_parent), dentry);
629 	return end_creating(dentry);
630 }
631 EXPORT_SYMBOL_GPL(debugfs_create_dir);
632 
633 /**
634  * debugfs_create_automount - create automount point in the debugfs filesystem
635  * @name: a pointer to a string containing the name of the file to create.
636  * @parent: a pointer to the parent dentry for this file.  This should be a
637  *          directory dentry if set.  If this parameter is NULL, then the
638  *          file will be created in the root of the debugfs filesystem.
639  * @f: function to be called when pathname resolution steps on that one.
640  * @data: opaque argument to pass to f().
641  *
642  * @f should return what ->d_automount() would.
643  */
debugfs_create_automount(const char * name,struct dentry * parent,debugfs_automount_t f,void * data)644 struct dentry *debugfs_create_automount(const char *name,
645 					struct dentry *parent,
646 					debugfs_automount_t f,
647 					void *data)
648 {
649 	struct dentry *dentry = start_creating(name, parent);
650 	struct debugfs_fsdata *fsd;
651 	struct inode *inode;
652 
653 	if (IS_ERR(dentry))
654 		return dentry;
655 
656 	fsd = kzalloc(sizeof(*fsd), GFP_KERNEL);
657 	if (!fsd) {
658 		failed_creating(dentry);
659 		return ERR_PTR(-ENOMEM);
660 	}
661 
662 	fsd->automount = f;
663 
664 	if (!(debugfs_allow & DEBUGFS_ALLOW_API)) {
665 		failed_creating(dentry);
666 		kfree(fsd);
667 		return ERR_PTR(-EPERM);
668 	}
669 
670 	inode = debugfs_get_inode(dentry->d_sb);
671 	if (unlikely(!inode)) {
672 		pr_err("out of free dentries, can not create automount '%s'\n",
673 		       name);
674 		kfree(fsd);
675 		return failed_creating(dentry);
676 	}
677 
678 	make_empty_dir_inode(inode);
679 	inode->i_flags |= S_AUTOMOUNT;
680 	inode->i_private = data;
681 	dentry->d_fsdata = fsd;
682 	/* directory inodes start off with i_nlink == 2 (for "." entry) */
683 	inc_nlink(inode);
684 	d_instantiate(dentry, inode);
685 	inc_nlink(d_inode(dentry->d_parent));
686 	fsnotify_mkdir(d_inode(dentry->d_parent), dentry);
687 	return end_creating(dentry);
688 }
689 EXPORT_SYMBOL(debugfs_create_automount);
690 
691 /**
692  * debugfs_create_symlink- create a symbolic link in the debugfs filesystem
693  * @name: a pointer to a string containing the name of the symbolic link to
694  *        create.
695  * @parent: a pointer to the parent dentry for this symbolic link.  This
696  *          should be a directory dentry if set.  If this parameter is NULL,
697  *          then the symbolic link will be created in the root of the debugfs
698  *          filesystem.
699  * @target: a pointer to a string containing the path to the target of the
700  *          symbolic link.
701  *
702  * This function creates a symbolic link with the given name in debugfs that
703  * links to the given target path.
704  *
705  * This function will return a pointer to a dentry if it succeeds.  This
706  * pointer must be passed to the debugfs_remove() function when the symbolic
707  * link is to be removed (no automatic cleanup happens if your module is
708  * unloaded, you are responsible here.)  If an error occurs, ERR_PTR(-ERROR)
709  * will be returned.
710  *
711  * If debugfs is not enabled in the kernel, the value -%ENODEV will be
712  * returned.
713  */
debugfs_create_symlink(const char * name,struct dentry * parent,const char * target)714 struct dentry *debugfs_create_symlink(const char *name, struct dentry *parent,
715 				      const char *target)
716 {
717 	struct dentry *dentry;
718 	struct inode *inode;
719 	char *link = kstrdup(target, GFP_KERNEL);
720 	if (!link)
721 		return ERR_PTR(-ENOMEM);
722 
723 	dentry = start_creating(name, parent);
724 	if (IS_ERR(dentry)) {
725 		kfree(link);
726 		return dentry;
727 	}
728 
729 	inode = debugfs_get_inode(dentry->d_sb);
730 	if (unlikely(!inode)) {
731 		pr_err("out of free dentries, can not create symlink '%s'\n",
732 		       name);
733 		kfree(link);
734 		return failed_creating(dentry);
735 	}
736 	inode->i_mode = S_IFLNK | S_IRWXUGO;
737 	inode->i_op = &debugfs_symlink_inode_operations;
738 	inode->i_link = link;
739 	d_instantiate(dentry, inode);
740 	return end_creating(dentry);
741 }
742 EXPORT_SYMBOL_GPL(debugfs_create_symlink);
743 
__debugfs_file_removed(struct dentry * dentry)744 static void __debugfs_file_removed(struct dentry *dentry)
745 {
746 	struct debugfs_fsdata *fsd;
747 
748 	/*
749 	 * Paired with the closing smp_mb() implied by a successful
750 	 * cmpxchg() in debugfs_file_get(): either
751 	 * debugfs_file_get() must see a dead dentry or we must see a
752 	 * debugfs_fsdata instance at ->d_fsdata here (or both).
753 	 */
754 	smp_mb();
755 	fsd = READ_ONCE(dentry->d_fsdata);
756 	if ((unsigned long)fsd & DEBUGFS_FSDATA_IS_REAL_FOPS_BIT)
757 		return;
758 
759 	/* if this was the last reference, we're done */
760 	if (refcount_dec_and_test(&fsd->active_users))
761 		return;
762 
763 	/*
764 	 * If there's still a reference, the code that obtained it can
765 	 * be in different states:
766 	 *  - The common case of not using cancellations, or already
767 	 *    after debugfs_leave_cancellation(), where we just need
768 	 *    to wait for debugfs_file_put() which signals the completion;
769 	 *  - inside a cancellation section, i.e. between
770 	 *    debugfs_enter_cancellation() and debugfs_leave_cancellation(),
771 	 *    in which case we need to trigger the ->cancel() function,
772 	 *    and then wait for debugfs_file_put() just like in the
773 	 *    previous case;
774 	 *  - before debugfs_enter_cancellation() (but obviously after
775 	 *    debugfs_file_get()), in which case we may not see the
776 	 *    cancellation in the list on the first round of the loop,
777 	 *    but debugfs_enter_cancellation() signals the completion
778 	 *    after adding it, so this code gets woken up to call the
779 	 *    ->cancel() function.
780 	 */
781 	while (refcount_read(&fsd->active_users)) {
782 		struct debugfs_cancellation *c;
783 
784 		/*
785 		 * Lock the cancellations. Note that the cancellations
786 		 * structs are meant to be on the stack, so we need to
787 		 * ensure we either use them here or don't touch them,
788 		 * and debugfs_leave_cancellation() will wait for this
789 		 * to be finished processing before exiting one. It may
790 		 * of course win and remove the cancellation, but then
791 		 * chances are we never even got into this bit, we only
792 		 * do if the refcount isn't zero already.
793 		 */
794 		mutex_lock(&fsd->cancellations_mtx);
795 		while ((c = list_first_entry_or_null(&fsd->cancellations,
796 						     typeof(*c), list))) {
797 			list_del_init(&c->list);
798 			c->cancel(dentry, c->cancel_data);
799 		}
800 		mutex_unlock(&fsd->cancellations_mtx);
801 
802 		wait_for_completion(&fsd->active_users_drained);
803 	}
804 }
805 
remove_one(struct dentry * victim)806 static void remove_one(struct dentry *victim)
807 {
808         if (d_is_reg(victim))
809 		__debugfs_file_removed(victim);
810 	simple_release_fs(&debugfs_mount, &debugfs_mount_count);
811 }
812 
813 /**
814  * debugfs_remove - recursively removes a directory
815  * @dentry: a pointer to a the dentry of the directory to be removed.  If this
816  *          parameter is NULL or an error value, nothing will be done.
817  *
818  * This function recursively removes a directory tree in debugfs that
819  * was previously created with a call to another debugfs function
820  * (like debugfs_create_file() or variants thereof.)
821  *
822  * This function is required to be called in order for the file to be
823  * removed, no automatic cleanup of files will happen when a module is
824  * removed, you are responsible here.
825  */
debugfs_remove(struct dentry * dentry)826 void debugfs_remove(struct dentry *dentry)
827 {
828 	if (IS_ERR_OR_NULL(dentry))
829 		return;
830 
831 	simple_pin_fs(&debug_fs_type, &debugfs_mount, &debugfs_mount_count);
832 	simple_recursive_removal(dentry, remove_one);
833 	simple_release_fs(&debugfs_mount, &debugfs_mount_count);
834 }
835 EXPORT_SYMBOL_GPL(debugfs_remove);
836 
837 /**
838  * debugfs_lookup_and_remove - lookup a directory or file and recursively remove it
839  * @name: a pointer to a string containing the name of the item to look up.
840  * @parent: a pointer to the parent dentry of the item.
841  *
842  * This is the equlivant of doing something like
843  * debugfs_remove(debugfs_lookup(..)) but with the proper reference counting
844  * handled for the directory being looked up.
845  */
debugfs_lookup_and_remove(const char * name,struct dentry * parent)846 void debugfs_lookup_and_remove(const char *name, struct dentry *parent)
847 {
848 	struct dentry *dentry;
849 
850 	dentry = debugfs_lookup(name, parent);
851 	if (!dentry)
852 		return;
853 
854 	debugfs_remove(dentry);
855 	dput(dentry);
856 }
857 EXPORT_SYMBOL_GPL(debugfs_lookup_and_remove);
858 
859 /**
860  * debugfs_rename - rename a file/directory in the debugfs filesystem
861  * @old_dir: a pointer to the parent dentry for the renamed object. This
862  *          should be a directory dentry.
863  * @old_dentry: dentry of an object to be renamed.
864  * @new_dir: a pointer to the parent dentry where the object should be
865  *          moved. This should be a directory dentry.
866  * @new_name: a pointer to a string containing the target name.
867  *
868  * This function renames a file/directory in debugfs.  The target must not
869  * exist for rename to succeed.
870  *
871  * This function will return a pointer to old_dentry (which is updated to
872  * reflect renaming) if it succeeds. If an error occurs, ERR_PTR(-ERROR)
873  * will be returned.
874  *
875  * If debugfs is not enabled in the kernel, the value -%ENODEV will be
876  * returned.
877  */
debugfs_rename(struct dentry * old_dir,struct dentry * old_dentry,struct dentry * new_dir,const char * new_name)878 struct dentry *debugfs_rename(struct dentry *old_dir, struct dentry *old_dentry,
879 		struct dentry *new_dir, const char *new_name)
880 {
881 	int error;
882 	struct dentry *dentry = NULL, *trap;
883 	struct name_snapshot old_name;
884 
885 	if (IS_ERR(old_dir))
886 		return old_dir;
887 	if (IS_ERR(new_dir))
888 		return new_dir;
889 	if (IS_ERR_OR_NULL(old_dentry))
890 		return old_dentry;
891 
892 	trap = lock_rename(new_dir, old_dir);
893 	/* Source or destination directories don't exist? */
894 	if (d_really_is_negative(old_dir) || d_really_is_negative(new_dir))
895 		goto exit;
896 	/* Source does not exist, cyclic rename, or mountpoint? */
897 	if (d_really_is_negative(old_dentry) || old_dentry == trap ||
898 	    d_mountpoint(old_dentry))
899 		goto exit;
900 	dentry = lookup_one_len(new_name, new_dir, strlen(new_name));
901 	/* Lookup failed, cyclic rename or target exists? */
902 	if (IS_ERR(dentry) || dentry == trap || d_really_is_positive(dentry))
903 		goto exit;
904 
905 	take_dentry_name_snapshot(&old_name, old_dentry);
906 
907 	error = simple_rename(&nop_mnt_idmap, d_inode(old_dir), old_dentry,
908 			      d_inode(new_dir), dentry, 0);
909 	if (error) {
910 		release_dentry_name_snapshot(&old_name);
911 		goto exit;
912 	}
913 	d_move(old_dentry, dentry);
914 	fsnotify_move(d_inode(old_dir), d_inode(new_dir), &old_name.name,
915 		d_is_dir(old_dentry),
916 		NULL, old_dentry);
917 	release_dentry_name_snapshot(&old_name);
918 	unlock_rename(new_dir, old_dir);
919 	dput(dentry);
920 	return old_dentry;
921 exit:
922 	if (dentry && !IS_ERR(dentry))
923 		dput(dentry);
924 	unlock_rename(new_dir, old_dir);
925 	if (IS_ERR(dentry))
926 		return dentry;
927 	return ERR_PTR(-EINVAL);
928 }
929 EXPORT_SYMBOL_GPL(debugfs_rename);
930 
931 /**
932  * debugfs_initialized - Tells whether debugfs has been registered
933  */
debugfs_initialized(void)934 bool debugfs_initialized(void)
935 {
936 	return debugfs_registered;
937 }
938 EXPORT_SYMBOL_GPL(debugfs_initialized);
939 
debugfs_kernel(char * str)940 static int __init debugfs_kernel(char *str)
941 {
942 	if (str) {
943 		if (!strcmp(str, "on"))
944 			debugfs_allow = DEBUGFS_ALLOW_API | DEBUGFS_ALLOW_MOUNT;
945 		else if (!strcmp(str, "no-mount"))
946 			debugfs_allow = DEBUGFS_ALLOW_API;
947 		else if (!strcmp(str, "off"))
948 			debugfs_allow = 0;
949 	}
950 
951 	return 0;
952 }
953 early_param("debugfs", debugfs_kernel);
debugfs_init(void)954 static int __init debugfs_init(void)
955 {
956 	int retval;
957 
958 	if (!(debugfs_allow & DEBUGFS_ALLOW_MOUNT))
959 		return -EPERM;
960 
961 	retval = sysfs_create_mount_point(kernel_kobj, "debug");
962 	if (retval)
963 		return retval;
964 
965 	retval = register_filesystem(&debug_fs_type);
966 	if (retval)
967 		sysfs_remove_mount_point(kernel_kobj, "debug");
968 	else
969 		debugfs_registered = true;
970 
971 	return retval;
972 }
973 core_initcall(debugfs_init);
974