xref: /openbmc/linux/kernel/watch_queue.c (revision c1853fba)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Watch queue and general notification mechanism, built on pipes
3  *
4  * Copyright (C) 2020 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  *
7  * See Documentation/watch_queue.rst
8  */
9 
10 #define pr_fmt(fmt) "watchq: " fmt
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/sched.h>
14 #include <linux/slab.h>
15 #include <linux/printk.h>
16 #include <linux/miscdevice.h>
17 #include <linux/fs.h>
18 #include <linux/mm.h>
19 #include <linux/pagemap.h>
20 #include <linux/poll.h>
21 #include <linux/uaccess.h>
22 #include <linux/vmalloc.h>
23 #include <linux/file.h>
24 #include <linux/security.h>
25 #include <linux/cred.h>
26 #include <linux/sched/signal.h>
27 #include <linux/watch_queue.h>
28 #include <linux/pipe_fs_i.h>
29 
30 MODULE_DESCRIPTION("Watch queue");
31 MODULE_AUTHOR("Red Hat, Inc.");
32 MODULE_LICENSE("GPL");
33 
34 #define WATCH_QUEUE_NOTE_SIZE 128
35 #define WATCH_QUEUE_NOTES_PER_PAGE (PAGE_SIZE / WATCH_QUEUE_NOTE_SIZE)
36 
37 static void watch_queue_pipe_buf_release(struct pipe_inode_info *pipe,
38 					 struct pipe_buffer *buf)
39 {
40 	struct watch_queue *wqueue = (struct watch_queue *)buf->private;
41 	struct page *page;
42 	unsigned int bit;
43 
44 	/* We need to work out which note within the page this refers to, but
45 	 * the note might have been maximum size, so merely ANDing the offset
46 	 * off doesn't work.  OTOH, the note must've been more than zero size.
47 	 */
48 	bit = buf->offset + buf->len;
49 	if ((bit & (WATCH_QUEUE_NOTE_SIZE - 1)) == 0)
50 		bit -= WATCH_QUEUE_NOTE_SIZE;
51 	bit /= WATCH_QUEUE_NOTE_SIZE;
52 
53 	page = buf->page;
54 	bit += page->index;
55 
56 	set_bit(bit, wqueue->notes_bitmap);
57 	generic_pipe_buf_release(pipe, buf);
58 }
59 
60 // No try_steal function => no stealing
61 #define watch_queue_pipe_buf_try_steal NULL
62 
63 /* New data written to a pipe may be appended to a buffer with this type. */
64 static const struct pipe_buf_operations watch_queue_pipe_buf_ops = {
65 	.release	= watch_queue_pipe_buf_release,
66 	.try_steal	= watch_queue_pipe_buf_try_steal,
67 	.get		= generic_pipe_buf_get,
68 };
69 
70 /*
71  * Post a notification to a watch queue.
72  */
73 static bool post_one_notification(struct watch_queue *wqueue,
74 				  struct watch_notification *n)
75 {
76 	void *p;
77 	struct pipe_inode_info *pipe = wqueue->pipe;
78 	struct pipe_buffer *buf;
79 	struct page *page;
80 	unsigned int head, tail, mask, note, offset, len;
81 	bool done = false;
82 
83 	if (!pipe)
84 		return false;
85 
86 	spin_lock_irq(&pipe->rd_wait.lock);
87 
88 	if (wqueue->defunct)
89 		goto out;
90 
91 	mask = pipe->ring_size - 1;
92 	head = pipe->head;
93 	tail = pipe->tail;
94 	if (pipe_full(head, tail, pipe->ring_size))
95 		goto lost;
96 
97 	note = find_first_bit(wqueue->notes_bitmap, wqueue->nr_notes);
98 	if (note >= wqueue->nr_notes)
99 		goto lost;
100 
101 	page = wqueue->notes[note / WATCH_QUEUE_NOTES_PER_PAGE];
102 	offset = note % WATCH_QUEUE_NOTES_PER_PAGE * WATCH_QUEUE_NOTE_SIZE;
103 	get_page(page);
104 	len = n->info & WATCH_INFO_LENGTH;
105 	p = kmap_atomic(page);
106 	memcpy(p + offset, n, len);
107 	kunmap_atomic(p);
108 
109 	buf = &pipe->bufs[head & mask];
110 	buf->page = page;
111 	buf->private = (unsigned long)wqueue;
112 	buf->ops = &watch_queue_pipe_buf_ops;
113 	buf->offset = offset;
114 	buf->len = len;
115 	buf->flags = PIPE_BUF_FLAG_WHOLE;
116 	pipe->head = head + 1;
117 
118 	if (!test_and_clear_bit(note, wqueue->notes_bitmap)) {
119 		spin_unlock_irq(&pipe->rd_wait.lock);
120 		BUG();
121 	}
122 	wake_up_interruptible_sync_poll_locked(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
123 	done = true;
124 
125 out:
126 	spin_unlock_irq(&pipe->rd_wait.lock);
127 	if (done)
128 		kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
129 	return done;
130 
131 lost:
132 	buf = &pipe->bufs[(head - 1) & mask];
133 	buf->flags |= PIPE_BUF_FLAG_LOSS;
134 	goto out;
135 }
136 
137 /*
138  * Apply filter rules to a notification.
139  */
140 static bool filter_watch_notification(const struct watch_filter *wf,
141 				      const struct watch_notification *n)
142 {
143 	const struct watch_type_filter *wt;
144 	unsigned int st_bits = sizeof(wt->subtype_filter[0]) * 8;
145 	unsigned int st_index = n->subtype / st_bits;
146 	unsigned int st_bit = 1U << (n->subtype % st_bits);
147 	int i;
148 
149 	if (!test_bit(n->type, wf->type_filter))
150 		return false;
151 
152 	for (i = 0; i < wf->nr_filters; i++) {
153 		wt = &wf->filters[i];
154 		if (n->type == wt->type &&
155 		    (wt->subtype_filter[st_index] & st_bit) &&
156 		    (n->info & wt->info_mask) == wt->info_filter)
157 			return true;
158 	}
159 
160 	return false; /* If there is a filter, the default is to reject. */
161 }
162 
163 /**
164  * __post_watch_notification - Post an event notification
165  * @wlist: The watch list to post the event to.
166  * @n: The notification record to post.
167  * @cred: The creds of the process that triggered the notification.
168  * @id: The ID to match on the watch.
169  *
170  * Post a notification of an event into a set of watch queues and let the users
171  * know.
172  *
173  * The size of the notification should be set in n->info & WATCH_INFO_LENGTH and
174  * should be in units of sizeof(*n).
175  */
176 void __post_watch_notification(struct watch_list *wlist,
177 			       struct watch_notification *n,
178 			       const struct cred *cred,
179 			       u64 id)
180 {
181 	const struct watch_filter *wf;
182 	struct watch_queue *wqueue;
183 	struct watch *watch;
184 
185 	if (((n->info & WATCH_INFO_LENGTH) >> WATCH_INFO_LENGTH__SHIFT) == 0) {
186 		WARN_ON(1);
187 		return;
188 	}
189 
190 	rcu_read_lock();
191 
192 	hlist_for_each_entry_rcu(watch, &wlist->watchers, list_node) {
193 		if (watch->id != id)
194 			continue;
195 		n->info &= ~WATCH_INFO_ID;
196 		n->info |= watch->info_id;
197 
198 		wqueue = rcu_dereference(watch->queue);
199 		wf = rcu_dereference(wqueue->filter);
200 		if (wf && !filter_watch_notification(wf, n))
201 			continue;
202 
203 		if (security_post_notification(watch->cred, cred, n) < 0)
204 			continue;
205 
206 		post_one_notification(wqueue, n);
207 	}
208 
209 	rcu_read_unlock();
210 }
211 EXPORT_SYMBOL(__post_watch_notification);
212 
213 /*
214  * Allocate sufficient pages to preallocation for the requested number of
215  * notifications.
216  */
217 long watch_queue_set_size(struct pipe_inode_info *pipe, unsigned int nr_notes)
218 {
219 	struct watch_queue *wqueue = pipe->watch_queue;
220 	struct page **pages;
221 	unsigned long *bitmap;
222 	unsigned long user_bufs;
223 	unsigned int bmsize;
224 	int ret, i, nr_pages;
225 
226 	if (!wqueue)
227 		return -ENODEV;
228 	if (wqueue->notes)
229 		return -EBUSY;
230 
231 	if (nr_notes < 1 ||
232 	    nr_notes > 512) /* TODO: choose a better hard limit */
233 		return -EINVAL;
234 
235 	nr_pages = (nr_notes + WATCH_QUEUE_NOTES_PER_PAGE - 1);
236 	nr_pages /= WATCH_QUEUE_NOTES_PER_PAGE;
237 	user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_pages);
238 
239 	if (nr_pages > pipe->max_usage &&
240 	    (too_many_pipe_buffers_hard(user_bufs) ||
241 	     too_many_pipe_buffers_soft(user_bufs)) &&
242 	    pipe_is_unprivileged_user()) {
243 		ret = -EPERM;
244 		goto error;
245 	}
246 
247 	ret = pipe_resize_ring(pipe, nr_notes);
248 	if (ret < 0)
249 		goto error;
250 
251 	pages = kcalloc(sizeof(struct page *), nr_pages, GFP_KERNEL);
252 	if (!pages)
253 		goto error;
254 
255 	for (i = 0; i < nr_pages; i++) {
256 		pages[i] = alloc_page(GFP_KERNEL);
257 		if (!pages[i])
258 			goto error_p;
259 		pages[i]->index = i * WATCH_QUEUE_NOTES_PER_PAGE;
260 	}
261 
262 	bmsize = (nr_notes + BITS_PER_LONG - 1) / BITS_PER_LONG;
263 	bmsize *= sizeof(unsigned long);
264 	bitmap = kmalloc(bmsize, GFP_KERNEL);
265 	if (!bitmap)
266 		goto error_p;
267 
268 	memset(bitmap, 0xff, bmsize);
269 	wqueue->notes = pages;
270 	wqueue->notes_bitmap = bitmap;
271 	wqueue->nr_pages = nr_pages;
272 	wqueue->nr_notes = nr_pages * WATCH_QUEUE_NOTES_PER_PAGE;
273 	return 0;
274 
275 error_p:
276 	for (i = 0; i < nr_pages; i++)
277 		__free_page(pages[i]);
278 	kfree(pages);
279 error:
280 	(void) account_pipe_buffers(pipe->user, nr_pages, pipe->nr_accounted);
281 	return ret;
282 }
283 
284 /*
285  * Set the filter on a watch queue.
286  */
287 long watch_queue_set_filter(struct pipe_inode_info *pipe,
288 			    struct watch_notification_filter __user *_filter)
289 {
290 	struct watch_notification_type_filter *tf;
291 	struct watch_notification_filter filter;
292 	struct watch_type_filter *q;
293 	struct watch_filter *wfilter;
294 	struct watch_queue *wqueue = pipe->watch_queue;
295 	int ret, nr_filter = 0, i;
296 
297 	if (!wqueue)
298 		return -ENODEV;
299 
300 	if (!_filter) {
301 		/* Remove the old filter */
302 		wfilter = NULL;
303 		goto set;
304 	}
305 
306 	/* Grab the user's filter specification */
307 	if (copy_from_user(&filter, _filter, sizeof(filter)) != 0)
308 		return -EFAULT;
309 	if (filter.nr_filters == 0 ||
310 	    filter.nr_filters > 16 ||
311 	    filter.__reserved != 0)
312 		return -EINVAL;
313 
314 	tf = memdup_user(_filter->filters, filter.nr_filters * sizeof(*tf));
315 	if (IS_ERR(tf))
316 		return PTR_ERR(tf);
317 
318 	ret = -EINVAL;
319 	for (i = 0; i < filter.nr_filters; i++) {
320 		if ((tf[i].info_filter & ~tf[i].info_mask) ||
321 		    tf[i].info_mask & WATCH_INFO_LENGTH)
322 			goto err_filter;
323 		/* Ignore any unknown types */
324 		if (tf[i].type >= WATCH_TYPE__NR)
325 			continue;
326 		nr_filter++;
327 	}
328 
329 	/* Now we need to build the internal filter from only the relevant
330 	 * user-specified filters.
331 	 */
332 	ret = -ENOMEM;
333 	wfilter = kzalloc(struct_size(wfilter, filters, nr_filter), GFP_KERNEL);
334 	if (!wfilter)
335 		goto err_filter;
336 	wfilter->nr_filters = nr_filter;
337 
338 	q = wfilter->filters;
339 	for (i = 0; i < filter.nr_filters; i++) {
340 		if (tf[i].type >= WATCH_TYPE__NR)
341 			continue;
342 
343 		q->type			= tf[i].type;
344 		q->info_filter		= tf[i].info_filter;
345 		q->info_mask		= tf[i].info_mask;
346 		q->subtype_filter[0]	= tf[i].subtype_filter[0];
347 		__set_bit(q->type, wfilter->type_filter);
348 		q++;
349 	}
350 
351 	kfree(tf);
352 set:
353 	pipe_lock(pipe);
354 	wfilter = rcu_replace_pointer(wqueue->filter, wfilter,
355 				      lockdep_is_held(&pipe->mutex));
356 	pipe_unlock(pipe);
357 	if (wfilter)
358 		kfree_rcu(wfilter, rcu);
359 	return 0;
360 
361 err_filter:
362 	kfree(tf);
363 	return ret;
364 }
365 
366 static void __put_watch_queue(struct kref *kref)
367 {
368 	struct watch_queue *wqueue =
369 		container_of(kref, struct watch_queue, usage);
370 	struct watch_filter *wfilter;
371 	int i;
372 
373 	for (i = 0; i < wqueue->nr_pages; i++)
374 		__free_page(wqueue->notes[i]);
375 
376 	wfilter = rcu_access_pointer(wqueue->filter);
377 	if (wfilter)
378 		kfree_rcu(wfilter, rcu);
379 	kfree_rcu(wqueue, rcu);
380 }
381 
382 /**
383  * put_watch_queue - Dispose of a ref on a watchqueue.
384  * @wqueue: The watch queue to unref.
385  */
386 void put_watch_queue(struct watch_queue *wqueue)
387 {
388 	kref_put(&wqueue->usage, __put_watch_queue);
389 }
390 EXPORT_SYMBOL(put_watch_queue);
391 
392 static void free_watch(struct rcu_head *rcu)
393 {
394 	struct watch *watch = container_of(rcu, struct watch, rcu);
395 
396 	put_watch_queue(rcu_access_pointer(watch->queue));
397 	atomic_dec(&watch->cred->user->nr_watches);
398 	put_cred(watch->cred);
399 }
400 
401 static void __put_watch(struct kref *kref)
402 {
403 	struct watch *watch = container_of(kref, struct watch, usage);
404 
405 	call_rcu(&watch->rcu, free_watch);
406 }
407 
408 /*
409  * Discard a watch.
410  */
411 static void put_watch(struct watch *watch)
412 {
413 	kref_put(&watch->usage, __put_watch);
414 }
415 
416 /**
417  * init_watch - Initialise a watch
418  * @watch: The watch to initialise.
419  * @wqueue: The queue to assign.
420  *
421  * Initialise a watch and set the watch queue.
422  */
423 void init_watch(struct watch *watch, struct watch_queue *wqueue)
424 {
425 	kref_init(&watch->usage);
426 	INIT_HLIST_NODE(&watch->list_node);
427 	INIT_HLIST_NODE(&watch->queue_node);
428 	rcu_assign_pointer(watch->queue, wqueue);
429 }
430 
431 /**
432  * add_watch_to_object - Add a watch on an object to a watch list
433  * @watch: The watch to add
434  * @wlist: The watch list to add to
435  *
436  * @watch->queue must have been set to point to the queue to post notifications
437  * to and the watch list of the object to be watched.  @watch->cred must also
438  * have been set to the appropriate credentials and a ref taken on them.
439  *
440  * The caller must pin the queue and the list both and must hold the list
441  * locked against racing watch additions/removals.
442  */
443 int add_watch_to_object(struct watch *watch, struct watch_list *wlist)
444 {
445 	struct watch_queue *wqueue = rcu_access_pointer(watch->queue);
446 	struct watch *w;
447 
448 	hlist_for_each_entry(w, &wlist->watchers, list_node) {
449 		struct watch_queue *wq = rcu_access_pointer(w->queue);
450 		if (wqueue == wq && watch->id == w->id)
451 			return -EBUSY;
452 	}
453 
454 	watch->cred = get_current_cred();
455 	rcu_assign_pointer(watch->watch_list, wlist);
456 
457 	if (atomic_inc_return(&watch->cred->user->nr_watches) >
458 	    task_rlimit(current, RLIMIT_NOFILE)) {
459 		atomic_dec(&watch->cred->user->nr_watches);
460 		put_cred(watch->cred);
461 		return -EAGAIN;
462 	}
463 
464 	spin_lock_bh(&wqueue->lock);
465 	kref_get(&wqueue->usage);
466 	kref_get(&watch->usage);
467 	hlist_add_head(&watch->queue_node, &wqueue->watches);
468 	spin_unlock_bh(&wqueue->lock);
469 
470 	hlist_add_head(&watch->list_node, &wlist->watchers);
471 	return 0;
472 }
473 EXPORT_SYMBOL(add_watch_to_object);
474 
475 /**
476  * remove_watch_from_object - Remove a watch or all watches from an object.
477  * @wlist: The watch list to remove from
478  * @wq: The watch queue of interest (ignored if @all is true)
479  * @id: The ID of the watch to remove (ignored if @all is true)
480  * @all: True to remove all objects
481  *
482  * Remove a specific watch or all watches from an object.  A notification is
483  * sent to the watcher to tell them that this happened.
484  */
485 int remove_watch_from_object(struct watch_list *wlist, struct watch_queue *wq,
486 			     u64 id, bool all)
487 {
488 	struct watch_notification_removal n;
489 	struct watch_queue *wqueue;
490 	struct watch *watch;
491 	int ret = -EBADSLT;
492 
493 	rcu_read_lock();
494 
495 again:
496 	spin_lock(&wlist->lock);
497 	hlist_for_each_entry(watch, &wlist->watchers, list_node) {
498 		if (all ||
499 		    (watch->id == id && rcu_access_pointer(watch->queue) == wq))
500 			goto found;
501 	}
502 	spin_unlock(&wlist->lock);
503 	goto out;
504 
505 found:
506 	ret = 0;
507 	hlist_del_init_rcu(&watch->list_node);
508 	rcu_assign_pointer(watch->watch_list, NULL);
509 	spin_unlock(&wlist->lock);
510 
511 	/* We now own the reference on watch that used to belong to wlist. */
512 
513 	n.watch.type = WATCH_TYPE_META;
514 	n.watch.subtype = WATCH_META_REMOVAL_NOTIFICATION;
515 	n.watch.info = watch->info_id | watch_sizeof(n.watch);
516 	n.id = id;
517 	if (id != 0)
518 		n.watch.info = watch->info_id | watch_sizeof(n);
519 
520 	wqueue = rcu_dereference(watch->queue);
521 
522 	/* We don't need the watch list lock for the next bit as RCU is
523 	 * protecting *wqueue from deallocation.
524 	 */
525 	if (wqueue) {
526 		post_one_notification(wqueue, &n.watch);
527 
528 		spin_lock_bh(&wqueue->lock);
529 
530 		if (!hlist_unhashed(&watch->queue_node)) {
531 			hlist_del_init_rcu(&watch->queue_node);
532 			put_watch(watch);
533 		}
534 
535 		spin_unlock_bh(&wqueue->lock);
536 	}
537 
538 	if (wlist->release_watch) {
539 		void (*release_watch)(struct watch *);
540 
541 		release_watch = wlist->release_watch;
542 		rcu_read_unlock();
543 		(*release_watch)(watch);
544 		rcu_read_lock();
545 	}
546 	put_watch(watch);
547 
548 	if (all && !hlist_empty(&wlist->watchers))
549 		goto again;
550 out:
551 	rcu_read_unlock();
552 	return ret;
553 }
554 EXPORT_SYMBOL(remove_watch_from_object);
555 
556 /*
557  * Remove all the watches that are contributory to a queue.  This has the
558  * potential to race with removal of the watches by the destruction of the
559  * objects being watched or with the distribution of notifications.
560  */
561 void watch_queue_clear(struct watch_queue *wqueue)
562 {
563 	struct watch_list *wlist;
564 	struct watch *watch;
565 	bool release;
566 
567 	rcu_read_lock();
568 	spin_lock_bh(&wqueue->lock);
569 
570 	/* Prevent new additions and prevent notifications from happening */
571 	wqueue->defunct = true;
572 
573 	while (!hlist_empty(&wqueue->watches)) {
574 		watch = hlist_entry(wqueue->watches.first, struct watch, queue_node);
575 		hlist_del_init_rcu(&watch->queue_node);
576 		/* We now own a ref on the watch. */
577 		spin_unlock_bh(&wqueue->lock);
578 
579 		/* We can't do the next bit under the queue lock as we need to
580 		 * get the list lock - which would cause a deadlock if someone
581 		 * was removing from the opposite direction at the same time or
582 		 * posting a notification.
583 		 */
584 		wlist = rcu_dereference(watch->watch_list);
585 		if (wlist) {
586 			void (*release_watch)(struct watch *);
587 
588 			spin_lock(&wlist->lock);
589 
590 			release = !hlist_unhashed(&watch->list_node);
591 			if (release) {
592 				hlist_del_init_rcu(&watch->list_node);
593 				rcu_assign_pointer(watch->watch_list, NULL);
594 
595 				/* We now own a second ref on the watch. */
596 			}
597 
598 			release_watch = wlist->release_watch;
599 			spin_unlock(&wlist->lock);
600 
601 			if (release) {
602 				if (release_watch) {
603 					rcu_read_unlock();
604 					/* This might need to call dput(), so
605 					 * we have to drop all the locks.
606 					 */
607 					(*release_watch)(watch);
608 					rcu_read_lock();
609 				}
610 				put_watch(watch);
611 			}
612 		}
613 
614 		put_watch(watch);
615 		spin_lock_bh(&wqueue->lock);
616 	}
617 
618 	spin_unlock_bh(&wqueue->lock);
619 	rcu_read_unlock();
620 }
621 
622 /**
623  * get_watch_queue - Get a watch queue from its file descriptor.
624  * @fd: The fd to query.
625  */
626 struct watch_queue *get_watch_queue(int fd)
627 {
628 	struct pipe_inode_info *pipe;
629 	struct watch_queue *wqueue = ERR_PTR(-EINVAL);
630 	struct fd f;
631 
632 	f = fdget(fd);
633 	if (f.file) {
634 		pipe = get_pipe_info(f.file, false);
635 		if (pipe && pipe->watch_queue) {
636 			wqueue = pipe->watch_queue;
637 			kref_get(&wqueue->usage);
638 		}
639 		fdput(f);
640 	}
641 
642 	return wqueue;
643 }
644 EXPORT_SYMBOL(get_watch_queue);
645 
646 /*
647  * Initialise a watch queue
648  */
649 int watch_queue_init(struct pipe_inode_info *pipe)
650 {
651 	struct watch_queue *wqueue;
652 
653 	wqueue = kzalloc(sizeof(*wqueue), GFP_KERNEL);
654 	if (!wqueue)
655 		return -ENOMEM;
656 
657 	wqueue->pipe = pipe;
658 	kref_init(&wqueue->usage);
659 	spin_lock_init(&wqueue->lock);
660 	INIT_HLIST_HEAD(&wqueue->watches);
661 
662 	pipe->watch_queue = wqueue;
663 	return 0;
664 }
665