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