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