xref: /openbmc/linux/io_uring/poll.c (revision 875e5771536f8f631f38f0c6090a108cd611fcf3)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/fs.h>
5 #include <linux/file.h>
6 #include <linux/mm.h>
7 #include <linux/slab.h>
8 #include <linux/poll.h>
9 #include <linux/hashtable.h>
10 #include <linux/io_uring.h>
11 
12 #include <trace/events/io_uring.h>
13 
14 #include <uapi/linux/io_uring.h>
15 
16 #include "io_uring.h"
17 #include "refs.h"
18 #include "opdef.h"
19 #include "kbuf.h"
20 #include "poll.h"
21 #include "cancel.h"
22 
23 struct io_poll_update {
24 	struct file			*file;
25 	u64				old_user_data;
26 	u64				new_user_data;
27 	__poll_t			events;
28 	bool				update_events;
29 	bool				update_user_data;
30 };
31 
32 struct io_poll_table {
33 	struct poll_table_struct pt;
34 	struct io_kiocb *req;
35 	int nr_entries;
36 	int error;
37 	bool owning;
38 	/* output value, set only if arm poll returns >0 */
39 	__poll_t result_mask;
40 };
41 
42 #define IO_POLL_CANCEL_FLAG	BIT(31)
43 #define IO_POLL_RETRY_FLAG	BIT(30)
44 #define IO_POLL_REF_MASK	GENMASK(29, 0)
45 
46 /*
47  * We usually have 1-2 refs taken, 128 is more than enough and we want to
48  * maximise the margin between this amount and the moment when it overflows.
49  */
50 #define IO_POLL_REF_BIAS	128
51 
52 #define IO_WQE_F_DOUBLE		1
53 
54 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
55 			void *key);
56 
wqe_to_req(struct wait_queue_entry * wqe)57 static inline struct io_kiocb *wqe_to_req(struct wait_queue_entry *wqe)
58 {
59 	unsigned long priv = (unsigned long)wqe->private;
60 
61 	return (struct io_kiocb *)(priv & ~IO_WQE_F_DOUBLE);
62 }
63 
wqe_is_double(struct wait_queue_entry * wqe)64 static inline bool wqe_is_double(struct wait_queue_entry *wqe)
65 {
66 	unsigned long priv = (unsigned long)wqe->private;
67 
68 	return priv & IO_WQE_F_DOUBLE;
69 }
70 
io_poll_get_ownership_slowpath(struct io_kiocb * req)71 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
72 {
73 	int v;
74 
75 	/*
76 	 * poll_refs are already elevated and we don't have much hope for
77 	 * grabbing the ownership. Instead of incrementing set a retry flag
78 	 * to notify the loop that there might have been some change.
79 	 */
80 	v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
81 	if (v & IO_POLL_REF_MASK)
82 		return false;
83 	return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
84 }
85 
86 /*
87  * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
88  * bump it and acquire ownership. It's disallowed to modify requests while not
89  * owning it, that prevents from races for enqueueing task_work's and b/w
90  * arming poll and wakeups.
91  */
io_poll_get_ownership(struct io_kiocb * req)92 static inline bool io_poll_get_ownership(struct io_kiocb *req)
93 {
94 	if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
95 		return io_poll_get_ownership_slowpath(req);
96 	return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
97 }
98 
io_poll_mark_cancelled(struct io_kiocb * req)99 static void io_poll_mark_cancelled(struct io_kiocb *req)
100 {
101 	atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
102 }
103 
io_poll_get_double(struct io_kiocb * req)104 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
105 {
106 	/* pure poll stashes this in ->async_data, poll driven retry elsewhere */
107 	if (req->opcode == IORING_OP_POLL_ADD)
108 		return req->async_data;
109 	return req->apoll->double_poll;
110 }
111 
io_poll_get_single(struct io_kiocb * req)112 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
113 {
114 	if (req->opcode == IORING_OP_POLL_ADD)
115 		return io_kiocb_to_cmd(req, struct io_poll);
116 	return &req->apoll->poll;
117 }
118 
io_poll_req_insert(struct io_kiocb * req)119 static void io_poll_req_insert(struct io_kiocb *req)
120 {
121 	struct io_hash_table *table = &req->ctx->cancel_table;
122 	u32 index = hash_long(req->cqe.user_data, table->hash_bits);
123 	struct io_hash_bucket *hb = &table->hbs[index];
124 
125 	spin_lock(&hb->lock);
126 	hlist_add_head(&req->hash_node, &hb->list);
127 	spin_unlock(&hb->lock);
128 }
129 
io_poll_req_delete(struct io_kiocb * req,struct io_ring_ctx * ctx)130 static void io_poll_req_delete(struct io_kiocb *req, struct io_ring_ctx *ctx)
131 {
132 	struct io_hash_table *table = &req->ctx->cancel_table;
133 	u32 index = hash_long(req->cqe.user_data, table->hash_bits);
134 	spinlock_t *lock = &table->hbs[index].lock;
135 
136 	spin_lock(lock);
137 	hash_del(&req->hash_node);
138 	spin_unlock(lock);
139 }
140 
io_poll_req_insert_locked(struct io_kiocb * req)141 static void io_poll_req_insert_locked(struct io_kiocb *req)
142 {
143 	struct io_hash_table *table = &req->ctx->cancel_table_locked;
144 	u32 index = hash_long(req->cqe.user_data, table->hash_bits);
145 
146 	lockdep_assert_held(&req->ctx->uring_lock);
147 
148 	hlist_add_head(&req->hash_node, &table->hbs[index].list);
149 }
150 
io_poll_tw_hash_eject(struct io_kiocb * req,struct io_tw_state * ts)151 static void io_poll_tw_hash_eject(struct io_kiocb *req, struct io_tw_state *ts)
152 {
153 	struct io_ring_ctx *ctx = req->ctx;
154 
155 	if (req->flags & REQ_F_HASH_LOCKED) {
156 		/*
157 		 * ->cancel_table_locked is protected by ->uring_lock in
158 		 * contrast to per bucket spinlocks. Likely, tctx_task_work()
159 		 * already grabbed the mutex for us, but there is a chance it
160 		 * failed.
161 		 */
162 		io_tw_lock(ctx, ts);
163 		hash_del(&req->hash_node);
164 		req->flags &= ~REQ_F_HASH_LOCKED;
165 	} else {
166 		io_poll_req_delete(req, ctx);
167 	}
168 }
169 
io_init_poll_iocb(struct io_poll * poll,__poll_t events)170 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events)
171 {
172 	poll->head = NULL;
173 #define IO_POLL_UNMASK	(EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
174 	/* mask in events that we always want/need */
175 	poll->events = events | IO_POLL_UNMASK;
176 	INIT_LIST_HEAD(&poll->wait.entry);
177 	init_waitqueue_func_entry(&poll->wait, io_poll_wake);
178 }
179 
io_poll_remove_entry(struct io_poll * poll)180 static inline void io_poll_remove_entry(struct io_poll *poll)
181 {
182 	struct wait_queue_head *head = smp_load_acquire(&poll->head);
183 
184 	if (head) {
185 		spin_lock_irq(&head->lock);
186 		list_del_init(&poll->wait.entry);
187 		poll->head = NULL;
188 		spin_unlock_irq(&head->lock);
189 	}
190 }
191 
io_poll_remove_entries(struct io_kiocb * req)192 static void io_poll_remove_entries(struct io_kiocb *req)
193 {
194 	/*
195 	 * Nothing to do if neither of those flags are set. Avoid dipping
196 	 * into the poll/apoll/double cachelines if we can.
197 	 */
198 	if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
199 		return;
200 
201 	/*
202 	 * While we hold the waitqueue lock and the waitqueue is nonempty,
203 	 * wake_up_pollfree() will wait for us.  However, taking the waitqueue
204 	 * lock in the first place can race with the waitqueue being freed.
205 	 *
206 	 * We solve this as eventpoll does: by taking advantage of the fact that
207 	 * all users of wake_up_pollfree() will RCU-delay the actual free.  If
208 	 * we enter rcu_read_lock() and see that the pointer to the queue is
209 	 * non-NULL, we can then lock it without the memory being freed out from
210 	 * under us.
211 	 *
212 	 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
213 	 * case the caller deletes the entry from the queue, leaving it empty.
214 	 * In that case, only RCU prevents the queue memory from being freed.
215 	 */
216 	rcu_read_lock();
217 	if (req->flags & REQ_F_SINGLE_POLL)
218 		io_poll_remove_entry(io_poll_get_single(req));
219 	if (req->flags & REQ_F_DOUBLE_POLL)
220 		io_poll_remove_entry(io_poll_get_double(req));
221 	rcu_read_unlock();
222 }
223 
224 enum {
225 	IOU_POLL_DONE = 0,
226 	IOU_POLL_NO_ACTION = 1,
227 	IOU_POLL_REMOVE_POLL_USE_RES = 2,
228 	IOU_POLL_REISSUE = 3,
229 	IOU_POLL_REQUEUE = 4,
230 };
231 
__io_poll_execute(struct io_kiocb * req,int mask)232 static void __io_poll_execute(struct io_kiocb *req, int mask)
233 {
234 	io_req_set_res(req, mask, 0);
235 	req->io_task_work.func = io_poll_task_func;
236 
237 	trace_io_uring_task_add(req, mask);
238 	io_req_task_work_add(req);
239 }
240 
io_poll_execute(struct io_kiocb * req,int res)241 static inline void io_poll_execute(struct io_kiocb *req, int res)
242 {
243 	if (io_poll_get_ownership(req))
244 		__io_poll_execute(req, res);
245 }
246 
247 /*
248  * All poll tw should go through this. Checks for poll events, manages
249  * references, does rewait, etc.
250  *
251  * Returns a negative error on failure. IOU_POLL_NO_ACTION when no action
252  * require, which is either spurious wakeup or multishot CQE is served.
253  * IOU_POLL_DONE when it's done with the request, then the mask is stored in
254  * req->cqe.res. IOU_POLL_REMOVE_POLL_USE_RES indicates to remove multishot
255  * poll and that the result is stored in req->cqe.
256  */
io_poll_check_events(struct io_kiocb * req,struct io_tw_state * ts)257 static int io_poll_check_events(struct io_kiocb *req, struct io_tw_state *ts)
258 {
259 	int v;
260 
261 	/* req->task == current here, checking PF_EXITING is safe */
262 	if (unlikely(req->task->flags & PF_EXITING))
263 		return -ECANCELED;
264 
265 	do {
266 		v = atomic_read(&req->poll_refs);
267 
268 		if (unlikely(v != 1)) {
269 			/* tw should be the owner and so have some refs */
270 			if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
271 				return IOU_POLL_NO_ACTION;
272 			if (v & IO_POLL_CANCEL_FLAG)
273 				return -ECANCELED;
274 			/*
275 			 * cqe.res contains only events of the first wake up
276 			 * and all others are to be lost. Redo vfs_poll() to get
277 			 * up to date state.
278 			 */
279 			if ((v & IO_POLL_REF_MASK) != 1)
280 				req->cqe.res = 0;
281 
282 			if (v & IO_POLL_RETRY_FLAG) {
283 				req->cqe.res = 0;
284 				/*
285 				 * We won't find new events that came in between
286 				 * vfs_poll and the ref put unless we clear the
287 				 * flag in advance.
288 				 */
289 				atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
290 				v &= ~IO_POLL_RETRY_FLAG;
291 			}
292 		}
293 
294 		/* the mask was stashed in __io_poll_execute */
295 		if (!req->cqe.res) {
296 			struct poll_table_struct pt = { ._key = req->apoll_events };
297 			req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
298 			/*
299 			 * We got woken with a mask, but someone else got to
300 			 * it first. The above vfs_poll() doesn't add us back
301 			 * to the waitqueue, so if we get nothing back, we
302 			 * should be safe and attempt a reissue.
303 			 */
304 			if (unlikely(!req->cqe.res)) {
305 				/* Multishot armed need not reissue */
306 				if (!(req->apoll_events & EPOLLONESHOT))
307 					continue;
308 				return IOU_POLL_REISSUE;
309 			}
310 		}
311 		if (req->apoll_events & EPOLLONESHOT)
312 			return IOU_POLL_DONE;
313 
314 		/* multishot, just fill a CQE and proceed */
315 		if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
316 			__poll_t mask = mangle_poll(req->cqe.res &
317 						    req->apoll_events);
318 
319 			if (!io_fill_cqe_req_aux(req, ts->locked, mask,
320 						 IORING_CQE_F_MORE)) {
321 				io_req_set_res(req, mask, 0);
322 				return IOU_POLL_REMOVE_POLL_USE_RES;
323 			}
324 		} else {
325 			int ret = io_poll_issue(req, ts);
326 			if (ret == IOU_STOP_MULTISHOT)
327 				return IOU_POLL_REMOVE_POLL_USE_RES;
328 			else if (ret == IOU_REQUEUE)
329 				return IOU_POLL_REQUEUE;
330 			if (ret < 0)
331 				return ret;
332 		}
333 
334 		/* force the next iteration to vfs_poll() */
335 		req->cqe.res = 0;
336 
337 		/*
338 		 * Release all references, retry if someone tried to restart
339 		 * task_work while we were executing it.
340 		 */
341 	} while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
342 					IO_POLL_REF_MASK);
343 
344 	return IOU_POLL_NO_ACTION;
345 }
346 
io_poll_task_func(struct io_kiocb * req,struct io_tw_state * ts)347 void io_poll_task_func(struct io_kiocb *req, struct io_tw_state *ts)
348 {
349 	int ret;
350 
351 	ret = io_poll_check_events(req, ts);
352 	if (ret == IOU_POLL_NO_ACTION) {
353 		io_kbuf_recycle(req, 0);
354 		return;
355 	} else if (ret == IOU_POLL_REQUEUE) {
356 		io_kbuf_recycle(req, 0);
357 		__io_poll_execute(req, 0);
358 		return;
359 	}
360 	io_poll_remove_entries(req);
361 	io_poll_tw_hash_eject(req, ts);
362 
363 	if (req->opcode == IORING_OP_POLL_ADD) {
364 		if (ret == IOU_POLL_DONE) {
365 			struct io_poll *poll;
366 
367 			poll = io_kiocb_to_cmd(req, struct io_poll);
368 			req->cqe.res = mangle_poll(req->cqe.res & poll->events);
369 		} else if (ret == IOU_POLL_REISSUE) {
370 			io_req_task_submit(req, ts);
371 			return;
372 		} else if (ret != IOU_POLL_REMOVE_POLL_USE_RES) {
373 			req->cqe.res = ret;
374 			req_set_fail(req);
375 		}
376 
377 		io_req_set_res(req, req->cqe.res, 0);
378 		io_req_task_complete(req, ts);
379 	} else {
380 		io_tw_lock(req->ctx, ts);
381 
382 		if (ret == IOU_POLL_REMOVE_POLL_USE_RES)
383 			io_req_task_complete(req, ts);
384 		else if (ret == IOU_POLL_DONE || ret == IOU_POLL_REISSUE)
385 			io_req_task_submit(req, ts);
386 		else
387 			io_req_defer_failed(req, ret);
388 	}
389 }
390 
io_poll_cancel_req(struct io_kiocb * req)391 static void io_poll_cancel_req(struct io_kiocb *req)
392 {
393 	io_poll_mark_cancelled(req);
394 	/* kick tw, which should complete the request */
395 	io_poll_execute(req, 0);
396 }
397 
398 #define IO_ASYNC_POLL_COMMON	(EPOLLONESHOT | EPOLLPRI)
399 
io_pollfree_wake(struct io_kiocb * req,struct io_poll * poll)400 static __cold int io_pollfree_wake(struct io_kiocb *req, struct io_poll *poll)
401 {
402 	io_poll_mark_cancelled(req);
403 	/* we have to kick tw in case it's not already */
404 	io_poll_execute(req, 0);
405 
406 	/*
407 	 * If the waitqueue is being freed early but someone is already
408 	 * holds ownership over it, we have to tear down the request as
409 	 * best we can. That means immediately removing the request from
410 	 * its waitqueue and preventing all further accesses to the
411 	 * waitqueue via the request.
412 	 */
413 	list_del_init(&poll->wait.entry);
414 
415 	/*
416 	 * Careful: this *must* be the last step, since as soon
417 	 * as req->head is NULL'ed out, the request can be
418 	 * completed and freed, since aio_poll_complete_work()
419 	 * will no longer need to take the waitqueue lock.
420 	 */
421 	smp_store_release(&poll->head, NULL);
422 	return 1;
423 }
424 
io_poll_wake(struct wait_queue_entry * wait,unsigned mode,int sync,void * key)425 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
426 			void *key)
427 {
428 	struct io_kiocb *req = wqe_to_req(wait);
429 	struct io_poll *poll = container_of(wait, struct io_poll, wait);
430 	__poll_t mask = key_to_poll(key);
431 
432 	if (unlikely(mask & POLLFREE))
433 		return io_pollfree_wake(req, poll);
434 
435 	/* for instances that support it check for an event match first */
436 	if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
437 		return 0;
438 
439 	if (io_poll_get_ownership(req)) {
440 		/*
441 		 * If we trigger a multishot poll off our own wakeup path,
442 		 * disable multishot as there is a circular dependency between
443 		 * CQ posting and triggering the event.
444 		 */
445 		if (mask & EPOLL_URING_WAKE)
446 			poll->events |= EPOLLONESHOT;
447 
448 		/* optional, saves extra locking for removal in tw handler */
449 		if (mask && poll->events & EPOLLONESHOT) {
450 			list_del_init(&poll->wait.entry);
451 			poll->head = NULL;
452 			if (wqe_is_double(wait))
453 				req->flags &= ~REQ_F_DOUBLE_POLL;
454 			else
455 				req->flags &= ~REQ_F_SINGLE_POLL;
456 		}
457 		__io_poll_execute(req, mask);
458 	}
459 	return 1;
460 }
461 
462 /* fails only when polling is already completing by the first entry */
io_poll_double_prepare(struct io_kiocb * req)463 static bool io_poll_double_prepare(struct io_kiocb *req)
464 {
465 	struct wait_queue_head *head;
466 	struct io_poll *poll = io_poll_get_single(req);
467 
468 	/* head is RCU protected, see io_poll_remove_entries() comments */
469 	rcu_read_lock();
470 	head = smp_load_acquire(&poll->head);
471 	/*
472 	 * poll arm might not hold ownership and so race for req->flags with
473 	 * io_poll_wake(). There is only one poll entry queued, serialise with
474 	 * it by taking its head lock. As we're still arming the tw hanlder
475 	 * is not going to be run, so there are no races with it.
476 	 */
477 	if (head) {
478 		spin_lock_irq(&head->lock);
479 		req->flags |= REQ_F_DOUBLE_POLL;
480 		if (req->opcode == IORING_OP_POLL_ADD)
481 			req->flags |= REQ_F_ASYNC_DATA;
482 		spin_unlock_irq(&head->lock);
483 	}
484 	rcu_read_unlock();
485 	return !!head;
486 }
487 
__io_queue_proc(struct io_poll * poll,struct io_poll_table * pt,struct wait_queue_head * head,struct io_poll ** poll_ptr)488 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
489 			    struct wait_queue_head *head,
490 			    struct io_poll **poll_ptr)
491 {
492 	struct io_kiocb *req = pt->req;
493 	unsigned long wqe_private = (unsigned long) req;
494 
495 	/*
496 	 * The file being polled uses multiple waitqueues for poll handling
497 	 * (e.g. one for read, one for write). Setup a separate io_poll
498 	 * if this happens.
499 	 */
500 	if (unlikely(pt->nr_entries)) {
501 		struct io_poll *first = poll;
502 
503 		/* double add on the same waitqueue head, ignore */
504 		if (first->head == head)
505 			return;
506 		/* already have a 2nd entry, fail a third attempt */
507 		if (*poll_ptr) {
508 			if ((*poll_ptr)->head == head)
509 				return;
510 			pt->error = -EINVAL;
511 			return;
512 		}
513 
514 		poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
515 		if (!poll) {
516 			pt->error = -ENOMEM;
517 			return;
518 		}
519 
520 		/* mark as double wq entry */
521 		wqe_private |= IO_WQE_F_DOUBLE;
522 		io_init_poll_iocb(poll, first->events);
523 		if (!io_poll_double_prepare(req)) {
524 			/* the request is completing, just back off */
525 			kfree(poll);
526 			return;
527 		}
528 		*poll_ptr = poll;
529 	} else {
530 		/* fine to modify, there is no poll queued to race with us */
531 		req->flags |= REQ_F_SINGLE_POLL;
532 	}
533 
534 	pt->nr_entries++;
535 	poll->head = head;
536 	poll->wait.private = (void *) wqe_private;
537 
538 	if (poll->events & EPOLLEXCLUSIVE)
539 		add_wait_queue_exclusive(head, &poll->wait);
540 	else
541 		add_wait_queue(head, &poll->wait);
542 }
543 
io_poll_queue_proc(struct file * file,struct wait_queue_head * head,struct poll_table_struct * p)544 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
545 			       struct poll_table_struct *p)
546 {
547 	struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
548 	struct io_poll *poll = io_kiocb_to_cmd(pt->req, struct io_poll);
549 
550 	__io_queue_proc(poll, pt, head,
551 			(struct io_poll **) &pt->req->async_data);
552 }
553 
io_poll_can_finish_inline(struct io_kiocb * req,struct io_poll_table * pt)554 static bool io_poll_can_finish_inline(struct io_kiocb *req,
555 				      struct io_poll_table *pt)
556 {
557 	return pt->owning || io_poll_get_ownership(req);
558 }
559 
io_poll_add_hash(struct io_kiocb * req)560 static void io_poll_add_hash(struct io_kiocb *req)
561 {
562 	if (req->flags & REQ_F_HASH_LOCKED)
563 		io_poll_req_insert_locked(req);
564 	else
565 		io_poll_req_insert(req);
566 }
567 
568 /*
569  * Returns 0 when it's handed over for polling. The caller owns the requests if
570  * it returns non-zero, but otherwise should not touch it. Negative values
571  * contain an error code. When the result is >0, the polling has completed
572  * inline and ipt.result_mask is set to the mask.
573  */
__io_arm_poll_handler(struct io_kiocb * req,struct io_poll * poll,struct io_poll_table * ipt,__poll_t mask,unsigned issue_flags)574 static int __io_arm_poll_handler(struct io_kiocb *req,
575 				 struct io_poll *poll,
576 				 struct io_poll_table *ipt, __poll_t mask,
577 				 unsigned issue_flags)
578 {
579 	struct io_ring_ctx *ctx = req->ctx;
580 
581 	INIT_HLIST_NODE(&req->hash_node);
582 	req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
583 	io_init_poll_iocb(poll, mask);
584 	poll->file = req->file;
585 	req->apoll_events = poll->events;
586 
587 	ipt->pt._key = mask;
588 	ipt->req = req;
589 	ipt->error = 0;
590 	ipt->nr_entries = 0;
591 	/*
592 	 * Polling is either completed here or via task_work, so if we're in the
593 	 * task context we're naturally serialised with tw by merit of running
594 	 * the same task. When it's io-wq, take the ownership to prevent tw
595 	 * from running. However, when we're in the task context, skip taking
596 	 * it as an optimisation.
597 	 *
598 	 * Note: even though the request won't be completed/freed, without
599 	 * ownership we still can race with io_poll_wake().
600 	 * io_poll_can_finish_inline() tries to deal with that.
601 	 */
602 	ipt->owning = issue_flags & IO_URING_F_UNLOCKED;
603 	atomic_set(&req->poll_refs, (int)ipt->owning);
604 
605 	/* io-wq doesn't hold uring_lock */
606 	if (issue_flags & IO_URING_F_UNLOCKED)
607 		req->flags &= ~REQ_F_HASH_LOCKED;
608 
609 	mask = vfs_poll(req->file, &ipt->pt) & poll->events;
610 
611 	if (unlikely(ipt->error || !ipt->nr_entries)) {
612 		io_poll_remove_entries(req);
613 
614 		if (!io_poll_can_finish_inline(req, ipt)) {
615 			io_poll_mark_cancelled(req);
616 			return 0;
617 		} else if (mask && (poll->events & EPOLLET)) {
618 			ipt->result_mask = mask;
619 			return 1;
620 		}
621 		return ipt->error ?: -EINVAL;
622 	}
623 
624 	if (mask &&
625 	   ((poll->events & (EPOLLET|EPOLLONESHOT)) == (EPOLLET|EPOLLONESHOT))) {
626 		if (!io_poll_can_finish_inline(req, ipt)) {
627 			io_poll_add_hash(req);
628 			return 0;
629 		}
630 		io_poll_remove_entries(req);
631 		ipt->result_mask = mask;
632 		/* no one else has access to the req, forget about the ref */
633 		return 1;
634 	}
635 
636 	io_poll_add_hash(req);
637 
638 	if (mask && (poll->events & EPOLLET) &&
639 	    io_poll_can_finish_inline(req, ipt)) {
640 		__io_poll_execute(req, mask);
641 		return 0;
642 	}
643 
644 	if (ipt->owning) {
645 		/*
646 		 * Try to release ownership. If we see a change of state, e.g.
647 		 * poll was waken up, queue up a tw, it'll deal with it.
648 		 */
649 		if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
650 			__io_poll_execute(req, 0);
651 	}
652 	return 0;
653 }
654 
io_async_queue_proc(struct file * file,struct wait_queue_head * head,struct poll_table_struct * p)655 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
656 			       struct poll_table_struct *p)
657 {
658 	struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
659 	struct async_poll *apoll = pt->req->apoll;
660 
661 	__io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
662 }
663 
664 /*
665  * We can't reliably detect loops in repeated poll triggers and issue
666  * subsequently failing. But rather than fail these immediately, allow a
667  * certain amount of retries before we give up. Given that this condition
668  * should _rarely_ trigger even once, we should be fine with a larger value.
669  */
670 #define APOLL_MAX_RETRY		128
671 
io_req_alloc_apoll(struct io_kiocb * req,unsigned issue_flags)672 static struct async_poll *io_req_alloc_apoll(struct io_kiocb *req,
673 					     unsigned issue_flags)
674 {
675 	struct io_ring_ctx *ctx = req->ctx;
676 	struct io_cache_entry *entry;
677 	struct async_poll *apoll;
678 
679 	if (req->flags & REQ_F_POLLED) {
680 		apoll = req->apoll;
681 		kfree(apoll->double_poll);
682 	} else if (!(issue_flags & IO_URING_F_UNLOCKED)) {
683 		entry = io_alloc_cache_get(&ctx->apoll_cache);
684 		if (entry == NULL)
685 			goto alloc_apoll;
686 		apoll = container_of(entry, struct async_poll, cache);
687 		apoll->poll.retries = APOLL_MAX_RETRY;
688 	} else {
689 alloc_apoll:
690 		apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
691 		if (unlikely(!apoll))
692 			return NULL;
693 		apoll->poll.retries = APOLL_MAX_RETRY;
694 	}
695 	apoll->double_poll = NULL;
696 	req->apoll = apoll;
697 	if (unlikely(!--apoll->poll.retries))
698 		return NULL;
699 	return apoll;
700 }
701 
io_arm_poll_handler(struct io_kiocb * req,unsigned issue_flags)702 int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
703 {
704 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
705 	struct async_poll *apoll;
706 	struct io_poll_table ipt;
707 	__poll_t mask = POLLPRI | POLLERR | EPOLLET;
708 	int ret;
709 
710 	/*
711 	 * apoll requests already grab the mutex to complete in the tw handler,
712 	 * so removal from the mutex-backed hash is free, use it by default.
713 	 */
714 	req->flags |= REQ_F_HASH_LOCKED;
715 
716 	if (!def->pollin && !def->pollout)
717 		return IO_APOLL_ABORTED;
718 	if (!io_file_can_poll(req))
719 		return IO_APOLL_ABORTED;
720 	if (!(req->flags & REQ_F_APOLL_MULTISHOT))
721 		mask |= EPOLLONESHOT;
722 
723 	if (def->pollin) {
724 		mask |= EPOLLIN | EPOLLRDNORM;
725 
726 		/* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
727 		if (req->flags & REQ_F_CLEAR_POLLIN)
728 			mask &= ~EPOLLIN;
729 	} else {
730 		mask |= EPOLLOUT | EPOLLWRNORM;
731 	}
732 	if (def->poll_exclusive)
733 		mask |= EPOLLEXCLUSIVE;
734 
735 	apoll = io_req_alloc_apoll(req, issue_flags);
736 	if (!apoll)
737 		return IO_APOLL_ABORTED;
738 	req->flags &= ~(REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL);
739 	req->flags |= REQ_F_POLLED;
740 	ipt.pt._qproc = io_async_queue_proc;
741 
742 	io_kbuf_recycle(req, issue_flags);
743 
744 	ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask, issue_flags);
745 	if (ret)
746 		return ret > 0 ? IO_APOLL_READY : IO_APOLL_ABORTED;
747 	trace_io_uring_poll_arm(req, mask, apoll->poll.events);
748 	return IO_APOLL_OK;
749 }
750 
io_poll_remove_all_table(struct task_struct * tsk,struct io_hash_table * table,bool cancel_all)751 static __cold bool io_poll_remove_all_table(struct task_struct *tsk,
752 					    struct io_hash_table *table,
753 					    bool cancel_all)
754 {
755 	unsigned nr_buckets = 1U << table->hash_bits;
756 	struct hlist_node *tmp;
757 	struct io_kiocb *req;
758 	bool found = false;
759 	int i;
760 
761 	for (i = 0; i < nr_buckets; i++) {
762 		struct io_hash_bucket *hb = &table->hbs[i];
763 
764 		spin_lock(&hb->lock);
765 		hlist_for_each_entry_safe(req, tmp, &hb->list, hash_node) {
766 			if (io_match_task_safe(req, tsk, cancel_all)) {
767 				hlist_del_init(&req->hash_node);
768 				io_poll_cancel_req(req);
769 				found = true;
770 			}
771 		}
772 		spin_unlock(&hb->lock);
773 	}
774 	return found;
775 }
776 
777 /*
778  * Returns true if we found and killed one or more poll requests
779  */
io_poll_remove_all(struct io_ring_ctx * ctx,struct task_struct * tsk,bool cancel_all)780 __cold bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
781 			       bool cancel_all)
782 	__must_hold(&ctx->uring_lock)
783 {
784 	bool ret;
785 
786 	ret = io_poll_remove_all_table(tsk, &ctx->cancel_table, cancel_all);
787 	ret |= io_poll_remove_all_table(tsk, &ctx->cancel_table_locked, cancel_all);
788 	return ret;
789 }
790 
io_poll_find(struct io_ring_ctx * ctx,bool poll_only,struct io_cancel_data * cd,struct io_hash_table * table,struct io_hash_bucket ** out_bucket)791 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
792 				     struct io_cancel_data *cd,
793 				     struct io_hash_table *table,
794 				     struct io_hash_bucket **out_bucket)
795 {
796 	struct io_kiocb *req;
797 	u32 index = hash_long(cd->data, table->hash_bits);
798 	struct io_hash_bucket *hb = &table->hbs[index];
799 
800 	*out_bucket = NULL;
801 
802 	spin_lock(&hb->lock);
803 	hlist_for_each_entry(req, &hb->list, hash_node) {
804 		if (cd->data != req->cqe.user_data)
805 			continue;
806 		if (poll_only && req->opcode != IORING_OP_POLL_ADD)
807 			continue;
808 		if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
809 			if (cd->seq == req->work.cancel_seq)
810 				continue;
811 			req->work.cancel_seq = cd->seq;
812 		}
813 		*out_bucket = hb;
814 		return req;
815 	}
816 	spin_unlock(&hb->lock);
817 	return NULL;
818 }
819 
io_poll_file_find(struct io_ring_ctx * ctx,struct io_cancel_data * cd,struct io_hash_table * table,struct io_hash_bucket ** out_bucket)820 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
821 					  struct io_cancel_data *cd,
822 					  struct io_hash_table *table,
823 					  struct io_hash_bucket **out_bucket)
824 {
825 	unsigned nr_buckets = 1U << table->hash_bits;
826 	struct io_kiocb *req;
827 	int i;
828 
829 	*out_bucket = NULL;
830 
831 	for (i = 0; i < nr_buckets; i++) {
832 		struct io_hash_bucket *hb = &table->hbs[i];
833 
834 		spin_lock(&hb->lock);
835 		hlist_for_each_entry(req, &hb->list, hash_node) {
836 			if (io_cancel_req_match(req, cd)) {
837 				*out_bucket = hb;
838 				return req;
839 			}
840 		}
841 		spin_unlock(&hb->lock);
842 	}
843 	return NULL;
844 }
845 
io_poll_disarm(struct io_kiocb * req)846 static int io_poll_disarm(struct io_kiocb *req)
847 {
848 	if (!req)
849 		return -ENOENT;
850 	if (!io_poll_get_ownership(req))
851 		return -EALREADY;
852 	io_poll_remove_entries(req);
853 	hash_del(&req->hash_node);
854 	return 0;
855 }
856 
__io_poll_cancel(struct io_ring_ctx * ctx,struct io_cancel_data * cd,struct io_hash_table * table)857 static int __io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd,
858 			    struct io_hash_table *table)
859 {
860 	struct io_hash_bucket *bucket;
861 	struct io_kiocb *req;
862 
863 	if (cd->flags & (IORING_ASYNC_CANCEL_FD | IORING_ASYNC_CANCEL_OP |
864 			 IORING_ASYNC_CANCEL_ANY))
865 		req = io_poll_file_find(ctx, cd, table, &bucket);
866 	else
867 		req = io_poll_find(ctx, false, cd, table, &bucket);
868 
869 	if (req)
870 		io_poll_cancel_req(req);
871 	if (bucket)
872 		spin_unlock(&bucket->lock);
873 	return req ? 0 : -ENOENT;
874 }
875 
io_poll_cancel(struct io_ring_ctx * ctx,struct io_cancel_data * cd,unsigned issue_flags)876 int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd,
877 		   unsigned issue_flags)
878 {
879 	int ret;
880 
881 	ret = __io_poll_cancel(ctx, cd, &ctx->cancel_table);
882 	if (ret != -ENOENT)
883 		return ret;
884 
885 	io_ring_submit_lock(ctx, issue_flags);
886 	ret = __io_poll_cancel(ctx, cd, &ctx->cancel_table_locked);
887 	io_ring_submit_unlock(ctx, issue_flags);
888 	return ret;
889 }
890 
io_poll_parse_events(const struct io_uring_sqe * sqe,unsigned int flags)891 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
892 				     unsigned int flags)
893 {
894 	u32 events;
895 
896 	events = READ_ONCE(sqe->poll32_events);
897 #ifdef __BIG_ENDIAN
898 	events = swahw32(events);
899 #endif
900 	if (!(flags & IORING_POLL_ADD_MULTI))
901 		events |= EPOLLONESHOT;
902 	if (!(flags & IORING_POLL_ADD_LEVEL))
903 		events |= EPOLLET;
904 	return demangle_poll(events) |
905 		(events & (EPOLLEXCLUSIVE|EPOLLONESHOT|EPOLLET));
906 }
907 
io_poll_remove_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)908 int io_poll_remove_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
909 {
910 	struct io_poll_update *upd = io_kiocb_to_cmd(req, struct io_poll_update);
911 	u32 flags;
912 
913 	if (sqe->buf_index || sqe->splice_fd_in)
914 		return -EINVAL;
915 	flags = READ_ONCE(sqe->len);
916 	if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
917 		      IORING_POLL_ADD_MULTI))
918 		return -EINVAL;
919 	/* meaningless without update */
920 	if (flags == IORING_POLL_ADD_MULTI)
921 		return -EINVAL;
922 
923 	upd->old_user_data = READ_ONCE(sqe->addr);
924 	upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
925 	upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
926 
927 	upd->new_user_data = READ_ONCE(sqe->off);
928 	if (!upd->update_user_data && upd->new_user_data)
929 		return -EINVAL;
930 	if (upd->update_events)
931 		upd->events = io_poll_parse_events(sqe, flags);
932 	else if (sqe->poll32_events)
933 		return -EINVAL;
934 
935 	return 0;
936 }
937 
io_poll_add_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)938 int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
939 {
940 	struct io_poll *poll = io_kiocb_to_cmd(req, struct io_poll);
941 	u32 flags;
942 
943 	if (sqe->buf_index || sqe->off || sqe->addr)
944 		return -EINVAL;
945 	flags = READ_ONCE(sqe->len);
946 	if (flags & ~IORING_POLL_ADD_MULTI)
947 		return -EINVAL;
948 	if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
949 		return -EINVAL;
950 
951 	poll->events = io_poll_parse_events(sqe, flags);
952 	return 0;
953 }
954 
io_poll_add(struct io_kiocb * req,unsigned int issue_flags)955 int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
956 {
957 	struct io_poll *poll = io_kiocb_to_cmd(req, struct io_poll);
958 	struct io_poll_table ipt;
959 	int ret;
960 
961 	ipt.pt._qproc = io_poll_queue_proc;
962 
963 	/*
964 	 * If sqpoll or single issuer, there is no contention for ->uring_lock
965 	 * and we'll end up holding it in tw handlers anyway.
966 	 */
967 	if (req->ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_SINGLE_ISSUER))
968 		req->flags |= REQ_F_HASH_LOCKED;
969 
970 	ret = __io_arm_poll_handler(req, poll, &ipt, poll->events, issue_flags);
971 	if (ret > 0) {
972 		io_req_set_res(req, ipt.result_mask, 0);
973 		return IOU_OK;
974 	}
975 	return ret ?: IOU_ISSUE_SKIP_COMPLETE;
976 }
977 
io_poll_remove(struct io_kiocb * req,unsigned int issue_flags)978 int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
979 {
980 	struct io_poll_update *poll_update = io_kiocb_to_cmd(req, struct io_poll_update);
981 	struct io_ring_ctx *ctx = req->ctx;
982 	struct io_cancel_data cd = { .ctx = ctx, .data = poll_update->old_user_data, };
983 	struct io_hash_bucket *bucket;
984 	struct io_kiocb *preq;
985 	int ret2, ret = 0;
986 
987 	io_ring_submit_lock(ctx, issue_flags);
988 	preq = io_poll_find(ctx, true, &cd, &ctx->cancel_table, &bucket);
989 	ret2 = io_poll_disarm(preq);
990 	if (bucket)
991 		spin_unlock(&bucket->lock);
992 	if (!ret2)
993 		goto found;
994 	if (ret2 != -ENOENT) {
995 		ret = ret2;
996 		goto out;
997 	}
998 
999 	preq = io_poll_find(ctx, true, &cd, &ctx->cancel_table_locked, &bucket);
1000 	ret2 = io_poll_disarm(preq);
1001 	if (bucket)
1002 		spin_unlock(&bucket->lock);
1003 	if (ret2) {
1004 		ret = ret2;
1005 		goto out;
1006 	}
1007 
1008 found:
1009 	if (WARN_ON_ONCE(preq->opcode != IORING_OP_POLL_ADD)) {
1010 		ret = -EFAULT;
1011 		goto out;
1012 	}
1013 
1014 	if (poll_update->update_events || poll_update->update_user_data) {
1015 		/* only mask one event flags, keep behavior flags */
1016 		if (poll_update->update_events) {
1017 			struct io_poll *poll = io_kiocb_to_cmd(preq, struct io_poll);
1018 
1019 			poll->events &= ~0xffff;
1020 			poll->events |= poll_update->events & 0xffff;
1021 			poll->events |= IO_POLL_UNMASK;
1022 		}
1023 		if (poll_update->update_user_data)
1024 			preq->cqe.user_data = poll_update->new_user_data;
1025 
1026 		ret2 = io_poll_add(preq, issue_flags & ~IO_URING_F_UNLOCKED);
1027 		/* successfully updated, don't complete poll request */
1028 		if (!ret2 || ret2 == -EIOCBQUEUED)
1029 			goto out;
1030 	}
1031 
1032 	req_set_fail(preq);
1033 	io_req_set_res(preq, -ECANCELED, 0);
1034 	preq->io_task_work.func = io_req_task_complete;
1035 	io_req_task_work_add(preq);
1036 out:
1037 	io_ring_submit_unlock(ctx, issue_flags);
1038 	if (ret < 0) {
1039 		req_set_fail(req);
1040 		return ret;
1041 	}
1042 	/* complete update request, we're done with it */
1043 	io_req_set_res(req, ret, 0);
1044 	return IOU_OK;
1045 }
1046 
io_apoll_cache_free(struct io_cache_entry * entry)1047 void io_apoll_cache_free(struct io_cache_entry *entry)
1048 {
1049 	kfree(container_of(entry, struct async_poll, cache));
1050 }
1051