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