1/* Daemon interface
2 *
3 * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com)
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public Licence
8 * as published by the Free Software Foundation; either version
9 * 2 of the Licence, or (at your option) any later version.
10 */
11
12#include <linux/module.h>
13#include <linux/init.h>
14#include <linux/sched.h>
15#include <linux/completion.h>
16#include <linux/slab.h>
17#include <linux/fs.h>
18#include <linux/file.h>
19#include <linux/namei.h>
20#include <linux/poll.h>
21#include <linux/mount.h>
22#include <linux/statfs.h>
23#include <linux/ctype.h>
24#include <linux/string.h>
25#include <linux/fs_struct.h>
26#include "internal.h"
27
28static int cachefiles_daemon_open(struct inode *, struct file *);
29static int cachefiles_daemon_release(struct inode *, struct file *);
30static ssize_t cachefiles_daemon_read(struct file *, char __user *, size_t,
31				      loff_t *);
32static ssize_t cachefiles_daemon_write(struct file *, const char __user *,
33				       size_t, loff_t *);
34static unsigned int cachefiles_daemon_poll(struct file *,
35					   struct poll_table_struct *);
36static int cachefiles_daemon_frun(struct cachefiles_cache *, char *);
37static int cachefiles_daemon_fcull(struct cachefiles_cache *, char *);
38static int cachefiles_daemon_fstop(struct cachefiles_cache *, char *);
39static int cachefiles_daemon_brun(struct cachefiles_cache *, char *);
40static int cachefiles_daemon_bcull(struct cachefiles_cache *, char *);
41static int cachefiles_daemon_bstop(struct cachefiles_cache *, char *);
42static int cachefiles_daemon_cull(struct cachefiles_cache *, char *);
43static int cachefiles_daemon_debug(struct cachefiles_cache *, char *);
44static int cachefiles_daemon_dir(struct cachefiles_cache *, char *);
45static int cachefiles_daemon_inuse(struct cachefiles_cache *, char *);
46static int cachefiles_daemon_secctx(struct cachefiles_cache *, char *);
47static int cachefiles_daemon_tag(struct cachefiles_cache *, char *);
48
49static unsigned long cachefiles_open;
50
51const struct file_operations cachefiles_daemon_fops = {
52	.owner		= THIS_MODULE,
53	.open		= cachefiles_daemon_open,
54	.release	= cachefiles_daemon_release,
55	.read		= cachefiles_daemon_read,
56	.write		= cachefiles_daemon_write,
57	.poll		= cachefiles_daemon_poll,
58	.llseek		= noop_llseek,
59};
60
61struct cachefiles_daemon_cmd {
62	char name[8];
63	int (*handler)(struct cachefiles_cache *cache, char *args);
64};
65
66static const struct cachefiles_daemon_cmd cachefiles_daemon_cmds[] = {
67	{ "bind",	cachefiles_daemon_bind		},
68	{ "brun",	cachefiles_daemon_brun		},
69	{ "bcull",	cachefiles_daemon_bcull		},
70	{ "bstop",	cachefiles_daemon_bstop		},
71	{ "cull",	cachefiles_daemon_cull		},
72	{ "debug",	cachefiles_daemon_debug		},
73	{ "dir",	cachefiles_daemon_dir		},
74	{ "frun",	cachefiles_daemon_frun		},
75	{ "fcull",	cachefiles_daemon_fcull		},
76	{ "fstop",	cachefiles_daemon_fstop		},
77	{ "inuse",	cachefiles_daemon_inuse		},
78	{ "secctx",	cachefiles_daemon_secctx	},
79	{ "tag",	cachefiles_daemon_tag		},
80	{ "",		NULL				}
81};
82
83
84/*
85 * do various checks
86 */
87static int cachefiles_daemon_open(struct inode *inode, struct file *file)
88{
89	struct cachefiles_cache *cache;
90
91	_enter("");
92
93	/* only the superuser may do this */
94	if (!capable(CAP_SYS_ADMIN))
95		return -EPERM;
96
97	/* the cachefiles device may only be open once at a time */
98	if (xchg(&cachefiles_open, 1) == 1)
99		return -EBUSY;
100
101	/* allocate a cache record */
102	cache = kzalloc(sizeof(struct cachefiles_cache), GFP_KERNEL);
103	if (!cache) {
104		cachefiles_open = 0;
105		return -ENOMEM;
106	}
107
108	mutex_init(&cache->daemon_mutex);
109	cache->active_nodes = RB_ROOT;
110	rwlock_init(&cache->active_lock);
111	init_waitqueue_head(&cache->daemon_pollwq);
112
113	/* set default caching limits
114	 * - limit at 1% free space and/or free files
115	 * - cull below 5% free space and/or free files
116	 * - cease culling above 7% free space and/or free files
117	 */
118	cache->frun_percent = 7;
119	cache->fcull_percent = 5;
120	cache->fstop_percent = 1;
121	cache->brun_percent = 7;
122	cache->bcull_percent = 5;
123	cache->bstop_percent = 1;
124
125	file->private_data = cache;
126	cache->cachefilesd = file;
127	return 0;
128}
129
130/*
131 * release a cache
132 */
133static int cachefiles_daemon_release(struct inode *inode, struct file *file)
134{
135	struct cachefiles_cache *cache = file->private_data;
136
137	_enter("");
138
139	ASSERT(cache);
140
141	set_bit(CACHEFILES_DEAD, &cache->flags);
142
143	cachefiles_daemon_unbind(cache);
144
145	ASSERT(!cache->active_nodes.rb_node);
146
147	/* clean up the control file interface */
148	cache->cachefilesd = NULL;
149	file->private_data = NULL;
150	cachefiles_open = 0;
151
152	kfree(cache);
153
154	_leave("");
155	return 0;
156}
157
158/*
159 * read the cache state
160 */
161static ssize_t cachefiles_daemon_read(struct file *file, char __user *_buffer,
162				      size_t buflen, loff_t *pos)
163{
164	struct cachefiles_cache *cache = file->private_data;
165	char buffer[256];
166	int n;
167
168	//_enter(",,%zu,", buflen);
169
170	if (!test_bit(CACHEFILES_READY, &cache->flags))
171		return 0;
172
173	/* check how much space the cache has */
174	cachefiles_has_space(cache, 0, 0);
175
176	/* summarise */
177	clear_bit(CACHEFILES_STATE_CHANGED, &cache->flags);
178
179	n = snprintf(buffer, sizeof(buffer),
180		     "cull=%c"
181		     " frun=%llx"
182		     " fcull=%llx"
183		     " fstop=%llx"
184		     " brun=%llx"
185		     " bcull=%llx"
186		     " bstop=%llx",
187		     test_bit(CACHEFILES_CULLING, &cache->flags) ? '1' : '0',
188		     (unsigned long long) cache->frun,
189		     (unsigned long long) cache->fcull,
190		     (unsigned long long) cache->fstop,
191		     (unsigned long long) cache->brun,
192		     (unsigned long long) cache->bcull,
193		     (unsigned long long) cache->bstop
194		     );
195
196	if (n > buflen)
197		return -EMSGSIZE;
198
199	if (copy_to_user(_buffer, buffer, n) != 0)
200		return -EFAULT;
201
202	return n;
203}
204
205/*
206 * command the cache
207 */
208static ssize_t cachefiles_daemon_write(struct file *file,
209				       const char __user *_data,
210				       size_t datalen,
211				       loff_t *pos)
212{
213	const struct cachefiles_daemon_cmd *cmd;
214	struct cachefiles_cache *cache = file->private_data;
215	ssize_t ret;
216	char *data, *args, *cp;
217
218	//_enter(",,%zu,", datalen);
219
220	ASSERT(cache);
221
222	if (test_bit(CACHEFILES_DEAD, &cache->flags))
223		return -EIO;
224
225	if (datalen < 0 || datalen > PAGE_SIZE - 1)
226		return -EOPNOTSUPP;
227
228	/* drag the command string into the kernel so we can parse it */
229	data = kmalloc(datalen + 1, GFP_KERNEL);
230	if (!data)
231		return -ENOMEM;
232
233	ret = -EFAULT;
234	if (copy_from_user(data, _data, datalen) != 0)
235		goto error;
236
237	data[datalen] = '\0';
238
239	ret = -EINVAL;
240	if (memchr(data, '\0', datalen))
241		goto error;
242
243	/* strip any newline */
244	cp = memchr(data, '\n', datalen);
245	if (cp) {
246		if (cp == data)
247			goto error;
248
249		*cp = '\0';
250	}
251
252	/* parse the command */
253	ret = -EOPNOTSUPP;
254
255	for (args = data; *args; args++)
256		if (isspace(*args))
257			break;
258	if (*args) {
259		if (args == data)
260			goto error;
261		*args = '\0';
262		args = skip_spaces(++args);
263	}
264
265	/* run the appropriate command handler */
266	for (cmd = cachefiles_daemon_cmds; cmd->name[0]; cmd++)
267		if (strcmp(cmd->name, data) == 0)
268			goto found_command;
269
270error:
271	kfree(data);
272	//_leave(" = %zd", ret);
273	return ret;
274
275found_command:
276	mutex_lock(&cache->daemon_mutex);
277
278	ret = -EIO;
279	if (!test_bit(CACHEFILES_DEAD, &cache->flags))
280		ret = cmd->handler(cache, args);
281
282	mutex_unlock(&cache->daemon_mutex);
283
284	if (ret == 0)
285		ret = datalen;
286	goto error;
287}
288
289/*
290 * poll for culling state
291 * - use POLLOUT to indicate culling state
292 */
293static unsigned int cachefiles_daemon_poll(struct file *file,
294					   struct poll_table_struct *poll)
295{
296	struct cachefiles_cache *cache = file->private_data;
297	unsigned int mask;
298
299	poll_wait(file, &cache->daemon_pollwq, poll);
300	mask = 0;
301
302	if (test_bit(CACHEFILES_STATE_CHANGED, &cache->flags))
303		mask |= POLLIN;
304
305	if (test_bit(CACHEFILES_CULLING, &cache->flags))
306		mask |= POLLOUT;
307
308	return mask;
309}
310
311/*
312 * give a range error for cache space constraints
313 * - can be tail-called
314 */
315static int cachefiles_daemon_range_error(struct cachefiles_cache *cache,
316					 char *args)
317{
318	pr_err("Free space limits must be in range 0%%<=stop<cull<run<100%%\n");
319
320	return -EINVAL;
321}
322
323/*
324 * set the percentage of files at which to stop culling
325 * - command: "frun <N>%"
326 */
327static int cachefiles_daemon_frun(struct cachefiles_cache *cache, char *args)
328{
329	unsigned long frun;
330
331	_enter(",%s", args);
332
333	if (!*args)
334		return -EINVAL;
335
336	frun = simple_strtoul(args, &args, 10);
337	if (args[0] != '%' || args[1] != '\0')
338		return -EINVAL;
339
340	if (frun <= cache->fcull_percent || frun >= 100)
341		return cachefiles_daemon_range_error(cache, args);
342
343	cache->frun_percent = frun;
344	return 0;
345}
346
347/*
348 * set the percentage of files at which to start culling
349 * - command: "fcull <N>%"
350 */
351static int cachefiles_daemon_fcull(struct cachefiles_cache *cache, char *args)
352{
353	unsigned long fcull;
354
355	_enter(",%s", args);
356
357	if (!*args)
358		return -EINVAL;
359
360	fcull = simple_strtoul(args, &args, 10);
361	if (args[0] != '%' || args[1] != '\0')
362		return -EINVAL;
363
364	if (fcull <= cache->fstop_percent || fcull >= cache->frun_percent)
365		return cachefiles_daemon_range_error(cache, args);
366
367	cache->fcull_percent = fcull;
368	return 0;
369}
370
371/*
372 * set the percentage of files at which to stop allocating
373 * - command: "fstop <N>%"
374 */
375static int cachefiles_daemon_fstop(struct cachefiles_cache *cache, char *args)
376{
377	unsigned long fstop;
378
379	_enter(",%s", args);
380
381	if (!*args)
382		return -EINVAL;
383
384	fstop = simple_strtoul(args, &args, 10);
385	if (args[0] != '%' || args[1] != '\0')
386		return -EINVAL;
387
388	if (fstop < 0 || fstop >= cache->fcull_percent)
389		return cachefiles_daemon_range_error(cache, args);
390
391	cache->fstop_percent = fstop;
392	return 0;
393}
394
395/*
396 * set the percentage of blocks at which to stop culling
397 * - command: "brun <N>%"
398 */
399static int cachefiles_daemon_brun(struct cachefiles_cache *cache, char *args)
400{
401	unsigned long brun;
402
403	_enter(",%s", args);
404
405	if (!*args)
406		return -EINVAL;
407
408	brun = simple_strtoul(args, &args, 10);
409	if (args[0] != '%' || args[1] != '\0')
410		return -EINVAL;
411
412	if (brun <= cache->bcull_percent || brun >= 100)
413		return cachefiles_daemon_range_error(cache, args);
414
415	cache->brun_percent = brun;
416	return 0;
417}
418
419/*
420 * set the percentage of blocks at which to start culling
421 * - command: "bcull <N>%"
422 */
423static int cachefiles_daemon_bcull(struct cachefiles_cache *cache, char *args)
424{
425	unsigned long bcull;
426
427	_enter(",%s", args);
428
429	if (!*args)
430		return -EINVAL;
431
432	bcull = simple_strtoul(args, &args, 10);
433	if (args[0] != '%' || args[1] != '\0')
434		return -EINVAL;
435
436	if (bcull <= cache->bstop_percent || bcull >= cache->brun_percent)
437		return cachefiles_daemon_range_error(cache, args);
438
439	cache->bcull_percent = bcull;
440	return 0;
441}
442
443/*
444 * set the percentage of blocks at which to stop allocating
445 * - command: "bstop <N>%"
446 */
447static int cachefiles_daemon_bstop(struct cachefiles_cache *cache, char *args)
448{
449	unsigned long bstop;
450
451	_enter(",%s", args);
452
453	if (!*args)
454		return -EINVAL;
455
456	bstop = simple_strtoul(args, &args, 10);
457	if (args[0] != '%' || args[1] != '\0')
458		return -EINVAL;
459
460	if (bstop < 0 || bstop >= cache->bcull_percent)
461		return cachefiles_daemon_range_error(cache, args);
462
463	cache->bstop_percent = bstop;
464	return 0;
465}
466
467/*
468 * set the cache directory
469 * - command: "dir <name>"
470 */
471static int cachefiles_daemon_dir(struct cachefiles_cache *cache, char *args)
472{
473	char *dir;
474
475	_enter(",%s", args);
476
477	if (!*args) {
478		pr_err("Empty directory specified\n");
479		return -EINVAL;
480	}
481
482	if (cache->rootdirname) {
483		pr_err("Second cache directory specified\n");
484		return -EEXIST;
485	}
486
487	dir = kstrdup(args, GFP_KERNEL);
488	if (!dir)
489		return -ENOMEM;
490
491	cache->rootdirname = dir;
492	return 0;
493}
494
495/*
496 * set the cache security context
497 * - command: "secctx <ctx>"
498 */
499static int cachefiles_daemon_secctx(struct cachefiles_cache *cache, char *args)
500{
501	char *secctx;
502
503	_enter(",%s", args);
504
505	if (!*args) {
506		pr_err("Empty security context specified\n");
507		return -EINVAL;
508	}
509
510	if (cache->secctx) {
511		pr_err("Second security context specified\n");
512		return -EINVAL;
513	}
514
515	secctx = kstrdup(args, GFP_KERNEL);
516	if (!secctx)
517		return -ENOMEM;
518
519	cache->secctx = secctx;
520	return 0;
521}
522
523/*
524 * set the cache tag
525 * - command: "tag <name>"
526 */
527static int cachefiles_daemon_tag(struct cachefiles_cache *cache, char *args)
528{
529	char *tag;
530
531	_enter(",%s", args);
532
533	if (!*args) {
534		pr_err("Empty tag specified\n");
535		return -EINVAL;
536	}
537
538	if (cache->tag)
539		return -EEXIST;
540
541	tag = kstrdup(args, GFP_KERNEL);
542	if (!tag)
543		return -ENOMEM;
544
545	cache->tag = tag;
546	return 0;
547}
548
549/*
550 * request a node in the cache be culled from the current working directory
551 * - command: "cull <name>"
552 */
553static int cachefiles_daemon_cull(struct cachefiles_cache *cache, char *args)
554{
555	struct path path;
556	const struct cred *saved_cred;
557	int ret;
558
559	_enter(",%s", args);
560
561	if (strchr(args, '/'))
562		goto inval;
563
564	if (!test_bit(CACHEFILES_READY, &cache->flags)) {
565		pr_err("cull applied to unready cache\n");
566		return -EIO;
567	}
568
569	if (test_bit(CACHEFILES_DEAD, &cache->flags)) {
570		pr_err("cull applied to dead cache\n");
571		return -EIO;
572	}
573
574	/* extract the directory dentry from the cwd */
575	get_fs_pwd(current->fs, &path);
576
577	if (!d_can_lookup(path.dentry))
578		goto notdir;
579
580	cachefiles_begin_secure(cache, &saved_cred);
581	ret = cachefiles_cull(cache, path.dentry, args);
582	cachefiles_end_secure(cache, saved_cred);
583
584	path_put(&path);
585	_leave(" = %d", ret);
586	return ret;
587
588notdir:
589	path_put(&path);
590	pr_err("cull command requires dirfd to be a directory\n");
591	return -ENOTDIR;
592
593inval:
594	pr_err("cull command requires dirfd and filename\n");
595	return -EINVAL;
596}
597
598/*
599 * set debugging mode
600 * - command: "debug <mask>"
601 */
602static int cachefiles_daemon_debug(struct cachefiles_cache *cache, char *args)
603{
604	unsigned long mask;
605
606	_enter(",%s", args);
607
608	mask = simple_strtoul(args, &args, 0);
609	if (args[0] != '\0')
610		goto inval;
611
612	cachefiles_debug = mask;
613	_leave(" = 0");
614	return 0;
615
616inval:
617	pr_err("debug command requires mask\n");
618	return -EINVAL;
619}
620
621/*
622 * find out whether an object in the current working directory is in use or not
623 * - command: "inuse <name>"
624 */
625static int cachefiles_daemon_inuse(struct cachefiles_cache *cache, char *args)
626{
627	struct path path;
628	const struct cred *saved_cred;
629	int ret;
630
631	//_enter(",%s", args);
632
633	if (strchr(args, '/'))
634		goto inval;
635
636	if (!test_bit(CACHEFILES_READY, &cache->flags)) {
637		pr_err("inuse applied to unready cache\n");
638		return -EIO;
639	}
640
641	if (test_bit(CACHEFILES_DEAD, &cache->flags)) {
642		pr_err("inuse applied to dead cache\n");
643		return -EIO;
644	}
645
646	/* extract the directory dentry from the cwd */
647	get_fs_pwd(current->fs, &path);
648
649	if (!d_can_lookup(path.dentry))
650		goto notdir;
651
652	cachefiles_begin_secure(cache, &saved_cred);
653	ret = cachefiles_check_in_use(cache, path.dentry, args);
654	cachefiles_end_secure(cache, saved_cred);
655
656	path_put(&path);
657	//_leave(" = %d", ret);
658	return ret;
659
660notdir:
661	path_put(&path);
662	pr_err("inuse command requires dirfd to be a directory\n");
663	return -ENOTDIR;
664
665inval:
666	pr_err("inuse command requires dirfd and filename\n");
667	return -EINVAL;
668}
669
670/*
671 * see if we have space for a number of pages and/or a number of files in the
672 * cache
673 */
674int cachefiles_has_space(struct cachefiles_cache *cache,
675			 unsigned fnr, unsigned bnr)
676{
677	struct kstatfs stats;
678	struct path path = {
679		.mnt	= cache->mnt,
680		.dentry	= cache->mnt->mnt_root,
681	};
682	int ret;
683
684	//_enter("{%llu,%llu,%llu,%llu,%llu,%llu},%u,%u",
685	//       (unsigned long long) cache->frun,
686	//       (unsigned long long) cache->fcull,
687	//       (unsigned long long) cache->fstop,
688	//       (unsigned long long) cache->brun,
689	//       (unsigned long long) cache->bcull,
690	//       (unsigned long long) cache->bstop,
691	//       fnr, bnr);
692
693	/* find out how many pages of blockdev are available */
694	memset(&stats, 0, sizeof(stats));
695
696	ret = vfs_statfs(&path, &stats);
697	if (ret < 0) {
698		if (ret == -EIO)
699			cachefiles_io_error(cache, "statfs failed");
700		_leave(" = %d", ret);
701		return ret;
702	}
703
704	stats.f_bavail >>= cache->bshift;
705
706	//_debug("avail %llu,%llu",
707	//       (unsigned long long) stats.f_ffree,
708	//       (unsigned long long) stats.f_bavail);
709
710	/* see if there is sufficient space */
711	if (stats.f_ffree > fnr)
712		stats.f_ffree -= fnr;
713	else
714		stats.f_ffree = 0;
715
716	if (stats.f_bavail > bnr)
717		stats.f_bavail -= bnr;
718	else
719		stats.f_bavail = 0;
720
721	ret = -ENOBUFS;
722	if (stats.f_ffree < cache->fstop ||
723	    stats.f_bavail < cache->bstop)
724		goto begin_cull;
725
726	ret = 0;
727	if (stats.f_ffree < cache->fcull ||
728	    stats.f_bavail < cache->bcull)
729		goto begin_cull;
730
731	if (test_bit(CACHEFILES_CULLING, &cache->flags) &&
732	    stats.f_ffree >= cache->frun &&
733	    stats.f_bavail >= cache->brun &&
734	    test_and_clear_bit(CACHEFILES_CULLING, &cache->flags)
735	    ) {
736		_debug("cease culling");
737		cachefiles_state_changed(cache);
738	}
739
740	//_leave(" = 0");
741	return 0;
742
743begin_cull:
744	if (!test_and_set_bit(CACHEFILES_CULLING, &cache->flags)) {
745		_debug("### CULL CACHE ###");
746		cachefiles_state_changed(cache);
747	}
748
749	_leave(" = %d", ret);
750	return ret;
751}
752