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